@teambit/preview 0.0.880 → 0.0.882

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 (84) hide show
  1. package/dist/artifact-file-middleware.js +2 -22
  2. package/dist/artifact-file-middleware.js.map +1 -1
  3. package/dist/bundler/chunks.js +1 -9
  4. package/dist/bundler/chunks.js.map +1 -1
  5. package/dist/bundler/create-peer-link.spec.js +0 -3
  6. package/dist/bundler/create-peer-link.spec.js.map +1 -1
  7. package/dist/bundler/create-peers-link.js +3 -20
  8. package/dist/bundler/create-peers-link.js.map +1 -1
  9. package/dist/bundler/html-plugin.js +0 -13
  10. package/dist/bundler/html-plugin.js.map +1 -1
  11. package/dist/bundler/html-template.js +0 -1
  12. package/dist/bundler/html-template.js.map +1 -1
  13. package/dist/component-preview.js +0 -3
  14. package/dist/component-preview.js.map +1 -1
  15. package/dist/component-preview.route.js +8 -23
  16. package/dist/component-preview.route.js.map +1 -1
  17. package/dist/env-preview-template.task.js +9 -75
  18. package/dist/env-preview-template.task.js.map +1 -1
  19. package/dist/env-template.route.js +6 -22
  20. package/dist/env-template.route.js.map +1 -1
  21. package/dist/events/click-inside-an-iframe.js +1 -12
  22. package/dist/events/click-inside-an-iframe.js.map +1 -1
  23. package/dist/events/index.js +0 -2
  24. package/dist/events/index.js.map +1 -1
  25. package/dist/exceptions/bundling-strategy-not-found.js +0 -3
  26. package/dist/exceptions/bundling-strategy-not-found.js.map +1 -1
  27. package/dist/exceptions/index.js +0 -12
  28. package/dist/exceptions/index.js.map +1 -1
  29. package/dist/exceptions/preview-artifact-not-found.js +0 -6
  30. package/dist/exceptions/preview-artifact-not-found.js.map +1 -1
  31. package/dist/exceptions/preview-not-found.js +0 -3
  32. package/dist/exceptions/preview-not-found.js.map +1 -1
  33. package/dist/exceptions/preview-output-file-not-found.js +0 -6
  34. package/dist/exceptions/preview-output-file-not-found.js.map +1 -1
  35. package/dist/execution-ref.js +0 -11
  36. package/dist/execution-ref.js.map +1 -1
  37. package/dist/generate-link.js +2 -7
  38. package/dist/generate-link.js.map +1 -1
  39. package/dist/gql/fetch-component-aspects.js +0 -6
  40. package/dist/gql/fetch-component-aspects.js.map +1 -1
  41. package/dist/html-utils.js +0 -9
  42. package/dist/html-utils.js.map +1 -1
  43. package/dist/index.js +0 -8
  44. package/dist/index.js.map +1 -1
  45. package/dist/mk-temp-dir.js +0 -10
  46. package/dist/mk-temp-dir.js.map +1 -1
  47. package/dist/preview-artifact.js +0 -12
  48. package/dist/preview-artifact.js.map +1 -1
  49. package/dist/preview-assets.route.js +2 -13
  50. package/dist/preview-assets.route.js.map +1 -1
  51. package/dist/preview-modules.js +0 -11
  52. package/dist/preview-modules.js.map +1 -1
  53. package/dist/preview.aspect.js +0 -6
  54. package/dist/preview.aspect.js.map +1 -1
  55. package/dist/preview.composition.js +0 -6
  56. package/dist/preview.composition.js.map +1 -1
  57. package/dist/preview.graphql.js +0 -5
  58. package/dist/preview.graphql.js.map +1 -1
  59. package/dist/preview.main.runtime.js +53 -226
  60. package/dist/preview.main.runtime.js.map +1 -1
  61. package/dist/preview.preview.runtime.js +18 -108
  62. package/dist/preview.preview.runtime.js.map +1 -1
  63. package/dist/preview.route.js +6 -21
  64. package/dist/preview.route.js.map +1 -1
  65. package/dist/preview.start-plugin.js +8 -42
  66. package/dist/preview.start-plugin.js.map +1 -1
  67. package/dist/preview.task.js +1 -20
  68. package/dist/preview.task.js.map +1 -1
  69. package/dist/rendering-context.js +1 -5
  70. package/dist/rendering-context.js.map +1 -1
  71. package/dist/size-event.js +0 -10
  72. package/dist/size-event.js.map +1 -1
  73. package/dist/strategies/component-strategy.js +19 -69
  74. package/dist/strategies/component-strategy.js.map +1 -1
  75. package/dist/strategies/env-strategy.js +1 -40
  76. package/dist/strategies/env-strategy.js.map +1 -1
  77. package/dist/strategies/generate-component-link.js +4 -7
  78. package/dist/strategies/generate-component-link.js.map +1 -1
  79. package/dist/strategies/index.js +0 -6
  80. package/dist/strategies/index.js.map +1 -1
  81. package/package-tar/teambit-preview-0.0.882.tgz +0 -0
  82. package/package.json +19 -19
  83. package/{preview-1666312873430.js → preview-1666496165706.js} +2 -2
  84. package/package-tar/teambit-preview-0.0.880.tgz +0 -0
