@teambit/preview 0.0.627 → 0.0.632

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 (68) hide show
  1. package/__preview-1643167379538.js +1 -0
  2. package/dist/artifact-file-middleware.d.ts +12 -0
  3. package/dist/artifact-file-middleware.js +81 -0
  4. package/dist/artifact-file-middleware.js.map +1 -0
  5. package/dist/bundling-strategy.d.ts +6 -1
  6. package/dist/component-preview.route.d.ts +20 -0
  7. package/dist/component-preview.route.js +83 -0
  8. package/dist/component-preview.route.js.map +1 -0
  9. package/dist/env-preview-template.task.d.ts +42 -0
  10. package/dist/env-preview-template.task.js +309 -0
  11. package/dist/env-preview-template.task.js.map +1 -0
  12. package/dist/env-template.route.d.ts +26 -0
  13. package/dist/env-template.route.js +89 -0
  14. package/dist/env-template.route.js.map +1 -0
  15. package/dist/generate-link.d.ts +1 -1
  16. package/dist/generate-link.js +3 -3
  17. package/dist/generate-link.js.map +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/preview-artifact.d.ts +2 -0
  21. package/dist/preview-artifact.js +21 -0
  22. package/dist/preview-artifact.js.map +1 -1
  23. package/dist/preview-assets.route.d.ts +19 -0
  24. package/dist/preview-assets.route.js +66 -0
  25. package/dist/preview-assets.route.js.map +1 -0
  26. package/dist/preview-definition.d.ts +16 -3
  27. package/dist/preview.graphql.d.ts +8 -1
  28. package/dist/preview.graphql.js +13 -2
  29. package/dist/preview.graphql.js.map +1 -1
  30. package/dist/preview.main.runtime.d.ts +78 -11
  31. package/dist/preview.main.runtime.js +251 -18
  32. package/dist/preview.main.runtime.js.map +1 -1
  33. package/dist/preview.preview.runtime.d.ts +11 -2
  34. package/dist/preview.preview.runtime.js +124 -6
  35. package/dist/preview.preview.runtime.js.map +1 -1
  36. package/dist/preview.route.d.ts +3 -7
  37. package/dist/preview.route.js +22 -21
  38. package/dist/preview.route.js.map +1 -1
  39. package/dist/preview.task.d.ts +2 -2
  40. package/dist/preview.task.js +25 -24
  41. package/dist/preview.task.js.map +1 -1
  42. package/dist/strategies/component-strategy.d.ts +52 -12
  43. package/dist/strategies/component-strategy.js +348 -20
  44. package/dist/strategies/component-strategy.js.map +1 -1
  45. package/dist/strategies/env-strategy.d.ts +7 -5
  46. package/dist/strategies/env-strategy.js +27 -1
  47. package/dist/strategies/env-strategy.js.map +1 -1
  48. package/dist/strategies/generate-component-link.d.ts +5 -0
  49. package/dist/strategies/generate-component-link.js +25 -0
  50. package/dist/strategies/generate-component-link.js.map +1 -0
  51. package/dist/types/preview-module.d.ts +1 -0
  52. package/dist/webpack/html.d.ts +2 -0
  53. package/dist/webpack/html.js +31 -0
  54. package/dist/webpack/html.js.map +1 -0
  55. package/dist/webpack/index.d.ts +1 -0
  56. package/dist/webpack/index.js +23 -0
  57. package/dist/webpack/index.js.map +1 -0
  58. package/package-tar/teambit-preview-0.0.632.tgz +0 -0
  59. package/package.json +29 -26
  60. package/preview.main.runtime.tsx +235 -23
  61. package/preview.preview.runtime.tsx +123 -7
  62. package/strategies/component-strategy.ts +329 -23
  63. package/strategies/env-strategy.ts +28 -10
  64. package/strategies/generate-component-link.ts +19 -0
  65. package/types/preview-module.ts +2 -0
  66. package/webpack/html.ts +22 -0
  67. package/webpack/index.ts +1 -0
  68. package/package-tar/teambit-preview-0.0.627.tgz +0 -0
@@ -56,6 +56,16 @@ function _componentId() {
56
56
  return data;
57
57
  }
58
58
 
