@teambit/preview 0.0.770 → 0.0.773

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/bundler/chunks.ts +51 -0
  2. package/bundler/html-plugin.ts +24 -0
  3. package/{webpack/html.ts → bundler/html-template.ts} +0 -0
  4. package/dist/bundler/chunks.d.ts +17 -0
  5. package/dist/bundler/chunks.js +68 -0
  6. package/dist/bundler/chunks.js.map +1 -0
  7. package/dist/bundler/html-plugin.d.ts +5 -0
  8. package/dist/bundler/html-plugin.js +56 -0
  9. package/dist/bundler/html-plugin.js.map +1 -0
  10. package/dist/{webpack/html.d.ts → bundler/html-template.d.ts} +0 -0
  11. package/dist/{webpack/html.js → bundler/html-template.js} +1 -1
  12. package/dist/bundler/html-template.js.map +1 -0
  13. package/dist/env-preview-template.task.d.ts +4 -9
  14. package/dist/env-preview-template.task.js +64 -74
  15. package/dist/env-preview-template.task.js.map +1 -1
  16. package/dist/preview-modules.d.ts +10 -0
  17. package/dist/preview-modules.js +54 -0
  18. package/dist/preview-modules.js.map +1 -0
  19. package/dist/preview.preview.runtime.d.ts +8 -5
  20. package/dist/preview.preview.runtime.js +76 -43
  21. package/dist/preview.preview.runtime.js.map +1 -1
  22. package/dist/strategies/component-strategy.js +6 -4
  23. package/dist/strategies/component-strategy.js.map +1 -1
  24. package/dist/strategies/env-strategy.js +4 -4
  25. package/dist/strategies/env-strategy.js.map +1 -1
  26. package/dist/strategies/generate-component-link.js +27 -3
  27. package/dist/strategies/generate-component-link.js.map +1 -1
  28. package/package-tar/teambit-preview-0.0.773.tgz +0 -0
  29. package/package.json +23 -21
  30. package/preview-1656386921357.js +5 -0
  31. package/preview-modules.tsx +28 -0
  32. package/preview.preview.runtime.tsx +71 -51
  33. package/strategies/component-strategy.ts +3 -3
  34. package/strategies/env-strategy.ts +1 -1
  35. package/strategies/generate-component-link.ts +20 -8
  36. package/dist/webpack/html.js.map +0 -1
  37. package/dist/webpack/index.d.ts +0 -1
  38. package/dist/webpack/index.js +0 -23
  39. package/dist/webpack/index.js.map +0 -1
  40. package/package-tar/teambit-preview-0.0.770.tgz +0 -0
  41. package/preview-1656041300679.js +0 -2
  42. package/webpack/index.ts +0 -1
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ require("core-js/modules/es.array.iterator.js");
6
+
7
+ Object.defineProperty(exports, "__esModule", {
8
+ value: true
9
+ });
10
+ exports.PreviewModules = exports.PREVIEW_MODULES = void 0;
11
+ exports.linkModules = linkModules;
12
+
13
+ function _defineProperty2() {
14
+ const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
15
+
16
+ _defineProperty2 = function () {
17
+ return data;
18
+ };
19
+
20
+ return data;
21
+ }
22
+
23
+ class PreviewModules extends Map {
24
+ constructor(...args) {
25
+ super(...args);
26
+ (0, _defineProperty2().default)(this, "onSet", new Set());
27
+ }
28
+
29
+ set(id, preview) {
30
+ super.set(id, preview);
31
+ this.onSet.forEach(callback => callback());
32
+ return this;
33
+ }
34
+
35
+ loadComponentPreviews(compId, previews) {
36
+ Object.entries(previews).forEach(([previewName, moduleFile]) => {
37
+ const preview = this.get(previewName);
38
+ if (!preview) return; // TODO - ok for now
39
+
40
+ preview.componentMap[compId] = moduleFile;
41
+ });
42
+ }
43
+
44
+ }
45
+
46
+ exports.PreviewModules = PreviewModules;
47
+ const PREVIEW_MODULES = new PreviewModules();
48
+ exports.PREVIEW_MODULES = PREVIEW_MODULES;
49
+
50
+ function linkModules(previewName, previewModule) {
51
+ PREVIEW_MODULES.set(previewName, previewModule);
52
+ }
53
+
54
+ //# sourceMappingURL=preview-modules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["PreviewModules","Map","Set","set","id","preview","onSet","forEach","callback","loadComponentPreviews","compId","previews","Object","entries","previewName","moduleFile","get","componentMap","PREVIEW_MODULES","linkModules","previewModule"],"sources":["preview-modules.tsx"],"sourcesContent":["import type { PreviewModule, ModuleFile } from './types/preview-module';\n\ntype ModuleId = string;\n\nexport class PreviewModules extends Map<ModuleId, PreviewModule> {\n onSet = new Set<() => void>();\n\n override set(id: ModuleId, preview: PreviewModule) {\n super.set(id, preview);\n this.onSet.forEach((callback) => callback());\n return this;\n }\n\n loadComponentPreviews(compId: string, previews: Record<string, ModuleFile[]>) {\n Object.entries(previews).forEach(([previewName, moduleFile]) => {\n const preview = this.get(previewName);\n if (!preview) return; // TODO - ok for now\n\n preview.componentMap[compId] = moduleFile;\n });\n }\n}\n\nexport const PREVIEW_MODULES = new PreviewModules();\n\nexport function linkModules(previewName: string, previewModule: PreviewModule) {\n PREVIEW_MODULES.set(previewName, previewModule);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIO,MAAMA,cAAN,SAA6BC,GAA7B,CAA0D;EAAA;IAAA;IAAA,+CACvD,IAAIC,GAAJ,EADuD;EAAA;;EAGtDC,GAAG,CAACC,EAAD,EAAeC,OAAf,EAAuC;IACjD,MAAMF,GAAN,CAAUC,EAAV,EAAcC,OAAd;IACA,KAAKC,KAAL,CAAWC,OAAX,CAAoBC,QAAD,IAAcA,QAAQ,EAAzC;IACA,OAAO,IAAP;EACD;;EAEDC,qBAAqB,CAACC,MAAD,EAAiBC,QAAjB,EAAyD;IAC5EC,MAAM,CAACC,OAAP,CAAeF,QAAf,EAAyBJ,OAAzB,CAAiC,CAAC,CAACO,WAAD,EAAcC,UAAd,CAAD,KAA+B;MAC9D,MAAMV,OAAO,GAAG,KAAKW,GAAL,CAASF,WAAT,CAAhB;MACA,IAAI,CAACT,OAAL,EAAc,OAFgD,CAExC;;MAEtBA,OAAO,CAACY,YAAR,CAAqBP,MAArB,IAA+BK,UAA/B;IACD,CALD;EAMD;;AAhB8D;;;AAmB1D,MAAMG,eAAe,GAAG,IAAIlB,cAAJ,EAAxB;;;AAEA,SAASmB,WAAT,CAAqBL,WAArB,EAA0CM,aAA1C,EAAwE;EAC7EF,eAAe,CAACf,GAAhB,CAAoBW,WAApB,EAAiCM,aAAjC;AACD"}
@@ -2,8 +2,9 @@ import { PubsubPreview } from '@teambit/pubsub';
2
2
  import { SlotRegistry } from '@teambit/harmony';