@@ -1,15 +1,10 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  require("core-js/modules/es.array.iterator.js");
6
-
7
5
  require("core-js/modules/es.promise.js");
8
-
9
6
  require("core-js/modules/es.regexp.exec.js");
10
-
11
7
  require("core-js/modules/web.url.js");
12
-
13
8
  Object.defineProperty(exports, "__esModule", {
14
9
  value: true
15
10
  });
@@ -20,158 +15,113 @@ Object.defineProperty(exports, "linkModules", {
20
15
  return _previewModules().linkModules;
21
16
  }
22
17
  });
23
-
24
18
  function _defineProperty2() {
25
19
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
26
-
27
20
  _defineProperty2 = function () {
28
21
  return data;
29
22
  };
30
-
31
23
  return data;
32
24
  }
33
-
34
25
  function _pubsub() {
35
26
  const data = _interopRequireDefault(require("@teambit/pubsub"));
36
-
37
27
  _pubsub = function () {
38
28
  return data;
39
29
  };
40
-
41
30
  return data;
42
31
  }
43
-
44
32
  function _harmony() {
45
33
  const data = require("@teambit/harmony");
46
-
47
34
  _harmony = function () {
48
35
  return data;
49
36
  };
50
-
51
37
  return data;
52
38
  }
53
-
54
39
  function _componentId() {
55
40
  const data = require("@teambit/component-id");
56
-
57
41
  _componentId = function () {
58
42
  return data;
59
43
  };
60
-
61
44
  return data;
62
45
  }
63
-
64
46
  function _crossFetch() {
65
47
  const data = _interopRequireDefault(require("cross-fetch"));
66
-
67
48
  _crossFetch = function () {
68
49
  return data;
69
50
  };
70
-
71
51
  return data;
72
52
  }
73
-
74
53
  function _memoizee() {
75
54
  const data = _interopRequireDefault(require("memoizee"));
76
-
77
55
  _memoizee = function () {
78
56
  return data;
79
57
  };
80
-
81
58
  return data;
82
59
  }
83
-
84
60
  function _lodash() {
85
61
  const data = require("lodash");
86
-
87
62
  _lodash = function () {
88
63
  return data;
89
64
  };
90
-
91
65
  return data;
92
66
  }
93
-
94
67
  function _exceptions() {
95
68
  const data = require("./exceptions");
96
-
97
69
  _exceptions = function () {
98
70
  return data;
99
71
  };
100
-
101
72
  return data;
102
73
  }
103
-
104
74
  function _preview() {
105
75
  const data = require("./preview.aspect");
106
-
107
76
  _preview = function () {
108
77
  return data;
109
78
  };
110
-
111
79
  return data;
112
80
  }
113
-
114
81
  function _events() {
115
82
  const data = require("./events");
116
-
117
83
  _events = function () {
118
84
  return data;
119
85
  };
120
-
121
86
  return data;
122
87
  }
123
-
124
88
  function _renderingContext() {
125
89
  const data = require("./rendering-context");
126
-
127
90
  _renderingContext = function () {
128
91
  return data;
129
92
  };
130
-
131
93
  return data;
132
94
  }
133
-
134
95
  function _fetchComponentAspects() {
135
96
  const data = require("./gql/fetch-component-aspects");
136
-
137
97
  _fetchComponentAspects = function () {
138
98
  return data;
139
99
  };
140
-
141
100
  return data;
142
101
  }
143
-
144
102
  function _previewModules() {
145
103
  const data = require("./preview-modules");
146
-
147
104
  _previewModules = function () {
148
105
  return data;
149
106
  };
150
-
151
107
  return data;
152
108
  }