59
+ function _crossFetch() {
60
+ const data = _interopRequireDefault(require("cross-fetch"));
61
+
62
+ _crossFetch = function () {
63
+ return data;
64
+ };
65
+
66
+ return data;
67
+ }
68
+
59
69
  function _exceptions() {
60
70
  const data = require("./exceptions");
61
71
 
@@ -111,7 +121,7 @@ class PreviewPreview {
111
121
  this.pubsub = pubsub;
112
122
  this.previewSlot = previewSlot;
113
123
  this.renderingContextSlot = renderingContextSlot;
114
- (0, _defineProperty2().default)(this, "render", () => {
124
+ (0, _defineProperty2().default)(this, "render", async () => {
115
125
  const {
116
126
  previewName,
117
127
  componentId
@@ -123,14 +133,15 @@ class PreviewPreview {
123
133
  throw new (_exceptions().PreviewNotFound)(previewName);
124
134
  }
125
135
 
126
- const includes = (preview.include || []).map(prevName => {
136
+ const includesAll = await Promise.all((preview.include || []).map(async prevName => {
127
137
  var _includedPreview$sele;
128
138
 
129
139
  const includedPreview = this.getPreview(prevName);
130
140
  if (!includedPreview) return undefined;
131
- return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, PREVIEW_MODULES[prevName]);
132
- }).filter(module => !!module);
133
- return preview.render(componentId.fullName, PREVIEW_MODULES[name], includes, this.getRenderingContext());
141
+ return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, await this.getPreviewModule(prevName, componentId));
142
+ }));
143
+ const includes = includesAll.filter(module => !!module);
144
+ return preview.render(componentId.fullName, await this.getPreviewModule(name, componentId), includes, this.getRenderingContext());
134
145
  });
135
146
  this.registerClickPubSub();
136
147
  }
@@ -147,9 +158,114 @@ class PreviewPreview {
147
158
  */
148
159
 
149
160
 
161
+ async getPreviewModule(name, id) {
162
+ if (PREVIEW_MODULES[name].componentMap[id.fullName]) return PREVIEW_MODULES[name]; // if (!window[name]) throw new PreviewNotFound(name);
163
+ // const isSplitComponentBundle = PREVIEW_MODULES[name].isSplitComponentBundle ?? false;
164
+ // const component = window[id.toStringWithoutVersion()];
165
+
166
+ const component = await this.fetchComponentPreview(id, name);
167
+ return {
168
+ mainModule: PREVIEW_MODULES[name].mainModule,
169
+ componentMap: {
170
+ [id.fullName]: component
171
+ }
172
+ };
173
+ }
174
+
175
+ async fetchComponentPreview(id, name) {
176
+ let previewFile;
177
+ const allFiles = await this.fetchComponentPreviewFiles(id, name);
178
+ allFiles.forEach(file => {
179
+ // We want to run the preview file always last
180
+ if (file.endsWith('-preview.js')) {
181
+ previewFile = file;
182
+ } else {
183
+ this.addComponentFileElement(id, file);
184
+ }
185
+ });
186
+ return new Promise((resolve, reject) => {
187
+ const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);
188
+ document.head.appendChild(previewScriptElement);
189
+ });
190
+ }
191
+
192
+ addComponentFileElement(id, previewBundleFileName) {
193
+ if (previewBundleFileName.endsWith('.js')) {
194
+ return this.addComponentFileScriptElement(id, previewBundleFileName);
195
+ }
196
+
197
+ return this.addComponentFileLinkElement(id, previewBundleFileName);
198
+ }
199
+
200
+ async fetchComponentPreviewFiles(id, previewName) {
201
+ const previewAssetsRoute = `~aspect/preview-assets`;
202
+ const stringId = id.toString();
203
+ const url = `/api/${stringId}/${previewAssetsRoute}`;
204
+ const res = await (0, _crossFetch().default)(url);
205
+
206
+ if (res.status >= 400) {
207
+ throw new (_exceptions().PreviewNotFound)(previewName);
208
+ }
209
+
210
+ const parsed = await res.json();
211
+
212
+ if (!parsed.files || !parsed.files.length) {
213
+ throw new (_exceptions().PreviewNotFound)(previewName);
214
+ }
215
+
216
+ return parsed.files;
217
+ }
218
+
219
+ addComponentFileScriptElement(id, previewBundleFileName) {
220
+ const script = document.createElement('script');
221
+ script.setAttribute('defer', 'defer');
222
+ const stringId = id.toString();
223
+ const previewRoute = `~aspect/component-preview`;
224
+ const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
225
+ script.src = src;
226
+ document.head.appendChild(script);
227
+ return script;
228
+ }
229
+
230
+ addComponentFileLinkElement(id, previewBundleFileName) {
231
+ const link = document.createElement('link');
232
+ const stringId = id.toString();
233
+ const previewRoute = `~aspect/component-preview`;
234
+ const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
235
+ link.setAttribute('href', href);
236
+
237
+ if (previewBundleFileName.endsWith('.css')) {
238
+ link.setAttribute('rel', 'stylesheet');
239
+ }
240
+
241
+ document.head.appendChild(link);
242
+ return link;
243
+ }
244
+
245
+ getPreviewScriptElement(id, name, previewBundleFileName, resolve, reject) {
246
+ const script = document.createElement('script');
247
+ script.setAttribute('defer', 'defer');
248
+ const stringId = id.toString(); // const previewRoute = `~aspect/preview`;
249
+
250
+ const previewRoute = `~aspect/component-preview`;
251
+ const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
252
+ script.src = src; // generate path to remote scope. [scope url]/
253
+
254
+ script.onload = () => {
255
+ const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];
256
+ if (!componentPreview) return reject(new (_exceptions().PreviewNotFound)(name));
257
+ const targetPreview = componentPreview[name];
258
+ if (!targetPreview) return reject(new (_exceptions().PreviewNotFound)(name));
259
+ return resolve(targetPreview);
260
+ };
261
+
262
+ return script;
263
+ }
150
264
  /**
151
265
  * register a new preview.
152
266
  */
267
+
268
+
153
269
  registerPreview(preview) {
154
270
  this.previewSlot.register(preview);
155
271
  return this;
@@ -202,6 +318,7 @@ class PreviewPreview {
202
318
  static async provider([pubsub], config, [previewSlot, renderingContextSlot]) {
203
319
  const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);
204
320
  window.addEventListener('hashchange', () => {
321
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
205
322
  preview.render();
206
323
  });
207
324
  return preview;
@@ -214,9 +331,10 @@ exports.PreviewPreview = PreviewPreview;
214
331
  (0, _defineProperty2().default)(PreviewPreview, "dependencies", [_pubsub().default]);
215
332
  (0, _defineProperty2().default)(PreviewPreview, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType()]);
216
333
 
217
- function linkModules(previewName, defaultModule, componentMap) {
334
+ function linkModules(previewName, defaultModule, isSplitComponentBundle, componentMap) {
218
335
  PREVIEW_MODULES[previewName] = {
219
336
  mainModule: defaultModule,
337
+ isSplitComponentBundle,
220
338
  componentMap
221
339
  };
222
340
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["preview.preview.runtime.tsx"],"names":["PREVIEW_MODULES","PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","previewName","componentId","getLocation","name","getDefault","preview","getPreview","PreviewNotFound","includes","include","map","prevName","includedPreview","undefined","selectPreviewModel","fullName","filter","module","render","getRenderingContext","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","registerPreview","register","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","defaultModule","componentMap","mainModule","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAIA,MAAMA,eAA8C,GAAG,EAAvD;;AAKO,MAAMC,cAAN,CAAqB;AAC1BC,EAAAA,WAAW;AACT;AACJ;AACA;AACYC,EAAAA,MAJC;AAMT;AACJ;AACA;AACYC,EAAAA,WATC,EAWDC,oBAXC,EAYT;AAAA,SARQF,MAQR,GARQA,MAQR;AAAA,SAHQC,WAGR,GAHQA,WAGR;AAAA,SADQC,oBACR,GADQA,oBACR;AAAA,oDAeO,MAAM;AACb,YAAM;AAAEC,QAAAA,WAAF;AAAeC,QAAAA;AAAf,UAA+B,KAAKC,WAAL,EAArC;AACA,YAAMC,IAAI,GAAGH,WAAW,IAAI,KAAKI,UAAL,EAA5B;AAEA,YAAMC,OAAO,GAAG,KAAKC,UAAL,CAAgBH,IAAhB,CAAhB;;AACA,UAAI,CAACE,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SAArB,CADR;AAELvD,MAAAA,WAAW,EAAEyD,2BAAYC,aAAZ,CAA0BJ,MAA1B;AAFR,KAAP;AAID;;AAQoB,eAARK,QAAQ,CACnB,CAAC/D,MAAD,CADmB,EAEnBgE,MAFmB,EAGnB,CAAC/D,WAAD,EAAcC,oBAAd,CAHmB,EAInB;AACA,UAAMM,OAAO,GAAG,IAAIV,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;AAEAsB,IAAAA,MAAM,CAACC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;AAC1CjB,MAAAA,OAAO,CAACa,MAAR;AACD,KAFD;AAIA,WAAOb,OAAP;AACD;;AAvHyB;;;gCAAfV,c,aAqGMmE,yB;gCArGNnE,c,kBAuGW,CAACoE,iBAAD,C;gCAvGXpE,c,WAyGI,CAACqE,gBAAKC,QAAL,EAAD,EAA+BD,gBAAKC,QAAL,EAA/B,C;;AAiBV,SAASC,WAAT,CAAqBlE,WAArB,EAA0CmE,aAA1C,EAA8DC,YAA9D,EAAoG;AACzG1E,EAAAA,eAAe,CAACM,WAAD,CAAf,GAA+B;AAC7BqE,IAAAA,UAAU,EAAEF,aADiB;AAE7BC,IAAAA;AAF6B,GAA/B;AAID;;AAEDrC,yBAAcuC,UAAd,CAAyB3E,cAAzB","sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\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';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nconst PREVIEW_MODULES: Record<string, PreviewModule> = {};\n\nexport type RenderingContextProvider = () => { [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 /**\n * render the preview.\n */\n render = () => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n const includes = (preview.include || [])\n .map((prevName) => {\n const includedPreview = this.getPreview(prevName);\n if (!includedPreview) return undefined;\n\n return includedPreview.selectPreviewModel?.(componentId.fullName, PREVIEW_MODULES[prevName]);\n })\n .filter((module) => !!module);\n\n return preview.render(componentId.fullName, PREVIEW_MODULES[name], includes, this.getRenderingContext());\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() {\n return new RenderingContext(this.renderingContextSlot);\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 preview.render();\n });\n\n return preview;\n }\n}\n\nexport function linkModules(previewName: string, defaultModule: any, componentMap: { [key: string]: any }) {\n PREVIEW_MODULES[previewName] = {\n mainModule: defaultModule,\n componentMap,\n };\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"]}
1
+ {"version":3,"sources":["preview.preview.runtime.tsx"],"names":["PREVIEW_MODULES","PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","previewName","componentId","getLocation","name","getDefault","preview","getPreview","PreviewNotFound","includesAll","Promise","all","include","map","prevName","includedPreview","undefined","selectPreviewModel","fullName","getPreviewModule","includes","filter","module","render","getRenderingContext","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","componentMap","component","fetchComponentPreview","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","forEach","file","endsWith","addComponentFileElement","resolve","reject","previewScriptElement","getPreviewScriptElement","document","head","appendChild","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","toString","url","res","status","parsed","json","files","length","script","createElement","setAttribute","previewRoute","src","link","href","onload","componentPreview","toStringWithoutVersion","targetPreview","registerPreview","register","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","defaultModule","isSplitComponentBundle","addRuntime"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CAA+B,CAA/B,CAApB;AACA,UAAM,CAACC,MAAD,EAASC,KAAT,IAAkBL,WAAW,CAACM,KAAZ,CAAkB,GAAlB,CAAxB;AAEA,WAAO;AACLvG,MAAAA,WAAW,EAAE,KAAK2F,QAAL,CAAcW,KAAd,EAAqB,SAArB,CADR;AAELrG,MAAAA,WAAW,EAAEuG,2BAAYC,aAAZ,CAA0BJ,MAA1B;AAFR,KAAP;AAID;;AAQoB,eAARK,QAAQ,CACnB,CAAC7G,MAAD,CADmB,EAEnB8G,MAFmB,EAGnB,CAAC7G,WAAD,EAAcC,oBAAd,CAHmB,EAInB;AACA,UAAMM,OAAO,GAAG,IAAIV,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;AAEA0B,IAAAA,MAAM,CAACC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;AAC1C;AACArB,MAAAA,OAAO,CAACiB,MAAR;AACD,KAHD;AAKA,WAAOjB,OAAP;AACD;;AApOyB;;;gCAAfV,c,aAiNMiH,yB;gCAjNNjH,c,kBAmNW,CAACkH,iBAAD,C;gCAnNXlH,c,WAqNI,CAACmH,gBAAKC,QAAL,EAAD,EAA+BD,gBAAKC,QAAL,EAA/B,C;;AAkBV,SAASC,WAAT,CACLhH,WADK,EAELiH,aAFK,EAGLC,sBAHK,EAIL5E,YAJK,EAKL;AACA5C,EAAAA,eAAe,CAACM,WAAD,CAAf,GAA+B;AAC7ByC,IAAAA,UAAU,EAAEwE,aADiB;AAE7BC,IAAAA,sBAF6B;AAG7B5E,IAAAA;AAH6B,GAA/B;AAKD;;AAEDH,yBAAcgF,UAAd,CAAyBxH,cAAzB","sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\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';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nconst PREVIEW_MODULES: Record<string, PreviewModule> = {};\n\nexport type RenderingContextProvider = () => { [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 /**\n * render the preview.\n */\n render = async () => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\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)\n );\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n\n return preview.render(\n componentId.fullName,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext()\n );\n };\n\n async getPreviewModule(name: string, id: ComponentID): Promise<PreviewModule> {\n if (PREVIEW_MODULES[name].componentMap[id.fullName]) return PREVIEW_MODULES[name];\n // if (!window[name]) throw new PreviewNotFound(name);\n // const isSplitComponentBundle = PREVIEW_MODULES[name].isSplitComponentBundle ?? false;\n // const component = window[id.toStringWithoutVersion()];\n const component: any = await this.fetchComponentPreview(id, name);\n\n return {\n mainModule: PREVIEW_MODULES[name].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 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[]> {\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 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 reject(new PreviewNotFound(name));\n\n return resolve(targetPreview);\n };\n return script;\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() {\n return new RenderingContext(this.renderingContextSlot);\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(\n previewName: string,\n defaultModule: any,\n isSplitComponentBundle: boolean,\n componentMap: { [key: string]: any }\n) {\n PREVIEW_MODULES[previewName] = {\n mainModule: defaultModule,\n isSplitComponentBundle,\n componentMap,\n };\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"]}
@@ -1,11 +1,8 @@
1
1
  /// <reference types="express" />
2
- import { Request, Response, Route } from '@teambit/express';
2
+ import type { NextFunction, Request, Response, Route } from '@teambit/express';
3
3
  import type { Logger } from '@teambit/logger';
4
4
  import { PreviewMain } from './preview.main.runtime';
5
- declare type UrlParams = {
6
- /** `/preview/:previewPath(*)` */
7
- previewPath?: string;
8
- };
5
+ import type { PreviewUrlParams } from './artifact-file-middleware';
9
6
  export declare class PreviewRoute implements Route {
10
7
  /**
11
8
  * preview extension.
@@ -19,6 +16,5 @@ export declare class PreviewRoute implements Route {
19
16
  preview: PreviewMain, logger: Logger);
20
17
  route: string;
21
18
  method: string;
22
- middlewares: ((req: Request<UrlParams>, res: Response) => Promise<import("express").Response<any>>)[];
19
+ middlewares: ((req: Request<PreviewUrlParams>, res: Response, next: NextFunction) => Promise<void | import("express").Response<any>>)[];
23
20
  }
24
- export {};
@@ -19,20 +19,20 @@ function _defineProperty2() {
19
19
  return data;
20
20
  }
21
21
 
22
- function _mime() {
23
- const data = _interopRequireDefault(require("mime"));
22
+ function _uiFoundationUiPages() {
23
+ const data = require("@teambit/ui-foundation.ui.pages.static-error");
24
24
 
25
- _mime = function () {
25
+ _uiFoundationUiPages = function () {
26
26
  return data;
27
27
  };
28
28
 
29
29
  return data;
30
30
  }
31
31
 
32
- function _uiFoundationUiPages() {
33
- const data = require("@teambit/ui-foundation.ui.pages.static-error");
32
+ function _artifactFileMiddleware() {
33
+ const data = require("./artifact-file-middleware");
34
34
 
35
- _uiFoundationUiPages = function () {
35
+ _artifactFileMiddleware = function () {
36
36
  return data;
37
37
  };
38
38
 
@@ -47,38 +47,39 @@ class PreviewRoute {
47
47
  preview, logger) {
48
48
  this.preview = preview;
49
49
  this.logger = logger;
50
- (0, _defineProperty2().default)(this, "route", `/preview/:previewPath(*)`);
50
+ (0, _defineProperty2().default)(this, "route", `/preview/:previewName?/:filePath(*)`);
51
51
  (0, _defineProperty2().default)(this, "method", 'get');
52
- (0, _defineProperty2().default)(this, "middlewares", [async (req, res) => {
52
+ (0, _defineProperty2().default)(this, "middlewares", [async (req, res, next) => {
53
53
  try {
54
- var _artifact;
55
-
56
54
  // @ts-ignore TODO: @guy please fix.
57
55
  const component = req.component;
58
56
  if (!component) return res.status(404).send((0, _uiFoundationUiPages().noPreview)());
57
+ const isLegacyPath = await this.preview.isBundledWithEnv(component);
59
58
  let artifact; // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680
60
59
 
61
60
  try {
62
- artifact = await this.preview.getPreview(component);
61
+ // Taking the env template (in this case we will take the component only bundle throw component-preview route)
62
+ // We use this route for the env template for backward compatibility - new scopes which contain components tagged with old versions of bit
63
+ if (!isLegacyPath) {
64
+ artifact = await this.preview.getEnvTemplateFromComponentEnv(component);
65
+ } else {
66
+ // If it's legacy (bundled together with the env template) take the preview bundle from the component directly
67
+ artifact = await this.preview.getPreview(component);
68
+ }
63
69
  } catch (e) {
64
70
  return res.status(404).send((0, _uiFoundationUiPages().noPreview)());
65
- } // TODO: please fix file path concatenation here.
66
-
71
+ } // @ts-ignore
67
72
 
68
- const file = (_artifact = artifact) === null || _artifact === void 0 ? void 0 : _artifact.getFile(`public/${req.params.previewPath || 'index.html'}`);
69
- if (!file) return res.status(404).send((0, _uiFoundationUiPages().noPreview)());
70
- const contents = file.contents;
71
- const str = `${file.cwd}/${file.path}`;
72
73
 
73
- const contentType = _mime().default.getType(str);
74
+ req.artifact = artifact; // @ts-ignore
74
75
 
75
- if (contentType) res.set('Content-Type', contentType);
76
- return res.send(contents);
76
+ req.isLegacyPath = isLegacyPath;
77
+ return next();
77
78
  } catch (e) {
78
79
  this.logger.error('failed getting preview', e);
79
80
  return res.status(500).send((0, _uiFoundationUiPages().serverError)());
80
81
  }
81
- }]);
82
+ }, (0, _artifactFileMiddleware().getArtifactFileMiddleware)(this.logger)]);
82
83
  }
83
84
 
84
85
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["preview.route.ts"],"names":["PreviewRoute","constructor","preview","logger","req","res","component","status","send","artifact","getPreview","e","file","getFile","params","previewPath","contents","str","cwd","path","contentType","mime","getType","set","error"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAWO,MAAMA,YAAN,CAAoC;AACzCC,EAAAA,WAAW;AACT;AACJ;AACA;AACYC,EAAAA,OAJC,EAKDC,MALC,EAMT;AAAA,SAFQD,OAER,GAFQA,OAER;AAAA,SADQC,MACR,GADQA,MACR;AAAA,mDAEO,0BAFP;AAAA,oDAGO,KAHP;AAAA,yDAKY,CACZ,OAAOC,GAAP,EAAgCC,GAAhC,KAAkD;AAChD,UAAI;AAAA;;AACF;AACA,cAAMC,SAAS,GAAGF,GAAG,CAACE,SAAtB;AACA,YAAI,CAACA,SAAL,EAAgB,OAAOD,GAAG,CAACE,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,uCAArB,CAAP;AAEhB,YAAIC,QAAJ,CALE,CAMF;;AACA,YAAI;AACFA,UAAAA,QAAQ,GAAG,MAAM,KAAKP,OAAL,CAAaQ,UAAb,CAAwBJ,SAAxB,CAAjB;AACD,SAFD,CAEE,OAAOK,CAAP,EAAe;AACf,iBAAON,GAAG,CAACE,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,uCAArB,CAAP;AACD,SAXC,CAYF;;;AACA,cAAMI,IAAI,gBAAGH,QAAH,8CAAG,UAAUI,OAAV,CAAmB,UAAST,GAAG,CAACU,MAAJ,CAAWC,WAAX,IAA0B,YAAa,EAAnE,CAAb;AACA,YAAI,CAACH,IAAL,EAAW,OAAOP,GAAG,CAACE,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,uCAArB,CAAP;AAEX,cAAMQ,QAAQ,GAAGJ,IAAI,CAACI,QAAtB;AACA,cAAMC,GAAG,GAAI,GAAEL,IAAI,CAACM,GAAI,IAAGN,IAAI,CAACO,IAAK,EAArC;;AACA,cAAMC,WAAW,GAAGC,gBAAKC,OAAL,CAAaL,GAAb,CAApB;;AACA,YAAIG,WAAJ,EAAiBf,GAAG,CAACkB,GAAJ,CAAQ,cAAR,EAAwBH,WAAxB;AACjB,eAAOf,GAAG,CAACG,IAAJ,CAASQ,QAAT,CAAP;AACD,OArBD,CAqBE,OAAOL,CAAP,EAAe;AACf,aAAKR,MAAL,CAAYqB,KAAZ,CAAkB,wBAAlB,EAA4Cb,CAA5C;AACA,eAAON,GAAG,CAACE,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,yCAArB,CAAP;AACD;AACF,KA3BW,CALZ;AAAE;;AAPqC","sourcesContent":["import { Request, Response, Route } from '@teambit/express';\nimport mime from 'mime';\nimport type { Component } from '@teambit/component';\nimport { noPreview, serverError } from '@teambit/ui-foundation.ui.pages.static-error';\nimport type { Logger } from '@teambit/logger';\n\nimport { PreviewMain } from './preview.main.runtime';\nimport { PreviewArtifact } from './preview-artifact';\n\ntype UrlParams = {\n /** `/preview/:previewPath(*)` */\n previewPath?: string;\n};\n\nexport class PreviewRoute implements Route {\n constructor(\n /**\n * preview extension.\n */\n private preview: PreviewMain,\n private logger: Logger\n ) {}\n\n route = `/preview/:previewPath(*)`;\n method = 'get';\n\n middlewares = [\n async (req: Request<UrlParams>, res: Response) => {\n try {\n // @ts-ignore TODO: @guy please fix.\n const component = req.component as Component | undefined;\n if (!component) return res.status(404).send(noPreview());\n\n let artifact: PreviewArtifact | undefined;\n // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680\n try {\n artifact = await this.preview.getPreview(component);\n } catch (e: any) {\n return res.status(404).send(noPreview());\n }\n // TODO: please fix file path concatenation here.\n const file = artifact?.getFile(`public/${req.params.previewPath || 'index.html'}`);\n if (!file) return res.status(404).send(noPreview());\n\n const contents = file.contents;\n const str = `${file.cwd}/${file.path}`;\n const contentType = mime.getType(str);\n if (contentType) res.set('Content-Type', contentType);\n return res.send(contents);\n } catch (e: any) {\n this.logger.error('failed getting preview', e);\n return res.status(500).send(serverError());\n }\n },\n ];\n}\n"]}
1
+ {"version":3,"sources":["preview.route.ts"],"names":["PreviewRoute","constructor","preview","logger","req","res","next","component","status","send","isLegacyPath","isBundledWithEnv","artifact","getEnvTemplateFromComponentEnv","getPreview","e","error"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAKA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGO,MAAMA,YAAN,CAAoC;AACzCC,EAAAA,WAAW;AACT;AACJ;AACA;AACYC,EAAAA,OAJC,EAKDC,MALC,EAMT;AAAA,SAFQD,OAER,GAFQA,OAER;AAAA,SADQC,MACR,GADQA,MACR;AAAA,mDAEO,qCAFP;AAAA,oDAGO,KAHP;AAAA,yDAKY,CACZ,OAAOC,GAAP,EAAuCC,GAAvC,EAAsDC,IAAtD,KAA6E;AAC3E,UAAI;AACF;AACA,cAAMC,SAAS,GAAGH,GAAG,CAACG,SAAtB;AACA,YAAI,CAACA,SAAL,EAAgB,OAAOF,GAAG,CAACG,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,uCAArB,CAAP;AAChB,cAAMC,YAAY,GAAG,MAAM,KAAKR,OAAL,CAAaS,gBAAb,CAA8BJ,SAA9B,CAA3B;AAEA,YAAIK,QAAJ,CANE,CAOF;;AACA,YAAI;AACF;AACA;AACA,cAAI,CAACF,YAAL,EAAmB;AACjBE,YAAAA,QAAQ,GAAG,MAAM,KAAKV,OAAL,CAAaW,8BAAb,CAA4CN,SAA5C,CAAjB;AACD,WAFD,MAEO;AACL;AACAK,YAAAA,QAAQ,GAAG,MAAM,KAAKV,OAAL,CAAaY,UAAb,CAAwBP,SAAxB,CAAjB;AACD;AACF,SATD,CASE,OAAOQ,CAAP,EAAe;AACf,iBAAOV,GAAG,CAACG,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,uCAArB,CAAP;AACD,SAnBC,CAoBF;;;AACAL,QAAAA,GAAG,CAACQ,QAAJ,GAAeA,QAAf,CArBE,CAsBF;;AACAR,QAAAA,GAAG,CAACM,YAAJ,GAAmBA,YAAnB;AACA,eAAOJ,IAAI,EAAX;AACD,OAzBD,CAyBE,OAAOS,CAAP,EAAe;AACf,aAAKZ,MAAL,CAAYa,KAAZ,CAAkB,wBAAlB,EAA4CD,CAA5C;AACA,eAAOV,GAAG,CAACG,MAAJ,CAAW,GAAX,EAAgBC,IAAhB,CAAqB,yCAArB,CAAP;AACD;AACF,KA/BW,EAgCZ,yDAA0B,KAAKN,MAA/B,CAhCY,CALZ;AAAE;;AAPqC","sourcesContent":["import type { NextFunction, Request, Response, Route } from '@teambit/express';\nimport type { Component } from '@teambit/component';\nimport { noPreview, serverError } from '@teambit/ui-foundation.ui.pages.static-error';\nimport type { Logger } from '@teambit/logger';\n\nimport { PreviewMain } from './preview.main.runtime';\nimport { PreviewArtifact } from './preview-artifact';\nimport { getArtifactFileMiddleware } from './artifact-file-middleware';\nimport type { PreviewUrlParams } from './artifact-file-middleware';\n\nexport class PreviewRoute implements Route {\n constructor(\n /**\n * preview extension.\n */\n private preview: PreviewMain,\n private logger: Logger\n ) {}\n\n route = `/preview/:previewName?/:filePath(*)`;\n method = 'get';\n\n middlewares = [\n async (req: Request<PreviewUrlParams>, res: Response, next: NextFunction) => {\n try {\n // @ts-ignore TODO: @guy please fix.\n const component = req.component as Component | undefined;\n if (!component) return res.status(404).send(noPreview());\n const isLegacyPath = await this.preview.isBundledWithEnv(component);\n\n let artifact: PreviewArtifact | undefined;\n // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680\n try {\n // Taking the env template (in this case we will take the component only bundle throw component-preview route)\n // We use this route for the env template for backward compatibility - new scopes which contain components tagged with old versions of bit\n if (!isLegacyPath) {\n artifact = await this.preview.getEnvTemplateFromComponentEnv(component);\n } else {\n // If it's legacy (bundled together with the env template) take the preview bundle from the component directly\n artifact = await this.preview.getPreview(component);\n }\n } catch (e: any) {\n return res.status(404).send(noPreview());\n }\n // @ts-ignore\n req.artifact = artifact;\n // @ts-ignore\n req.isLegacyPath = isLegacyPath;\n return next();\n } catch (e: any) {\n this.logger.error('failed getting preview', e);\n return res.status(500).send(serverError());\n }\n },\n getArtifactFileMiddleware(this.logger),\n ];\n}\n"]}
@@ -4,8 +4,8 @@ import { BundlerMain } from '@teambit/bundler';
4
4
  import { ComponentMap } from '@teambit/component';
5
5
  import { Capsule } from '@teambit/isolator';
6
6
  import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
7
- import { PreviewDefinition } from './preview-definition';
8
7
  import { PreviewMain } from './preview.main.runtime';
8
+ export declare const PREVIEW_TASK_NAME = "GeneratePreview";
9
9
  export declare class PreviewTask implements BuildTask {
10
10
  /**
11
11
  * bundler extension.
@@ -28,7 +28,7 @@ export declare class PreviewTask implements BuildTask {
28
28
  name: string;
29
29
  location: TaskLocation;
30
30
  execute(context: BuildContext): Promise<BuiltTaskResult>;
31
- computePaths(capsule: Capsule, defs: PreviewDefinition[], context: BuildContext): Promise<string[]>;
31
+ getLinkFileDirectory(): string;
32
32
  getPreviewDirectory(context: ExecutionContext): string;
33
33
  getPathsFromMap(capsule: Capsule, moduleMap: ComponentMap<AbstractVinyl[]>, context: BuildContext): ComponentMap<string[]>;
34
34
  }
@@ -2,14 +2,12 @@
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
4
 
5
- require("core-js/modules/es.array.iterator.js");
6
-
7
5
  require("core-js/modules/es.promise.js");
8
6
 
9
7
  Object.defineProperty(exports, "__esModule", {
10
8
  value: true
11
9
  });
12
- exports.PreviewTask = void 0;
10
+ exports.PreviewTask = exports.PREVIEW_TASK_NAME = void 0;
13
11
 
14
12
  function _defineProperty2() {
15
13
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
@@ -31,16 +29,19 @@ function _path() {
31
29
  return data;
32
30
  }
33
31
 
34
- function _lodash() {
35
- const data = require("lodash");
32
+ function _builder() {
33
+ const data = require("@teambit/builder");
36
34
 
37
- _lodash = function () {
35
+ _builder = function () {
38
36
  return data;
39
37
  };
40
38
 
41
39
  return data;
42
40
  }
43
41
 
42
+ const PREVIEW_TASK_NAME = 'GeneratePreview';
43
+ exports.PREVIEW_TASK_NAME = PREVIEW_TASK_NAME;
44
+
44
45
  class PreviewTask {
45
46
  constructor(
46
47
  /**
@@ -54,39 +55,39 @@ class PreviewTask {
54
55
  this.bundler = bundler;
55
56
  this.preview = preview;
56
57
  (0, _defineProperty2().default)(this, "aspectId", 'teambit.preview/preview');
57
- (0, _defineProperty2().default)(this, "name", 'GeneratePreview');
58
+ (0, _defineProperty2().default)(this, "name", PREVIEW_TASK_NAME);
58
59
  (0, _defineProperty2().default)(this, "location", 'end');
59
60
  }
60
61
 
62
+ // readonly dependencies = [CompilerAspect.id];
61
63
  async execute(context) {
64
+ var _envPreviewConfig$spl;
65
+
62
66
  const defs = this.preview.getDefs();
63
67
  const url = `/preview/${context.envRuntime.id}`;
64
- const bundlingStrategy = this.preview.getBundlingStrategy();
65
- const targets = await bundlingStrategy.computeTargets(context, defs, this);
68
+ const bundlingStrategy = this.preview.getBundlingStrategy(context.env);
69
+ const envPreviewConfig = this.preview.getEnvPreviewConfig(context.env);
70
+ const splitComponentBundle = (_envPreviewConfig$spl = envPreviewConfig.splitComponentBundle) !== null && _envPreviewConfig$spl !== void 0 ? _envPreviewConfig$spl : false;
71
+ const computeTargetsContext = Object.assign(context, {
72
+ splitComponentBundle
73
+ });
74
+ const targets = await bundlingStrategy.computeTargets(computeTargetsContext, defs, this);
66
75
  const bundlerContext = Object.assign(context, {
67
76
  targets,
77
+ externalizePeer: bundlingStrategy.name !== 'env',
68
78
  entry: [],
69
79
  publicPath: this.getPreviewDirectory(context),
70
- rootPath: url
80
+ rootPath: url,
81
+ development: context.dev
71
82
  });
72
83
  const bundler = await context.env.getBundler(bundlerContext, []);
73
84
  const bundlerResults = await bundler.run();
74
- return bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);
85
+ const results = bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);
86
+ return results;
75
87
  }
76
88
 
77
- async computePaths(capsule, defs, context) {
78
- const previewMain = await this.preview.writePreviewRuntime(context);
79
- const moduleMapsPromise = defs.map(async previewDef => {
80
- const moduleMap = await previewDef.getModuleMap([capsule.component]);
81
- const paths = this.getPathsFromMap(capsule, moduleMap, context);
82
- const template = previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : 'undefined';
83
- const link = this.preview.writeLink(previewDef.prefix, paths, previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : undefined, capsule.path);
84
- const files = (0, _lodash().flatten)(paths.toArray().map(([, file]) => file)).concat([link]);
85
- if (template) return files.concat([template]);
86
- return files;
87
- });
88
- const moduleMaps = await Promise.all(moduleMapsPromise);
89
- return (0, _lodash().flatten)(moduleMaps.concat([previewMain]));
89
+ getLinkFileDirectory() {
90
+ return (0, _path().join)(_builder().CAPSULE_ARTIFACTS_DIR, 'preview-links');
90
91
  }
91
92
 
92
93
  getPreviewDirectory(context) {
@@ -1 +1 @@
1
- {"version":3,"sources":["preview.task.ts"],"names":["PreviewTask","constructor","bundler","preview","execute","context","defs","getDefs","url","envRuntime","id","bundlingStrategy","getBundlingStrategy","targets","computeTargets","bundlerContext","Object","assign","entry","publicPath","getPreviewDirectory","rootPath","env","getBundler","bundlerResults","run","computeResults","computePaths","capsule","previewMain","writePreviewRuntime","moduleMapsPromise","map","previewDef","moduleMap","getModuleMap","component","paths","getPathsFromMap","template","renderTemplatePath","link","writeLink","prefix","undefined","path","files","toArray","file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D,CAAlB,CAAR,CAAP;AACD;;AAEDT,EAAAA,mBAAmB,CAACf,OAAD,EAA4B;AAC7C,UAAMgD,UAAU,GAAG,qBAAS,GAAEhD,OAAO,CAACK,EAAG,SAAtB,CAAnB;AACA,WAAO2C,UAAP;AACD;;AAEDf,EAAAA,eAAe,CACbV,OADa,EAEbM,SAFa,EAGb7B,OAHa,EAIW;AACxB,UAAMiD,QAAkB,GAAGjD,OAAO,CAACiB,GAAR,CAAYiC,WAAZ,CAAwBlD,OAAxB,CAA3B;AACA,WAAO6B,SAAS,CAACF,GAAV,CAAec,KAAD,IAAW;AAC9B,aAAOA,KAAK,CAACd,GAAN,CAAWgB,IAAD,IAAU,kBAAKpB,OAAO,CAACiB,IAAb,EAAmBS,QAAQ,CAACE,oBAAT,CAA8BR,IAAI,CAACS,QAAnC,CAAnB,CAApB,CAAP;AACD,KAFM,CAAP;AAGD;;AA7E2C","sourcesContent":["import { resolve, join } from 'path';\nimport { ExecutionContext } from '@teambit/envs';\nimport { BuildContext, BuiltTaskResult, BuildTask, TaskLocation } from '@teambit/builder';\nimport { Bundler, BundlerContext, BundlerMain, Target } from '@teambit/bundler';\nimport { Compiler } from '@teambit/compiler';\nimport { ComponentMap } from '@teambit/component';\nimport { Capsule } from '@teambit/isolator';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { flatten } from 'lodash';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewMain } from './preview.main.runtime';\n\nexport class PreviewTask implements BuildTask {\n constructor(\n /**\n * bundler extension.\n */\n private bundler: BundlerMain,\n\n /**\n * preview extension.\n */\n private preview: PreviewMain\n ) {}\n\n aspectId = 'teambit.preview/preview';\n name = 'GeneratePreview';\n location: TaskLocation = 'end';\n\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n const defs = this.preview.getDefs();\n const url = `/preview/${context.envRuntime.id}`;\n const bundlingStrategy = this.preview.getBundlingStrategy();\n\n const targets: Target[] = await bundlingStrategy.computeTargets(context, defs, this);\n\n const bundlerContext: BundlerContext = Object.assign(context, {\n targets,\n entry: [],\n publicPath: this.getPreviewDirectory(context),\n rootPath: url,\n });\n\n const bundler: Bundler = await context.env.getBundler(bundlerContext, []);\n const bundlerResults = await bundler.run();\n\n return bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);\n }\n\n async computePaths(capsule: Capsule, defs: PreviewDefinition[], context: BuildContext): Promise<string[]> {\n const previewMain = await this.preview.writePreviewRuntime(context);\n\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([capsule.component]);\n const paths = this.getPathsFromMap(capsule, moduleMap, context);\n const template = previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : 'undefined';\n\n const link = this.preview.writeLink(\n previewDef.prefix,\n paths,\n previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : undefined,\n capsule.path\n );\n\n const files = flatten(paths.toArray().map(([, file]) => file)).concat([link]);\n\n if (template) return files.concat([template]);\n return files;\n });\n\n const moduleMaps = await Promise.all(moduleMapsPromise);\n\n return flatten(moduleMaps.concat([previewMain]));\n }\n\n getPreviewDirectory(context: ExecutionContext) {\n const outputPath = resolve(`${context.id}/public`);\n return outputPath;\n }\n\n getPathsFromMap(\n capsule: Capsule,\n moduleMap: ComponentMap<AbstractVinyl[]>,\n context: BuildContext\n ): ComponentMap<string[]> {\n const compiler: Compiler = context.env.getCompiler(context);\n return moduleMap.map((files) => {\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["preview.task.ts"],"names":["PREVIEW_TASK_NAME","PreviewTask","constructor","bundler","preview","execute","context","defs","getDefs","url","envRuntime","id","bundlingStrategy","getBundlingStrategy","env","envPreviewConfig","getEnvPreviewConfig","splitComponentBundle","computeTargetsContext","Object","assign","targets","computeTargets","bundlerContext","externalizePeer","name","entry","publicPath","getPreviewDirectory","rootPath","development","dev","getBundler","bundlerResults","run","results","computeResults","getLinkFileDirectory","CAPSULE_ARTIFACTS_DIR","outputPath","getPathsFromMap","capsule","moduleMap","compiler","getCompiler","map","files","file","path","getDistPathBySrcPath","relative"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAQO,MAAMA,iBAAiB,GAAG,iBAA1B;;;AACA,MAAMC,WAAN,CAAuC;AAC5CC,EAAAA,WAAW;AACT;AACJ;AACA;AACYC,EAAAA,OAJC;AAMT;AACJ;AACA;AACYC,EAAAA,OATC,EAUT;AAAA,SANQD,OAMR,GANQA,OAMR;AAAA,SADQC,OACR,GADQA,OACR;AAAA,sDAES,yBAFT;AAAA,kDAGKJ,iBAHL;AAAA,sDAIuB,KAJvB;AAAE;;AAKJ;AAEa,QAAPK,OAAO,CAACC,OAAD,EAAkD;AAAA;;AAC7D,UAAMC,IAAI,GAAG,KAAKH,OAAL,CAAaI,OAAb,EAAb;AACA,UAAMC,GAAG,GAAI,YAAWH,OAAO,CAACI,UAAR,CAAmBC,EAAG,EAA9C;AACA,UAAMC,gBAAgB,GAAG,KAAKR,OAAL,CAAaS,mBAAb,CAAiCP,OAAO,CAACQ,GAAzC,CAAzB;AACA,UAAMC,gBAAgB,GAAG,KAAKX,OAAL,CAAaY,mBAAb,CAAiCV,OAAO,CAACQ,GAAzC,CAAzB;AACA,UAAMG,oBAAoB,4BAAGF,gBAAgB,CAACE,oBAApB,yEAA4C,KAAtE;AACA,UAAMC,qBAAqB,GAAGC,MAAM,CAACC,MAAP,CAAcd,OAAd,EAAuB;AAAEW,MAAAA;AAAF,KAAvB,CAA9B;AAEA,UAAMI,OAAiB,GAAG,MAAMT,gBAAgB,CAACU,cAAjB,CAAgCJ,qBAAhC,EAAuDX,IAAvD,EAA6D,IAA7D,CAAhC;AAEA,UAAMgB,cAA8B,GAAGJ,MAAM,CAACC,MAAP,CAAcd,OAAd,EAAuB;A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{ ExecutionContext } from '@teambit/envs';\nimport { BuildContext, BuiltTaskResult, BuildTask, TaskLocation, CAPSULE_ARTIFACTS_DIR } from '@teambit/builder';\nimport { Bundler, BundlerContext, BundlerMain, Target } from '@teambit/bundler';\nimport { Compiler } from '@teambit/compiler';\nimport { ComponentMap } from '@teambit/component';\nimport { Capsule } from '@teambit/isolator';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { PreviewMain } from './preview.main.runtime';\n\nexport const PREVIEW_TASK_NAME = 'GeneratePreview';\nexport class PreviewTask implements BuildTask {\n constructor(\n /**\n * bundler extension.\n */\n private bundler: BundlerMain,\n\n /**\n * preview extension.\n */\n private preview: PreviewMain\n ) {}\n\n aspectId = 'teambit.preview/preview';\n name = PREVIEW_TASK_NAME;\n location: TaskLocation = 'end';\n // readonly dependencies = [CompilerAspect.id];\n\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n const defs = this.preview.getDefs();\n const url = `/preview/${context.envRuntime.id}`;\n const bundlingStrategy = this.preview.getBundlingStrategy(context.env);\n const envPreviewConfig = this.preview.getEnvPreviewConfig(context.env);\n const splitComponentBundle = envPreviewConfig.splitComponentBundle ?? false;\n const computeTargetsContext = Object.assign(context, { splitComponentBundle });\n\n const targets: Target[] = await bundlingStrategy.computeTargets(computeTargetsContext, defs, this);\n\n const bundlerContext: BundlerContext = Object.assign(context, {\n targets,\n externalizePeer: bundlingStrategy.name !== 'env',\n entry: [],\n publicPath: this.getPreviewDirectory(context),\n rootPath: url,\n development: context.dev,\n });\n\n const bundler: Bundler = await context.env.getBundler(bundlerContext, []);\n const bundlerResults = await bundler.run();\n\n const results = bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);\n return results;\n }\n\n getLinkFileDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview-links');\n }\n\n getPreviewDirectory(context: ExecutionContext) {\n const outputPath = resolve(`${context.id}/public`);\n return outputPath;\n }\n\n getPathsFromMap(\n capsule: Capsule,\n moduleMap: ComponentMap<AbstractVinyl[]>,\n context: BuildContext\n ): ComponentMap<string[]> {\n const compiler: Compiler = context.env.getCompiler(context);\n return moduleMap.map((files) => {\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n });\n }\n}\n"]}
@@ -1,20 +1,60 @@
1
- import { BuildContext } from '@teambit/builder';
2
- import { Target, BundlerResult, BundlerContext } from '@teambit/bundler';
3
- import { BundlingStrategy } from '../bundling-strategy';
4
- import { PreviewDefinition } from '../preview-definition';
5
- import { PreviewTask } from '../preview.task';
1
+ import { Component } from '@teambit/component';
2
+ import { ComponentResult } from '@teambit/builder';
3
+ import type { PkgMain } from '@teambit/pkg';
4
+ import type { DependencyResolverMain } from '@teambit/dependency-resolver';
5
+ import type { BundlerResult, BundlerContext, BundlerEntryMap } from '@teambit/bundler';
6
+ import { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
7
+ import type { PreviewDefinition } from '../preview-definition';
8
+ import type { PreviewMain } from '../preview.main.runtime';
9
+ export declare const PREVIEW_CHUNK_SUFFIX = "preview";
10
+ export declare const COMPONENT_CHUNK_SUFFIX = "component";
11
+ export declare const PREVIEW_CHUNK_FILENAME_SUFFIX: string;
12
+ export declare const COMPONENT_CHUNK_FILENAME_SUFFIX: string;
13
+ export declare const COMPONENT_STRATEGY_SIZE_KEY_NAME = "size";
14
+ export declare const COMPONENT_STRATEGY_ARTIFACT_NAME = "preview-component";
15
+ /**
16
+ * bundles all components in a given env into the same bundle.
17
+ */
6
18
  export declare class ComponentBundlingStrategy implements BundlingStrategy {
19
+ private preview;
20
+ private pkg;
21
+ private dependencyResolver;
7
22
  name: string;
8
- computeTargets(context: BuildContext, previewDefs: PreviewDefinition[], previewTask: PreviewTask): Promise<Target[]>;
9
- computeResults(context: BundlerContext, results: BundlerResult[], previewTask: PreviewTask): Promise<{
10
- componentsResults: {
11
- errors: Error[];
12
- component: import("@teambit/component").Component;
13
- warning: string[];
14
- }[];
23
+ constructor(preview: PreviewMain, pkg: PkgMain, dependencyResolver: DependencyResolverMain);
24
+ computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<{
25
+ entries: BundlerEntryMap;
26
+ components: Component[];
27
+ outputPath: string;
28
+ }[]>;
29
+ computeComponentEntry(previewDefs: PreviewDefinition[], component: Component, context: ComputeTargetsContext): Promise<{
30
+ [x: string]: {
31
+ filename: string;
32
+ import: string;
33
+ library: {
34
+ name: string;
35
+ type: string;
36
+ };
37
+ };
38
+ }>;
39
+ private getComponentChunkId;
40
+ private getComponentChunkFileName;
41
+ private getAssetAbsolutePath;
42
+ copyAssetsToCapsules(context: BundlerContext, result: BundlerResult): void;
43
+ private findAssetsForComponent;
44
+ private getArtifactDirectory;
45
+ private computeComponentMetadata;
46
+ computeResults(context: BundlerContext, results: BundlerResult[]): Promise<{
47
+ componentsResults: ComponentResult[];
15
48
  artifacts: {
16
49
  name: string;
17
50
  globPatterns: string[];
51
+ rootDir: string;
18
52
  }[];
19
53
  }>;
54
+ private getArtifactDef;
55
+ getDirName(context: ComputeTargetsContext): string;
56
+ private getOutputPath;
57
+ private getPaths;
58
+ private getComponentOutputPath;
59
+ private computePaths;
20
60
  }