3
3
  import { ComponentID } from '@teambit/component-id';
4
4
  import { PreviewType } from './preview-type';
5
- import { PreviewModule } from './types/preview-module';
5
+ import { ModuleFile, PreviewModule } from './types/preview-module';
6
6
  import { RenderingContext } from './rendering-context';
7
+ export { linkModules } from './preview-modules';
7
8
  export declare type PreviewSlot = SlotRegistry<PreviewType>;
8
9
  export declare type RenderingContextOptions = {
9
10
  aspectsFilter?: string[];
@@ -33,17 +34,20 @@ export declare class PreviewPreview {
33
34
  previewSlot: PreviewSlot, renderingContextSlot: RenderingContextSlot);
34
35
  private registerClickPubSub;
35
36
  private isDev;
37
+ private isReady;
38
+ private _setupPromise?;
39
+ setup: () => Promise<void>;
36
40
  /**
37
41
  * render the preview.
38
42
  */
39
43
  render: (rootExt?: string | undefined) => Promise<void>;
40
- getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule>;
41
- fetchComponentPreview(id: ComponentID, name: string): Promise<unknown>;
44
+ getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule>;
45
+ fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>>;
42
46
  private addComponentFileElement;
43
47
  private fetchComponentPreviewFiles;
44
48
  private addComponentFileScriptElement;
45
49
  private addComponentFileLinkElement;
46
- private getPreviewScriptElement;
50
+ private loadPreviewScript;
47
51
  private getComponentAspects;
48
52
  /**
49
53
  * register a new preview.
@@ -67,4 +71,3 @@ export declare class PreviewPreview {
67
71
  static slots: (((registerFn: () => string) => SlotRegistry<PreviewType>) | ((registerFn: () => string) => SlotRegistry<RenderingContextProvider>))[];
68
72
  static provider([pubsub]: [PubsubPreview], config: any, [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]): Promise<PreviewPreview>;
69
73
  }
70
- export declare function linkModules(previewName: string, previewModule: PreviewModule): void;
@@ -14,7 +14,12 @@ Object.defineProperty(exports, "__esModule", {
14
14
  value: true
15
15
  });
16
16
  exports.PreviewPreview = void 0;
17
- exports.linkModules = linkModules;
17
+ Object.defineProperty(exports, "linkModules", {
18
+ enumerable: true,
19
+ get: function () {
20
+ return _previewModules().linkModules;
21
+ }
22
+ });
18
23
 
19
24
  function _defineProperty2() {
20
25
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
@@ -126,8 +131,17 @@ function _fetchComponentAspects() {
126
131
  return data;
127
132
  }
128
133
 
129
- const PREVIEW_MODULES = {};
134
+ function _previewModules() {
135
+ const data = require("./preview-modules");
136
+
137
+ _previewModules = function () {
138
+ return data;
139
+ };
140
+
141
+ return data;
142
+ }
130
143
 
144
+ // forward linkModules() for generate-link.ts
131
145
  class PreviewPreview {
132
146
  constructor(
133
147
  /**
@@ -142,6 +156,18 @@ class PreviewPreview {
142
156
  this.previewSlot = previewSlot;
143
157
  this.renderingContextSlot = renderingContextSlot;
144
158
  (0, _defineProperty2().default)(this, "isDev", false);
159
+ (0, _defineProperty2().default)(this, "_setupPromise", void 0);
160
+ (0, _defineProperty2().default)(this, "setup", () => {
161
+ var _this$_setupPromise;
162
+
163
+ if (this.isReady()) return Promise.resolve();
164
+ (_this$_setupPromise = this._setupPromise) !== null && _this$_setupPromise !== void 0 ? _this$_setupPromise : this._setupPromise = new Promise(resolve => {
165
+ _previewModules().PREVIEW_MODULES.onSet.add(() => {
166
+ if (this.isReady()) resolve();
167
+ });
168
+ });
169
+ return this._setupPromise;
170
+ });
145
171
  (0, _defineProperty2().default)(this, "render", async rootExt => {
146
172
  const {
147
173
  previewName,
@@ -155,12 +181,13 @@ class PreviewPreview {
155
181
  throw new (_exceptions().PreviewNotFound)(previewName);
156
182
  }
157
183
 
158
- const includesAll = await Promise.all((preview.include || []).map(async prevName => {
184
+ const includesAll = await Promise.all((preview.include || []).map(async inclPreviewName => {
159
185
  var _includedPreview$sele;
160
186
 
161
- const includedPreview = this.getPreview(prevName);
187
+ const includedPreview = this.getPreview(inclPreviewName);
162
188
  if (!includedPreview) return undefined;
163
- return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, await this.getPreviewModule(prevName, componentId, name));
189
+ const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);
190
+ return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, inclPreviewModule);
164
191
  }));
165
192
  const includes = includesAll.filter(module => !!module); // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
166
193
 
@@ -182,18 +209,33 @@ class PreviewPreview {
182
209
  });
183
210
  }
184
211
 
185
- async getPreviewModule(name, id, parentPreviewName) {
186
- const relevantModel = PREVIEW_MODULES[name];
187
- if (relevantModel.componentMap[id.fullName]) return relevantModel;
188
- let component; // Handle case when there is overview but no composition on the workspace dev server
212
+ isReady() {
213
+ var _preview$include$ever, _preview$include;
214
+
215
+ const {
216
+ previewName
217
+ } = this.getLocation();
218
+ const name = previewName || this.getDefault();
219
+ if (!_previewModules().PREVIEW_MODULES.has(name)) return false;
220
+ const preview = this.getPreview(name);
221
+ if (!preview) return false;
222
+ const includedReady = (_preview$include$ever = (_preview$include = preview.include) === null || _preview$include === void 0 ? void 0 : _preview$include.every(included => _previewModules().PREVIEW_MODULES.has(included))) !== null && _preview$include$ever !== void 0 ? _preview$include$ever : true;
223
+ if (!includedReady) return false;
224
+ return true;
225
+ }
189
226
 
190
- if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {
191
- // if (!window[name]) throw new PreviewNotFound(name);
192
- // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;
193
- // const component = window[id.toStringWithoutVersion()];
194
- component = await this.fetchComponentPreview(id, name);
195
- }
227
+ async getPreviewModule(previewName, id) {
228
+ const compShortId = id.fullName;
229
+
230
+ const relevantModel = _previewModules().PREVIEW_MODULES.get(previewName);
231
+
232
+ if (!relevantModel) throw new Error(`[preview.preview] missing preview "${previewName}"`);
233
+ if (relevantModel.componentMap[compShortId]) return relevantModel;
234
+ const componentPreviews = await this.fetchComponentPreview(id, previewName);
235
+
236
+ _previewModules().PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);
196
237
 
238
+ const component = componentPreviews[previewName];
197
239
  return {
198
240
  mainModule: relevantModel.mainModule,
199
241
  componentMap: {
@@ -206,10 +248,7 @@ class PreviewPreview {
206
248
  let previewFile;
207
249
  const allFiles = await this.fetchComponentPreviewFiles(id, name); // It's a component bundled with the env
208
250
 
209
- if (allFiles === null) {
210
- return Promise.resolve(undefined);
211
- }
212
-
251
+ if (allFiles === null) return {};
213
252
  allFiles.forEach(file => {
214
253
  // We want to run the preview file always last
215
254
  if (file.endsWith('-preview.js')) {
@@ -218,10 +257,8 @@ class PreviewPreview {
218
257
  this.addComponentFileElement(id, file);
219
258
  }
220
259
  });
221
- return new Promise((resolve, reject) => {
222
- const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);
223
- document.head.appendChild(previewScriptElement);
224
- });
260
+ if (!previewFile) return {};
261
+ return this.loadPreviewScript(id, name, previewFile);
225
262
  }
226
263
 
227
264
  addComponentFileElement(id, previewBundleFileName) {
@@ -281,24 +318,24 @@ class PreviewPreview {
281
318
  return link;
282
319
  }
283
320
 
284
- getPreviewScriptElement(id, name, previewBundleFileName, resolve, reject) {
285
- const script = document.createElement('script');
286
- script.setAttribute('defer', 'defer');
287
- const stringId = id.toString(); // const previewRoute = `~aspect/preview`;
321
+ async loadPreviewScript(id, previewName, previewBundleFileName) {
322
+ await new Promise((resolve, reject) => {
323
+ const script = document.createElement('script');
324
+ const previewRoute = `~aspect/component-preview`;
325
+ const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;
326
+ script.src = src;
327
+ script.setAttribute('defer', 'defer');
288
328
 
289
- const previewRoute = `~aspect/component-preview`;
290
- const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
291
- script.src = src; // generate path to remote scope. [scope url]/
292
-
293
- script.onload = () => {
294
- const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];
295
- if (!componentPreview) return reject(new (_exceptions().PreviewNotFound)(name));
296
- const targetPreview = componentPreview[name];
297
- if (!targetPreview) return resolve(undefined);
298
- return resolve(targetPreview);
299
- };
329
+ script.onload = () => resolve();
300
330
 
301
- return script;
331
+ script.onerror = (message, _, _1, _2, error) => reject(error || new Error(`[preview.preview] failed to load preview script: ${message}`));
332
+
333
+ document.head.appendChild(script);
334
+ });
335
+ const globalId = `${id.toStringWithoutVersion()}-preview`;
336
+ const componentPreview = window[globalId];
337
+ if (!componentPreview) throw new (_exceptions().PreviewNotFound)(previewName);
338
+ return componentPreview;
302
339
  }
303
340
 
304
341
  /**
@@ -371,10 +408,6 @@ exports.PreviewPreview = PreviewPreview;
371
408
  (0, _defineProperty2().default)(PreviewPreview, "dependencies", [_pubsub().default]);
372
409
  (0, _defineProperty2().default)(PreviewPreview, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType()]);
373
410
 
374
- function linkModules(previewName, previewModule) {
375
- PREVIEW_MODULES[previewName] = previewModule;
376
- }
377
-
378
411
  _preview().PreviewAspect.addRuntime(PreviewPreview);
379
412
 
380
413
  //# sourceMappingURL=preview.preview.runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["PREVIEW_MODULES","PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","Promise","all","include","map","prevName","includedPreview","undefined","selectPreviewModel","fullName","getPreviewModule","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","parentPreviewName","relevantModel","componentMap","component","fetchComponentPreview","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","resolve","forEach","file","endsWith","addComponentFileElement","reject","previewScriptElement","getPreviewScriptElement","document","head","appendChild","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","script","createElement","setAttribute","previewRoute","src","link","href","onload","componentPreview","toStringWithoutVersion","targetPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","get","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","linkModules","previewModule","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nconst PREVIEW_MODULES: Record<string, PreviewModule> = {};\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (prevName) => {\n const includedPreview = this.getPreview(prevName);\n if (!includedPreview) return undefined;\n\n return includedPreview.selectPreviewModel?.(\n componentId.fullName,\n await this.getPreviewModule(prevName, componentId, name)\n );\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule> {\n const relevantModel = PREVIEW_MODULES[name];\n if (relevantModel.componentMap[id.fullName]) return relevantModel;\n\n let component;\n // Handle case when there is overview but no composition on the workspace dev server\n if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {\n // if (!window[name]) throw new PreviewNotFound(name);\n // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;\n // const component = window[id.toStringWithoutVersion()];\n component = await this.fetchComponentPreview(id, name);\n }\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string) {\n let previewFile;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) {\n return Promise.resolve(undefined);\n }\n allFiles.forEach((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n } else {\n this.addComponentFileElement(id, file);\n }\n });\n return new Promise((resolve, reject) => {\n const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);\n document.head.appendChild(previewScriptElement);\n });\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n document.head.appendChild(script);\n return script;\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const link = document.createElement('link');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n link.setAttribute('href', href);\n if (previewBundleFileName.endsWith('.css')) {\n link.setAttribute('rel', 'stylesheet');\n }\n document.head.appendChild(link);\n return link;\n }\n\n private getPreviewScriptElement(id: ComponentID, name: string, previewBundleFileName: string, resolve, reject) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n // const previewRoute = `~aspect/preview`;\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src; // generate path to remote scope. [scope url]/\n script.onload = () => {\n const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];\n if (!componentPreview) return reject(new PreviewNotFound(name));\n const targetPreview = componentPreview[name];\n if (!targetPreview) return resolve(undefined);\n\n return resolve(targetPreview);\n };\n return script;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nexport function linkModules(previewName: string, previewModule: PreviewModule) {\n PREVIEW_MODULES[previewName] = previewModule;\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIA,MAAMA,eAA8C,GAAG,EAAvD;;AAMO,MAAMC,cAAN,CAAqB;EAC1BC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,WATC,EAWDC,oBAXC,EAYT;IAAA,KARQF,MAQR,GARQA,MAQR;IAAA,KAHQC,WAGR,GAHQA,WAGR;IAAA,KADQC,oBACR,GADQA,oBACR;IAAA,+CAYc,KAZd;IAAA,gDAiBO,MAAOC,OAAP,IAA4B;MACnC,MAAM;QAAEC,WAAF;QAAeC;MAAf,IAA+B,KAAKC,WAAL,EAArC;MACA,MAAMC,IAAI,GAAGH,WAAW,IAAI,KAAKI,UAAL,EAA5B;MACA,IAAIL,OAAJ,EAAa,KAAKM,KAAL,GAAaN,OAAO,KAAK,6BAAzB;MAEb,MAAMO,OAAO,GAAG,KAAKC,UAAL,CAAg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B;IACA,MAAMQ,OAAO,GAAG,IAAIZ,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEAmC,MAAM,CAACC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA5B,OAAO,CAACoB,MAAR;IACD,CAHD;IAKA,OAAOpB,OAAP;EACD;;AA7PyB;;;gCAAfZ,c,aA0OM8H,yB;gCA1ON9H,c,kBA4OW,CAAC+H,iBAAD,C;gCA5OX/H,c,WA8OI,CAACgI,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBV,SAASC,WAAT,CAAqB5H,WAArB,EAA0C6H,aAA1C,EAAwE;EAC7EpI,eAAe,CAACO,WAAD,CAAf,GAA+B6H,aAA/B;AACD;;AAEDlF,wBAAA,CAAcmF,UAAd,CAAyBpI,cAAzB"}
1
+ {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","forEach","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","script","document","createElement","setAttribute","previewRoute","src","head","appendChild","link","href","reject","onload","onerror","message","_","_1","_2","error","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n allFiles.forEach((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n } else {\n this.addComponentFileElement(id, file);\n }\n });\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n document.head.appendChild(script);\n return script;\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const link = document.createElement('link');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n link.setAttribute('href', href);\n if (previewBundleFileName.endsWith('.css')) {\n link.setAttribute('rel', 'stylesheet');\n }\n document.head.appendChild(link);\n return link;\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n await new Promise<void>((resolve, reject) => {\n const script = document.createElement('script');\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n script.setAttribute('defer', 'defer');\n script.onload = () => resolve();\n script.onerror = (message, _, _1, _2, error) =>\n reject(error || new Error(`[preview.preview] failed to load preview script: ${message}`));\n document.head.appendChild(script);\n });\n\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAMA,cAAN,CAAqB;EAC1BC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,WATC,EAWDC,oBAXC,EAYT;IAAA,KARQF,MAQR,GARQA,MAQR;IAAA,KAHQC,WAGR,GAHQA,WAGR;IAAA,KADQC,oBACR,GADQA,oBACR;IAAA,+CAYc,KAZd;IAAA;IAAA,+CA4BM,MAAM;MAAA;;MACZ,IAAI,KAAKC,OAAL,EAAJ,EAAoB,OAAOC,OAAO,CAACC,OAAR,EAAP;MAEpB,4BAAKC,aAAL,0EAAKA,aAAL,GAAuB,IAAIF,OAAJ,CAAaC,OAAD,IAAa;QAC9CE,iCAAA,CAAgBC,KAAhB,CAAsBC,GAAtB,CAA0B,MAAM;UAC9B,IAAI,KAAKN,O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CAlQXjJ,c,WAoQI,CAACkJ,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB3F,wBAAA,CAAc4F,UAAd,CAAyBpJ,cAAzB"}
@@ -401,16 +401,18 @@ class ComponentBundlingStrategy {
401
401
  const moduleMapsPromise = defs.map(async previewDef => {
402
402
  const moduleMap = await previewDef.getModuleMap([component]);
403
403
  const maybeFiles = moduleMap.get(component);
404
- if (!maybeFiles || !capsule) return [];
404
+ if (!maybeFiles || !capsule) return {
405
+ prefix: previewDef.prefix,
406
+ paths: []
407
+ };
405
408
  const [, files] = maybeFiles;
406
- const compiledPaths = this.getPaths(context, component, files); // const files = flatten(paths.toArray().map(([, file]) => file));
407
-
409
+ const compiledPaths = this.getPaths(context, component, files);
408
410
  return {
409
411
  prefix: previewDef.prefix,
410
412
  paths: compiledPaths
411
413
  };
412
414
  });
413
- const moduleMaps = (0, _lodash().flatten)(await Promise.all(moduleMapsPromise));
415
+ const moduleMaps = await Promise.all(moduleMapsPromise);
414
416
  const contents = (0, _generateComponentLink().generateComponentLink)(moduleMaps);
415
417
  return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview'); // return flatten(moduleMaps);
416
418
  }
@@ -1 +1 @@
1
- {"version":3,"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","origComponents","capsuleNetwork","originalSeedersCapsules","map","capsule","component","entriesArr","Promise","all","computeComponentEntry","chunkSize","config","maxChunkSize","chunks","chunk","peers","getPeerDependenciesListFromEnv","env","targets","currentChunk","entries","components","forEach","entry","Object","assign","push","hostDependencies","aliasHostDependencies","externalizeHostDependencies","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","join","getAssetFilename","split","copyAssetsToCapsules","result","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","dirname","fs","copyFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","basename","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","componentsResults","flatten","computeTargetResult","artifacts","getArtifactDef","isEmpty","errors","err","message","warning","warnings","startTime","endTime","globPatterns","rootDir","getDirName","envName","replace","resolve","capsulesRootDir","compiler","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","compiledPaths","prefix","paths","moduleMaps","contents","generateComponentLink","writeLinkContents"],"sources":["component-strategy.ts"],"sourcesContent":["import { join, resolve, basename, dirname } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty, chunk } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap, Target } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n\ntype ComponentEntry = {\n component: Component;\n entries: Object;\n};\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<Target[]> {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const origComponents = context.capsuleNetwork.originalSeedersCapsules.map((capsule) => capsule.component);\n\n const entriesArr = await Promise.all(\n origComponents.map((component) => {\n return this.computeComponentEntry(previewDefs, component, context);\n }, {})\n );\n\n const chunkSize = this.preview.config.maxChunkSize;\n\n const chunks = chunkSize ? chunk(entriesArr, chunkSize) : [entriesArr];\n\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n const targets = chunks.map((currentChunk) => {\n const entries: BundlerEntryMap = {};\n const components: Component[] = [];\n currentChunk.forEach((entry) => {\n Object.assign(entries, entry.entries);\n components.push(entry.component);\n });\n\n return {\n entries,\n components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n externalizeHostDependencies: true,\n };\n });\n\n return targets;\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n }\n\n async computeComponentEntry(\n previewDefs: PreviewDefinition[],\n component: Component,\n context: ComputeTargetsContext\n ): Promise<ComponentEntry> {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return { component, entries };\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', this.getAssetFilename(asset));\n }\n\n private getAssetFilename(asset: Asset): string {\n // handle cases where the asset name is something like my-image.svg?hash (while the filename in the fs is just my-image.svg)\n const [name] = asset.name.split('?');\n return name;\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(artifactDirFullPath);\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const destFilePath = join(artifactDirFullPath, this.getAssetFilename(asset));\n mkdirpSync(dirname(destFilePath));\n capsule.fs.copyFileSync(filePath, destFilePath);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const componentsResults = flatten(\n await Promise.all(results.map((result) => this.computeTargetResult(context, result)))\n );\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async computeTargetResult(context: BundlerContext, result: BundlerResult) {\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n return componentsResults;\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n // const files = flatten(paths.toArray().map(([, file]) => file));\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = flatten(await Promise.all(moduleMapsPromise));\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,MAAMA,oBAAoB,GAAG,SAA7B;;AACA,MAAMC,sBAAsB,GAAG,WAA/B;;AACA,MAAMC,6BAA6B,GAAI,GAAEF,oBAAqB,KAA9D;;AACA,MAAMG,+BAA+B,GAAI,GAAEF,sBAAuB,KAAlE;;AAEA,MAAMG,gCAAgC,GAAG,MAAzC;;AACA,MAAMC,gCAAgC,GAAG,mBAAzC;;;AAMP;AACA;AACA;AACO,MAAMC,yBAAN,CAA4D;EAGjEC,WAAW,CAASC,OAAT,EAAuCC,GAAvC,EAA6DC,kBAA7D,EAAyG;IAAA,KAAhGF,OAAgG,GAAhGA,OAAgG;IAAA,KA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B,CAGjB;;IACA,IAAI,CAACjC,OAAL,EACE,MAAM,KAAI+H,oBAAJ,EACH,wCAAuC9H,SAAS,CAACgC,EAAV,CAAaG,QAAb,EAAwB,iCAD5D,CAAN;IAGF,MAAM4F,iBAAiB,GAAGF,IAAI,CAAC/H,GAAL,CAAS,MAAOkI,UAAP,IAAsB;MACvD,MAAMC,SAAS,GAAG,MAAMD,UAAU,CAACE,YAAX,CAAwB,CAAClI,SAAD,CAAxB,CAAxB;MACA,MAAMmI,UAAU,GAAGF,SAAS,CAACG,GAAV,CAAcpI,SAAd,CAAnB;MACA,IAAI,CAACmI,UAAD,IAAe,CAACpI,OAApB,EAA6B,OAAO,EAAP;MAC7B,MAAM,GAAG0D,KAAH,IAAY0E,UAAlB;MACA,MAAME,aAAa,GAAG,KAAKzG,QAAL,CAAcvC,OAAd,EAAuBW,SAAvB,EAAkCyD,KAAlC,CAAtB,CALuD,CAMvD;;MAEA,OAAO;QACL6E,MAAM,EAAEN,UAAU,CAACM,MADd;QAELC,KAAK,EAAEF;MAFF,CAAP;IAID,CAZyB,CAA1B;IAcA,MAAMG,UAAU,GAAG,IAAAnC,iBAAA,EAAQ,MAAMnG,OAAO,CAACC,GAAR,CAAY4H,iBAAZ,CAAd,CAAnB;IAEA,MAAMU,QAAQ,GAAG,IAAAC,8CAAA,EAAsBF,UAAtB,CAAjB;IACA,OAAO,KAAKvJ,OAAL,CAAa0J,iBAAb,CAA+BF,QAA/B,EAAyC,KAAKb,sBAAL,CAA4B7H,OAA5B,CAAzC,EAA+E,SAA/E,CAAP,CAzBiB,CA0BjB;EACD;;AA7VgE"}
1
+ {"version":3,"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","origComponents","capsuleNetwork","originalSeedersCapsules","map","capsule","component","entriesArr","Promise","all","computeComponentEntry","chunkSize","config","maxChunkSize","chunks","chunk","peers","getPeerDependenciesListFromEnv","env","targets","currentChunk","entries","components","forEach","entry","Object","assign","push","hostDependencies","aliasHostDependencies","externalizeHostDependencies","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","join","getAssetFilename","split","copyAssetsToCapsules","result","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","dirname","fs","copyFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","basename","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","componentsResults","flatten","computeTargetResult","artifacts","getArtifactDef","isEmpty","errors","err","message","warning","warnings","startTime","endTime","globPatterns","rootDir","getDirName","envName","replace","resolve","capsulesRootDir","compiler","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","prefix","paths","compiledPaths","moduleMaps","contents","generateComponentLink","writeLinkContents"],"sources":["component-strategy.ts"],"sourcesContent":["import { join, resolve, basename, dirname } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty, chunk } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap, Target } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n\ntype ComponentEntry = {\n component: Component;\n entries: Object;\n};\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<Target[]> {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const origComponents = context.capsuleNetwork.originalSeedersCapsules.map((capsule) => capsule.component);\n\n const entriesArr = await Promise.all(\n origComponents.map((component) => {\n return this.computeComponentEntry(previewDefs, component, context);\n }, {})\n );\n\n const chunkSize = this.preview.config.maxChunkSize;\n\n const chunks = chunkSize ? chunk(entriesArr, chunkSize) : [entriesArr];\n\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n const targets = chunks.map((currentChunk) => {\n const entries: BundlerEntryMap = {};\n const components: Component[] = [];\n currentChunk.forEach((entry) => {\n Object.assign(entries, entry.entries);\n components.push(entry.component);\n });\n\n return {\n entries,\n components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n externalizeHostDependencies: true,\n };\n });\n\n return targets;\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n }\n\n async computeComponentEntry(\n previewDefs: PreviewDefinition[],\n component: Component,\n context: ComputeTargetsContext\n ): Promise<ComponentEntry> {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return { component, entries };\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', this.getAssetFilename(asset));\n }\n\n private getAssetFilename(asset: Asset): string {\n // handle cases where the asset name is something like my-image.svg?hash (while the filename in the fs is just my-image.svg)\n const [name] = asset.name.split('?');\n return name;\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(artifactDirFullPath);\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const destFilePath = join(artifactDirFullPath, this.getAssetFilename(asset));\n mkdirpSync(dirname(destFilePath));\n capsule.fs.copyFileSync(filePath, destFilePath);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const componentsResults = flatten(\n await Promise.all(results.map((result) => this.computeTargetResult(context, result)))\n );\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async computeTargetResult(context: BundlerContext, result: BundlerResult) {\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n return componentsResults;\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return { prefix: previewDef.prefix, paths: [] };\n\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = await Promise.all(moduleMapsPromise);\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,MAAMA,oBAAoB,GAAG,SAA7B;;AACA,MAAMC,sBAAsB,GAAG,WAA/B;;AACA,MAAMC,6BAA6B,GAAI,GAAEF,oBAAqB,KAA9D;;AACA,MAAMG,+BAA+B,GAAI,GAAEF,sBAAuB,KAAlE;;AAEA,MAAMG,gCAAgC,GAA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,10 +65,10 @@ function _component() {
65
65
  return data;
66
66
  }
67
67
 
68
- function _webpack() {
69
- const data = require("../webpack");
68
+ function _htmlTemplate() {
69
+ const data = require("../bundler/html-template");
70
70
 
71
- _webpack = function () {
71
+ _htmlTemplate = function () {
72
72
  return data;
73
73
  };
74
74
 
@@ -115,7 +115,7 @@ class EnvBundlingStrategy {
115
115
 
116
116
  const config = {
117
117
  title: 'Preview',
118
- templateContent: (0, _webpack().html)('Preview'),
118
+ templateContent: (0, _htmlTemplate().html)('Preview'),
119
119
  cache: false,
120
120
  minify: (_options$dev = options === null || options === void 0 ? void 0 : options.dev) !== null && _options$dev !== void 0 ? _options$dev : true
121
121
  };