153
-
154
109
  function _htmlUtils() {
155
110
  const data = require("./html-utils");
156
-
157
111
  _htmlUtils = function () {
158
112
  return data;
159
113
  };
160
-
161
114
  return data;
162
115
  }
163
-
164
116
  function _sizeEvent() {
165
117
  const data = require("./size-event");
166
-
167
118
  _sizeEvent = function () {
168
119
  return data;
169
120
  };
170
-
171
121
  return data;
172
122
  }
173
-
174
123
  // forward linkModules() for generate-link.ts
124
+
175
125
  class PreviewPreview {
176
126
  constructor(
177
127
  /**
@@ -189,7 +139,6 @@ class PreviewPreview {
189
139
  (0, _defineProperty2().default)(this, "_setupPromise", void 0);
190
140
  (0, _defineProperty2().default)(this, "setup", () => {
191
141
  var _this$_setupPromise;
192
-
193
142
  if (this.isReady()) return Promise.resolve();
194
143
  (_this$_setupPromise = this._setupPromise) !== null && _this$_setupPromise !== void 0 ? _this$_setupPromise : this._setupPromise = new Promise(resolve => {
195
144
  _previewModules().PREVIEW_MODULES.onSet.add(() => {
@@ -208,21 +157,18 @@ class PreviewPreview {
208
157
  const name = previewName || this.getDefault();
209
158
  if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';
210
159
  const preview = this.getPreview(name);
211
-
212
160
  if (!preview || !componentId) {
213
161
  throw new (_exceptions().PreviewNotFound)(previewName);
214
162
  }
215
-
216
163
  const includesAll = await Promise.all((preview.include || []).map(async inclPreviewName => {
217
164
  var _includedPreview$sele;
218
-
219
165
  const includedPreview = this.getPreview(inclPreviewName);
220
166
  if (!includedPreview) return undefined;
221
167
  const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);
222
168
  return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, inclPreviewModule);
223
169
  }));
224
- const includes = includesAll.filter(module => !!module); // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
225
-
170
+ const includes = includesAll.filter(module => !!module);
171
+ // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
226
172
  const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
227
173
  const previewModule = await this.getPreviewModule(name, componentId);
228
174
  const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));
@@ -236,7 +182,6 @@ class PreviewPreview {
236
182
  }));
237
183
  this.registerClickPubSub();
238
184
  }
239
-
240
185
  registerClickPubSub() {
241
186
  window.addEventListener('click', e => {
242
187
  const timestamp = Date.now();
@@ -244,10 +189,8 @@ class PreviewPreview {
244
189
  this.pubsub.pub(_preview().PreviewAspect.id, new (_events().ClickInsideAnIframeEvent)(timestamp, clickEvent));
245
190
  });
246
191
  }
247
-
248
192
  isReady() {
249
193
  var _preview$include$ever, _preview$include;
250
-
251
194
  const {
252
195
  previewName
253
196
  } = this.getLocation();
@@ -259,23 +202,19 @@ class PreviewPreview {
259
202
  if (!includedReady) return false;
260
203
  return true;
261
204
  }
262
-
263
205
  setViewport() {
264
206
  const query = this.getQuery();
265
207
  const viewPort = this.getParam(query, 'viewport');
266
-
267
208
  if (!viewPort) {
268
209
  window.document.body.style.width = '100%';
269
210
  return;
270
211
  }
271
-
272
212
  window.document.body.style.maxWidth = `${viewPort}px`;
273
213
  }
274
-
275
214
  reportSize() {
276
215
  var _window, _window2;
277
-
278
- if (!((_window = window) !== null && _window !== void 0 && _window.parent) || !((_window2 = window) !== null && _window2 !== void 0 && _window2.document)) return; // TODO: discuss with gilad for a better way to resolve page loaded here.
216
+ if (!((_window = window) !== null && _window !== void 0 && _window.parent) || !((_window2 = window) !== null && _window2 !== void 0 && _window2.document)) return;
217
+ // TODO: discuss with gilad for a better way to resolve page loaded here.
279
218
 
280
219
  const sendPubsubEvent = () => {
281
220
  this.pubsub.pub(_preview().PreviewAspect.id, new (_sizeEvent().SizeEvent)({
@@ -283,36 +222,28 @@ class PreviewPreview {
283
222
  height: window.document.body.offsetHeight
284
223
  }));
285
224
  };
286
-
287
225
  window.document.body.addEventListener('resize', (0, _lodash().debounce)(sendPubsubEvent, 300));
288
226
  let counter = 0;
289
227
  const interval = setInterval(() => {
290
228
  // TODO: think
291
229
  counter += 1;
292
-
293
230
  if (counter > 10) {
294
231
  clearInterval(interval);
295
232
  return;
296
233
  }
297
-
298
234
  this.pubsub.pub(_preview().PreviewAspect.id, new (_sizeEvent().SizeEvent)({
299
235
  width: window.document.body.offsetWidth,
300
236
  height: window.document.body.offsetHeight
301
237
  }));
302
238
  }, 200);
303
239
  }
304
-
305
240
  async getPreviewModule(previewName, id) {
306
241
  const compShortId = id.fullName;
307
-
308
242
  const relevantModel = _previewModules().PREVIEW_MODULES.get(previewName);
309
-
310
243
  if (!relevantModel) throw new Error(`[preview.preview] missing preview "${previewName}"`);
311
244
  if (relevantModel.componentMap[compShortId]) return relevantModel;
312
245
  const componentPreviews = await this.fetchComponentPreview(id, previewName);
313
-
314
246
  _previewModules().PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);
315
-
316
247
  const component = componentPreviews[previewName];
317
248
  const metadata = componentPreviews[`${previewName}_metadata`];
318
249
  return {
@@ -325,11 +256,10 @@ class PreviewPreview {
325
256
  }
326
257
  };
327
258
  }
328
-
329
259
  async fetchComponentPreview(id, name) {
330
260
  let previewFile;
331
- const allFiles = await this.fetchComponentPreviewFiles(id, name); // It's a component bundled with the env
332
-
261
+ const allFiles = await this.fetchComponentPreviewFiles(id, name);
262
+ // It's a component bundled with the env
333
263
  if (allFiles === null) return {};
334
264
  await Promise.all(allFiles.map(file => {
335
265
  // We want to run the preview file always last
@@ -337,50 +267,43 @@ class PreviewPreview {
337
267
  previewFile = file;
338
268
  return undefined;
339
269
  }
340
-
341
270
  return this.addComponentFileElement(id, file);
342
271
  }));
343
272
  if (!previewFile) return {};
344
273
  return this.loadPreviewScript(id, name, previewFile);
345
274
  }
346
-
347
275
  addComponentFileElement(id, previewBundleFileName) {
348
276
  if (previewBundleFileName.endsWith('.js')) {
349
277
  return this.addComponentFileScriptElement(id, previewBundleFileName);
350
- } // TODO - should we load assets other than .css / .js?
351
- // if (previewBundleFileName.endsWith('.css')) {
352
-
278
+ }
353
279
 
280
+ // TODO - should we load assets other than .css / .js?
281
+ // if (previewBundleFileName.endsWith('.css')) {
354
282
  this.addComponentFileLinkElement(id, previewBundleFileName).catch(err => {
355
283
  throw new Error(`[preview.preview] failed loading asset "${previewBundleFileName}". Error - "${err === null || err === void 0 ? void 0 : err.toString()}"`);
356
- }); // do NOT await non js assets, as they might never load (like images), and not critical for rendering.
284
+ });
357
285
 
286
+ // do NOT await non js assets, as they might never load (like images), and not critical for rendering.
358
287
  return undefined;
359
288
  }
360
-
361
289
  async fetchComponentPreviewFiles(id, previewName) {
362
290
  const previewAssetsRoute = `~aspect/preview-assets`;
363
291
  const stringId = id.toString();
364
292
  const url = `/api/${stringId}/${previewAssetsRoute}`;
365
293
  const res = await (0, _crossFetch().default)(url);
366
-
367
294
  if (res.status >= 400) {
368
295
  throw new (_exceptions().PreviewNotFound)(previewName);
369
296
  }
370
-
371
- const parsed = await res.json(); // This is component bundled with the env, no reason to bring the files, as they will be the files of the env
372
-
297
+ const parsed = await res.json();
298
+ // This is component bundled with the env, no reason to bring the files, as they will be the files of the env
373
299
  if (parsed.isBundledWithEnv) {
374
300
  return null;
375
301
  }
376
-
377
302
  if (!parsed.files || !parsed.files.length) {
378
303
  throw new (_exceptions().PreviewNotFound)(previewName);
379
304
  }
380
-
381
305
  return parsed.files;
382
306
  }
383
-
384
307
  addComponentFileScriptElement(id, previewBundleFileName) {
385
308
  const previewRoute = `~aspect/component-preview`;
386
309
  const stringId = id.toString();
@@ -389,7 +312,6 @@ class PreviewPreview {
389
312
  src
390
313
  });
391
314
  }
392
-
393
315
  addComponentFileLinkElement(id, previewBundleFileName) {
394
316
  const stringId = id.toString();
395
317
  const previewRoute = `~aspect/component-preview`;
@@ -398,20 +320,19 @@ class PreviewPreview {
398
320
  href
399
321
  });
400
322
  }
401
-
402
323
  async loadPreviewScript(id, previewName, previewBundleFileName) {
403
324
  const previewRoute = `~aspect/component-preview`;
404
325
  const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;
405
326
  await (0, _htmlUtils().loadScript)({
406
327
  src
407
- }); // TODO - replace with jsonp
328
+ });
408
329
 
330
+ // TODO - replace with jsonp
409
331
  const globalId = `${id.toStringWithoutVersion()}-preview`;
410
332
  const componentPreview = window[globalId];
411
333
  if (!componentPreview) throw new (_exceptions().PreviewNotFound)(previewName);
412
334
  return componentPreview;
413
335
  }
414
-
415
336
  /**
416
337
  * register a new preview.
417
338
  */
@@ -419,50 +340,43 @@ class PreviewPreview {
419
340
  this.previewSlot.register(preview);
420
341
  return this;
421
342
  }
343
+
422
344
  /**
423
345
  * get the preview rendering context.
424
346
  */
425
-
426
-
427
347
  getRenderingContext(aspectsFilter) {
428
348
  return new (_renderingContext().RenderingContext)(this.renderingContextSlot, {
429
349
  aspectsFilter
430
350
  });
431
351
  }
352
+
432
353
  /**
433
354
  * allows aspects to add rendering contexts.
434
355
  * render context is available through all preview definitions.
435
356
  */
436
-
437
-
438
357
  registerRenderContext(renderContext) {
439
358
  this.renderingContextSlot.register(renderContext);
440
359
  return this;
441
360
  }
442
-
443
361
  getDefault() {
444
362
  const previews = this.previewSlot.values();
445
363
  const defaultOne = previews.find(previewCandidate => previewCandidate.default);
446
364
  return (defaultOne === null || defaultOne === void 0 ? void 0 : defaultOne.name) || previews[0].name;
447
365
  }
448
-
449
366
  getPreview(previewName) {
450
367
  const previews = this.previewSlot.values();
451
368
  const preview = previews.find(previewCandidate => previewCandidate.name === previewName);
452
369
  return preview;
453
370
  }
454
-
455
371
  getParam(query, param) {
456
372
  const params = new URLSearchParams(query);
457
373
  return params.get(param);
458
374
  }
459
-
460
375
  getQuery() {
461
376
  const withoutHash = window.location.hash.substring(1);
462
377
  const [, after] = withoutHash.split('?');
463
378
  return after;
464
379
  }
465
-
466
380
  getLocation() {
467
381
  const withoutHash = window.location.hash.substring(1);
468
382
  const [before, after] = withoutHash.split('?');
@@ -471,7 +385,6 @@ class PreviewPreview {
471
385
  componentId: _componentId().ComponentID.tryFromString(before)
472
386
  };
473
387
  }
474
-
475
388
  static async provider([pubsub], config, [previewSlot, renderingContextSlot]) {
476
389
  const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);
477
390
  window.addEventListener('hashchange', () => {
@@ -480,14 +393,11 @@ class PreviewPreview {
480
393
  });
481
394
  return preview;
482
395
  }
483
-
484
396
  }
485
-
486
397
  exports.PreviewPreview = PreviewPreview;
487
398
  (0, _defineProperty2().default)(PreviewPreview, "runtime", _preview().PreviewRuntime);
488
399
  (0, _defineProperty2().default)(PreviewPreview, "dependencies", [_pubsub().default]);
489
400
  (0, _defineProperty2().default)(PreviewPreview, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType()]);
490
-
491
401
  _preview().PreviewAspect.addRuntime(PreviewPreview);
492
402
 
493
403
  //# sourceMappingURL=preview.preview.runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","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","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","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';\nimport { debounce } from 'lodash';\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';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\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 // fit content always.\n window.document.body.style.width = 'fit-content';\n\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 const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n };\n\n window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n }, 200);\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 const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\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 await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return 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\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\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 previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\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 getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\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;;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;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAM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W,CAACK,KAAZ,CAAkB,GAAlB,CAAxB;IAEA,OAAO;MACLnI,WAAW,EAAE,KAAKuD,QAAL,CAAc2E,KAAd,EAAqB,SAArB,CADR;MAELjI,WAAW,EAAEoI,0BAAA,CAAYC,aAAZ,CAA0BF,MAA1B;IAFR,CAAP;EAID;;EAQoB,aAARG,QAAQ,CACnB,CAACvJ,MAAD,CADmB,EAEnBwJ,MAFmB,EAGnB,CAACvJ,WAAD,EAAcC,oBAAd,CAHmB,EAInB;IACA,MAAMoB,OAAO,GAAG,IAAIxB,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEAS,MAAM,CAACyC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA9B,OAAO,CAACqB,MAAR;IACD,CAHD;IAKA,OAAOrB,OAAP;EACD;;AAxUyB;;;gCAAfxB,c,aAqTM2J,yB;gCArTN3J,c,kBAuTW,CAAC4J,iBAAD,C;gCAvTX5J,c,WAyTI,CAAC6J,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB/F,wBAAA,CAAcgG,UAAd,CAAyB/J,cAAzB"}
1
+ {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","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","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","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';\nimport { debounce } from 'lodash';\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';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\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 // fit content always.\n window.document.body.style.width = 'fit-content';\n\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 const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n };\n\n window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n }, 200);\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 const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\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 await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return 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\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\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 previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\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 getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\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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AI,CAACC,QAAQ,EAAe,EAAED,eAAI,CAACC,QAAQ,EAA4B,CAAC;AAkB1F/F,wBAAa,CAACgG,UAAU,CAAC/J,cAAc,CAAC"}
@@ -1,44 +1,32 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  require("core-js/modules/es.promise.js");
6
-
7
5
  Object.defineProperty(exports, "__esModule", {
8
6
  value: true
9
7
  });
10
8
  exports.PreviewRoute = void 0;
11
-
12
9
  function _defineProperty2() {
13
10
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
14
-
15
11
  _defineProperty2 = function () {
16
12
  return data;
17
13
  };
18
-
19
14
  return data;
20
15
  }
21
-
22
16
  function _uiFoundationUiPages() {
23
17
  const data = require("@teambit/ui-foundation.ui.pages.static-error");
24
-
25
18
  _uiFoundationUiPages = function () {
26
19
  return data;
27
20
  };
28
-
29
21
  return data;
30
22
  }
31
-
32
23
  function _artifactFileMiddleware() {
33
24
  const data = require("./artifact-file-middleware");
34
-
35
25
  _artifactFileMiddleware = function () {
36
26
  return data;
37
27
  };
38
-
39
28
  return data;
40
29
  }
41
-
42
30
  class PreviewRoute {
43
31
  constructor(
44
32
  /**
@@ -55,8 +43,8 @@ class PreviewRoute {
55
43
  const component = req.component;
56
44
  if (!component) return res.status(404).send((0, _uiFoundationUiPages().noPreview)());
57
45
  const isLegacyPath = await this.preview.isBundledWithEnv(component);
58
- let artifact; // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680
59
-
46
+ let artifact;
47
+ // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680
60
48
  try {
61
49
  // Taking the env template (in this case we will take the component only bundle throw component-preview route)
62
50
  // We use this route for the env template for backward compatibility - new scopes which contain components tagged with old versions of bit
@@ -69,11 +57,10 @@ class PreviewRoute {
69
57
  } catch (e) {
70
58
  this.logger.error(`getEnvTemplateFromComponentEnv or getPreview has failed`, e);
71
59
  return res.status(404).send((0, _uiFoundationUiPages().noPreview)());
72
- } // @ts-ignore
73
-
74
-
75
- req.artifact = artifact; // @ts-ignore
76
-
60
+ }
61
+ // @ts-ignore
62
+ req.artifact = artifact;
63
+ // @ts-ignore
77
64
  req.isLegacyPath = isLegacyPath;
78
65
  return next();
79
66
  } catch (e) {
@@ -82,9 +69,7 @@ class PreviewRoute {
82
69
  }
83
70
  }, (0, _artifactFileMiddleware().getArtifactFileMiddleware)(this.logger)]);
84
71
  }
85
-
86
72
  }
87
-
88
73
  exports.PreviewRoute = PreviewRoute;
89
74
 
90
75
  //# sourceMappingURL=preview.route.js.map