@teambit/preview 0.0.769 → 0.0.772

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/bundler/chunks.ts +51 -0
  2. package/bundler/html-plugin.ts +24 -0
  3. package/{webpack/html.ts → bundler/html-template.ts} +0 -0
  4. package/dist/bundler/chunks.d.ts +17 -0
  5. package/dist/bundler/chunks.js +68 -0
  6. package/dist/bundler/chunks.js.map +1 -0
  7. package/dist/bundler/html-plugin.d.ts +5 -0
  8. package/dist/bundler/html-plugin.js +56 -0
  9. package/dist/bundler/html-plugin.js.map +1 -0
  10. package/dist/{webpack/html.d.ts → bundler/html-template.d.ts} +0 -0
  11. package/dist/{webpack/html.js → bundler/html-template.js} +1 -1
  12. package/dist/bundler/html-template.js.map +1 -0
  13. package/dist/env-preview-template.task.d.ts +4 -9
  14. package/dist/env-preview-template.task.js +64 -74
  15. package/dist/env-preview-template.task.js.map +1 -1
  16. package/dist/preview-modules.d.ts +10 -0
  17. package/dist/preview-modules.js +54 -0
  18. package/dist/preview-modules.js.map +1 -0
  19. package/dist/preview.preview.runtime.d.ts +8 -5
  20. package/dist/preview.preview.runtime.js +76 -43
  21. package/dist/preview.preview.runtime.js.map +1 -1
  22. package/dist/strategies/component-strategy.js +6 -4
  23. package/dist/strategies/component-strategy.js.map +1 -1
  24. package/dist/strategies/env-strategy.js +4 -4
  25. package/dist/strategies/env-strategy.js.map +1 -1
  26. package/dist/strategies/generate-component-link.js +27 -3
  27. package/dist/strategies/generate-component-link.js.map +1 -1
  28. package/package-tar/teambit-preview-0.0.772.tgz +0 -0
  29. package/package.json +23 -21
  30. package/preview-1656362028747.js +5 -0
  31. package/preview-modules.tsx +28 -0
  32. package/preview.preview.runtime.tsx +71 -51
  33. package/strategies/component-strategy.ts +3 -3
  34. package/strategies/env-strategy.ts +1 -1
  35. package/strategies/generate-component-link.ts +20 -8
  36. package/dist/webpack/html.js.map +0 -1
  37. package/dist/webpack/index.d.ts +0 -1
  38. package/dist/webpack/index.js +0 -23
  39. package/dist/webpack/index.js.map +0 -1
  40. package/package-tar/teambit-preview-0.0.769.tgz +0 -0
  41. package/preview-1655954795354.js +0 -2
  42. package/webpack/index.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"names":["ENV_STRATEGY_ARTIFACT_NAME","EnvBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","htmlConfig","generateHtmlConfig","dev","peers","getPeerDependenciesListFromEnv","env","entries","computePaths","html","components","hostDependencies","aliasHostDependencies","options","config","title","templateContent","cache","minify","computeResults","results","result","componentsResults","map","component","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","rootDir","getDirName","name","globPatterns","envName","id","replace","resolve","capsuleNetwork","capsulesRootDir","getPaths","files","capsule","compiler","getCompiler","file","join","path","getDistPathBySrcPath","relative","defs","previewMain","writePreviewRuntime","moduleMapsPromise","previewDef","moduleMap","getModuleMap","paths","ComponentMap","as","graphCapsules","getCapsule","maybeFiles","get","compiledPaths","template","renderTemplatePath","link","writeLink","prefix","undefined","flatten","toArray","concat","moduleMaps","Promise","all"],"sources":["env-strategy.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { flatten } from 'lodash';\nimport { ComponentMap } from '@teambit/component';\nimport { Compiler } from '@teambit/compiler';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { Capsule } from '@teambit/isolator';\nimport { ComponentResult } from '@teambit/builder';\nimport { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';\nimport { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { PkgMain } from '@teambit/pkg';\nimport type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport { PreviewDefinition } from '../preview-definition';\nimport { PreviewMain } from '../preview.main.runtime';\nimport { html } from '../webpack';\n\nexport const ENV_STRATEGY_ARTIFACT_NAME = 'preview';\n\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class EnvBundlingStrategy implements BundlingStrategy {\n name = 'env';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const htmlConfig = this.generateHtmlConfig({ dev: context.dev });\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n return [\n {\n entries: await this.computePaths(outputPath, previewDefs, context),\n html: [htmlConfig],\n components: context.components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n },\n ];\n }\n\n private generateHtmlConfig(options: { dev?: boolean }): BundlerHtmlConfig {\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n cache: false,\n minify: options?.dev ?? true,\n };\n return config;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef(context);\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef(context: ComputeTargetsContext) {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n const env: 'env' = 'env';\n const rootDir = this.getDirName(context);\n\n return [\n {\n name: ENV_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['public/**'],\n rootDir,\n context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, files: AbstractVinyl[], capsule: Capsule) {\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private async computePaths(\n outputPath: string,\n defs: PreviewDefinition[],\n context: ComputeTargetsContext\n ): Promise<string[]> {\n const previewMain = await this.preview.writePreviewRuntime(context);\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap(context.components);\n\n const paths = ComponentMap.as(context.components, (component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, files, capsule);\n return compiledPaths;\n });\n\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 outputPath,\n false\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"],"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;;AAWA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,MAAMA,0BAA0B,GAAG,SAAnC;AAEP;AACA;AACA;;;;AACO,MAAMC,mBAAN,CAAsD;EAG3DC,WAAW,CAASC,OAAT,EAAuCC,GAAvC,EAA6DC,kBAA7D,EAAyG;IAAA,KAAhGF,OAAgG,GAAhGA,OAAg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X,GAAgC,MAAMZ,UAAU,CAACY,kBAAX,CAA8B3E,OAA9B,CAAtC,GAA+E+E,SAHpE,EAIX7E,UAJW,EAKX,KALW,CAAb;MAQA,MAAMgD,KAAK,GAAG,IAAA8B,iBAAA,EAAQd,KAAK,CAACe,OAAN,GAAgBrD,GAAhB,CAAoB,CAAC,GAAG0B,IAAH,CAAD,KAAcA,IAAlC,CAAR,EAAiD4B,MAAjD,CAAwD,CAACN,IAAD,CAAxD,CAAd;MAEA,IAAIF,QAAJ,EAAc,OAAOxB,KAAK,CAACgC,MAAN,CAAa,CAACR,QAAD,CAAb,CAAP;MACd,OAAOxB,KAAP;IACD,CA1ByB,CAA1B;IA4BA,MAAMiC,UAAU,GAAG,MAAMC,OAAO,CAACC,GAAR,CAAYvB,iBAAZ,CAAzB;IAEA,OAAO,IAAAkB,iBAAA,EAAQG,UAAU,CAACD,MAAX,CAAkB,CAACtB,WAAD,CAAlB,CAAR,CAAP;EACD;;AA1H0D"}
1
+ {"version":3,"names":["ENV_STRATEGY_ARTIFACT_NAME","EnvBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","htmlConfig","generateHtmlConfig","dev","peers","getPeerDependenciesListFromEnv","env","entries","computePaths","html","components","hostDependencies","aliasHostDependencies","options","config","title","templateContent","cache","minify","computeResults","results","result","componentsResults","map","component","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","rootDir","getDirName","name","globPatterns","envName","id","replace","resolve","capsuleNetwork","capsulesRootDir","getPaths","files","capsule","compiler","getCompiler","file","join","path","getDistPathBySrcPath","relative","defs","previewMain","writePreviewRuntime","moduleMapsPromise","previewDef","moduleMap","getModuleMap","paths","ComponentMap","as","graphCapsules","getCapsule","maybeFiles","get","compiledPaths","template","renderTemplatePath","link","writeLink","prefix","undefined","flatten","toArray","concat","moduleMaps","Promise","all"],"sources":["env-strategy.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { flatten } from 'lodash';\nimport { ComponentMap } from '@teambit/component';\nimport { Compiler } from '@teambit/compiler';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { Capsule } from '@teambit/isolator';\nimport { ComponentResult } from '@teambit/builder';\nimport { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';\nimport { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { PkgMain } from '@teambit/pkg';\nimport type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport { PreviewDefinition } from '../preview-definition';\nimport { PreviewMain } from '../preview.main.runtime';\nimport { html } from '../bundler/html-template';\n\nexport const ENV_STRATEGY_ARTIFACT_NAME = 'preview';\n\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class EnvBundlingStrategy implements BundlingStrategy {\n name = 'env';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const htmlConfig = this.generateHtmlConfig({ dev: context.dev });\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n return [\n {\n entries: await this.computePaths(outputPath, previewDefs, context),\n html: [htmlConfig],\n components: context.components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n },\n ];\n }\n\n private generateHtmlConfig(options: { dev?: boolean }): BundlerHtmlConfig {\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n cache: false,\n minify: options?.dev ?? true,\n };\n return config;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef(context);\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef(context: ComputeTargetsContext) {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n const env: 'env' = 'env';\n const rootDir = this.getDirName(context);\n\n return [\n {\n name: ENV_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['public/**'],\n rootDir,\n context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, files: AbstractVinyl[], capsule: Capsule) {\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private async computePaths(\n outputPath: string,\n defs: PreviewDefinition[],\n context: ComputeTargetsContext\n ): Promise<string[]> {\n const previewMain = await this.preview.writePreviewRuntime(context);\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap(context.components);\n\n const paths = ComponentMap.as(context.components, (component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, files, capsule);\n return compiledPaths;\n });\n\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 outputPath,\n false\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"],"mappings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e,CAACpB,OAApB,EAA6B,OAAO,EAAP;QAC7B,MAAM,GAAGD,KAAH,IAAYqB,UAAlB;QACA,MAAME,aAAa,GAAG,KAAKxB,QAAL,CAAcjD,OAAd,EAAuBkD,KAAvB,EAA8BC,OAA9B,CAAtB;QACA,OAAOsB,aAAP;MACD,CAPa,CAAd;;MASA,MAAMC,QAAQ,GAAGX,UAAU,CAACY,kBAAX,GAAgC,MAAMZ,UAAU,CAACY,kBAAX,CAA8B3E,OAA9B,CAAtC,GAA+E,WAAhG;MAEA,MAAM4E,IAAI,GAAG,KAAKhF,OAAL,CAAaiF,SAAb,CACXd,UAAU,CAACe,MADA,EAEXZ,KAFW,EAGXH,UAAU,CAACY,kBAAX,GAAgC,MAAMZ,UAAU,CAACY,kBAAX,CAA8B3E,OAA9B,CAAtC,GAA+E+E,SAHpE,EAIX7E,UAJW,EAKX,KALW,CAAb;MAQA,MAAMgD,KAAK,GAAG,IAAA8B,iBAAA,EAAQd,KAAK,CAACe,OAAN,GAAgBrD,GAAhB,CAAoB,CAAC,GAAG0B,IAAH,CAAD,KAAcA,IAAlC,CAAR,EAAiD4B,MAAjD,CAAwD,CAACN,IAAD,CAAxD,CAAd;MAEA,IAAIF,QAAJ,EAAc,OAAOxB,KAAK,CAACgC,MAAN,CAAa,CAACR,QAAD,CAAb,CAAP;MACd,OAAOxB,KAAP;IACD,CA1ByB,CAA1B;IA4BA,MAAMiC,UAAU,GAAG,MAAMC,OAAO,CAACC,GAAR,CAAYvB,iBAAZ,CAAzB;IAEA,OAAO,IAAAkB,iBAAA,EAAQG,UAAU,CAACD,MAAX,CAAkB,CAACtB,WAAD,CAAlB,CAAR,CAAP;EACD;;AA1H0D"}
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
 
3
+ require("core-js/modules/es.array.iterator.js");
4
+
3
5
  Object.defineProperty(exports, "__esModule", {
4
6
  value: true
5
7
  });
@@ -16,9 +18,31 @@ function _toolboxPath() {
16
18
  }
17
19
 
18
20
  function generateComponentLink(modules) {
19
- return `${modules.map(moduleVar => {
20
- return `export const ${moduleVar.prefix} = [${moduleVar.paths.map(path => `require('${(0, _toolboxPath().toWindowsCompatiblePath)(path)}')`).join(', ')}]`; // return `export { * as ${moduleVar.prefix} } from '${toWindowsCompatiblePath(moduleVar.paths)}'`;
21
- }).join('\n')}
21
+ const links = modules.map(({
22
+ prefix,
23
+ paths
24
+ }) => ({
25
+ name: prefix,
26
+ entries: paths.map((path, idx) => ({
27
+ path: (0, _toolboxPath().toWindowsCompatiblePath)(path),
28
+ linkName: `${prefix}_${idx}`
29
+ }))
30
+ })); // import per preview file
31
+
32
+ const importStr = links.map(({
33
+ entries
34
+ }) => entries.map(({
35
+ path,
36
+ linkName
37
+ }) => `import * as ${linkName} from '${path}'`).join(';\n')).join('\n'); // export files group per preview
38
+
39
+ const exportsString = links.map(({
40
+ name,
41
+ entries
42
+ }) => `export const ${name} = [${entries.map(entry => entry.linkName).join(', ')}]`).join(';\n');
43
+ return `${importStr}
44
+
45
+ ${exportsString}
22
46
  `;
23
47
  }
24
48
 
@@ -1 +1 @@
1
- {"version":3,"names":["generateComponentLink","modules","map","moduleVar","prefix","paths","path","toWindowsCompatiblePath","join"],"sources":["generate-component-link.ts"],"sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\n\nexport type ModuleVar = {\n prefix: string;\n paths: string[];\n};\n\nexport function generateComponentLink(modules: ModuleVar[]): string {\n return `${modules\n .map((moduleVar) => {\n return `export const ${moduleVar.prefix} = [${moduleVar.paths\n .map((path) => `require('${toWindowsCompatiblePath(path)}')`)\n .join(', ')}]`;\n\n // return `export { * as ${moduleVar.prefix} } from '${toWindowsCompatiblePath(moduleVar.paths)}'`;\n })\n .join('\\n')}\n`;\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAOO,SAASA,qBAAT,CAA+BC,OAA/B,EAA6D;EAClE,OAAQ,GAAEA,OAAO,CACdC,GADO,CACFC,SAAD,IAAe;IAClB,OAAQ,gBAAeA,SAAS,CAACC,MAAO,OAAMD,SAAS,CAACE,KAAV,CAC3CH,GAD2C,CACtCI,IAAD,IAAW,YAAW,IAAAC,sCAAA,EAAwBD,IAAxB,CAA8B,IADb,EAE3CE,IAF2C,CAEtC,IAFsC,CAEhC,GAFd,CADkB,CAKlB;EACD,CAPO,EAQPA,IARO,CAQF,IARE,CAQI;AAChB,CATE;AAUD"}
1
+ {"version":3,"names":["generateComponentLink","modules","links","map","prefix","paths","name","entries","path","idx","toWindowsCompatiblePath","linkName","importStr","join","exportsString","entry"],"sources":["generate-component-link.ts"],"sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\n\nexport type ModuleVar = {\n prefix: string;\n paths: string[];\n};\n\nexport function generateComponentLink(modules: ModuleVar[]): string {\n const links = modules.map(({ prefix, paths }) => ({\n name: prefix,\n entries: paths.map((path, idx) => ({\n path: toWindowsCompatiblePath(path),\n linkName: `${prefix}_${idx}`,\n })),\n }));\n\n // import per preview file\n const importStr: string = links\n .map(({ entries }) => entries.map(({ path, linkName }) => `import * as ${linkName} from '${path}'`).join(';\\n'))\n .join('\\n');\n\n // export files group per preview\n const exportsString: string = links\n .map(({ name, entries }) => `export const ${name} = [${entries.map((entry) => entry.linkName).join(', ')}]`)\n .join(';\\n');\n\n return `${importStr}\n\n${exportsString}\n`;\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAOO,SAASA,qBAAT,CAA+BC,OAA/B,EAA6D;EAClE,MAAMC,KAAK,GAAGD,OAAO,CAACE,GAAR,CAAY,CAAC;IAAEC,MAAF;IAAUC;EAAV,CAAD,MAAwB;IAChDC,IAAI,EAAEF,MAD0C;IAEhDG,OAAO,EAAEF,KAAK,CAACF,GAAN,CAAU,CAACK,IAAD,EAAOC,GAAP,MAAgB;MACjCD,IAAI,EAAE,IAAAE,sCAAA,EAAwBF,IAAxB,CAD2B;MAEjCG,QAAQ,EAAG,GAAEP,MAAO,IAAGK,GAAI;IAFM,CAAhB,CAAV;EAFuC,CAAxB,CAAZ,CAAd,CADkE,CASlE;;EACA,MAAMG,SAAiB,GAAGV,KAAK,CAC5BC,GADuB,CACnB,CAAC;IAAEI;EAAF,CAAD,KAAiBA,OAAO,CAACJ,GAAR,CAAY,CAAC;IAAEK,IAAF;IAAQG;EAAR,CAAD,KAAyB,eAAcA,QAAS,UAASH,IAAK,GAA1E,EAA8EK,IAA9E,CAAmF,KAAnF,CADE,EAEvBA,IAFuB,CAElB,IAFkB,CAA1B,CAVkE,CAclE;;EACA,MAAMC,aAAqB,GAAGZ,KAAK,CAChCC,GAD2B,CACvB,CAAC;IAAEG,IAAF;IAAQC;EAAR,CAAD,KAAwB,gBAAeD,IAAK,OAAMC,OAAO,CAACJ,GAAR,CAAaY,KAAD,IAAWA,KAAK,CAACJ,QAA7B,EAAuCE,IAAvC,CAA4C,IAA5C,CAAkD,GAD7E,EAE3BA,IAF2B,CAEtB,KAFsB,CAA9B;EAIA,OAAQ,GAAED,SAAU;AACtB;AACA,EAAEE,aAAc;AAChB,CAHE;AAID"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.769",
3
+ "version": "0.0.772",
4
4
  "homepage": "https://bit.dev/teambit/preview/preview",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.preview",
8
8
  "name": "preview",
9
- "version": "0.0.769"
9
+ "version": "0.0.772"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -17,32 +17,33 @@
17
17
  "object-hash": "2.1.1",
18
18
  "cross-fetch": "3.0.6",
19
19
  "memoizee": "0.4.15",
20
+ "lodash.compact": "3.0.1",
20
21
  "graphql-request": "3.4.0",
21
22
  "@babel/runtime": "7.12.18",
22
23
  "core-js": "^3.0.0",
23
24
  "@teambit/harmony": "0.3.3",
24
- "@teambit/express": "0.0.606",
25
- "@teambit/logger": "0.0.601",
25
+ "@teambit/express": "0.0.609",
26
+ "@teambit/logger": "0.0.604",
26
27
  "@teambit/ui-foundation.ui.pages.static-error": "0.0.73",
27
- "@teambit/builder": "0.0.769",
28
- "@teambit/bundler": "0.0.769",
29
- "@teambit/component": "0.0.769",
30
- "@teambit/aspect-loader": "0.0.769",
31
- "@teambit/dependency-resolver": "0.0.769",
32
- "@teambit/envs": "0.0.769",
33
- "@teambit/isolator": "0.0.769",
28
+ "@teambit/builder": "0.0.772",
29
+ "@teambit/bundler": "0.0.772",
30
+ "@teambit/component": "0.0.772",
31
+ "@teambit/aspect-loader": "0.0.772",
32
+ "@teambit/dependency-resolver": "0.0.772",
33
+ "@teambit/envs": "0.0.772",
34
34
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.483",
35
35
  "@teambit/component-id": "0.0.402",
36
36
  "@teambit/bit-error": "0.0.394",
37
- "@teambit/cli": "0.0.508",
38
- "@teambit/graphql": "0.0.769",
39
- "@teambit/pkg": "0.0.769",
40
- "@teambit/pubsub": "0.0.769",
41
- "@teambit/ui": "0.0.769",
42
- "@teambit/workspace": "0.0.769",
43
- "@teambit/compiler": "0.0.769",
37
+ "@teambit/cli": "0.0.511",
38
+ "@teambit/graphql": "0.0.772",
39
+ "@teambit/pkg": "0.0.772",
40
+ "@teambit/pubsub": "0.0.772",
41
+ "@teambit/ui": "0.0.772",
42
+ "@teambit/workspace": "0.0.772",
43
+ "@teambit/compiler": "0.0.772",
44
44
  "@teambit/preview.cli.preview-server-status": "0.0.491",
45
- "@teambit/preview.cli.webpack-events-listener": "0.0.161"
45
+ "@teambit/preview.cli.webpack-events-listener": "0.0.161",
46
+ "@teambit/isolator": "0.0.772"
46
47
  },
47
48
  "devDependencies": {
48
49
  "@types/mime": "2.0.3",
@@ -51,6 +52,7 @@
51
52
  "@types/react": "^17.0.8",
52
53
  "@types/object-hash": "1.3.4",
53
54
  "@types/memoizee": "0.4.5",
55
+ "@types/lodash.compact": "3.0.6",
54
56
  "@types/mocha": "9.1.0",
55
57
  "@types/testing-library__jest-dom": "5.9.5",
56
58
  "@types/jest": "^26.0.0",
@@ -59,7 +61,7 @@
59
61
  "@teambit/preview.aspect-docs.preview": "0.0.138"
60
62
  },
61
63
  "peerDependencies": {
62
- "@teambit/legacy": "1.0.288",
64
+ "@teambit/legacy": "1.0.292",
63
65
  "react-dom": "^16.8.0 || ^17.0.0",
64
66
  "react": "^16.8.0 || ^17.0.0"
65
67
  },
@@ -87,7 +89,7 @@
87
89
  "react": "-"
88
90
  },
89
91
  "peerDependencies": {
90
- "@teambit/legacy": "1.0.288",
92
+ "@teambit/legacy": "1.0.292",
91
93
  "react-dom": "^16.8.0 || ^17.0.0",
92
94
  "react": "^16.8.0 || ^17.0.0"
93
95
  }
@@ -0,0 +1,5 @@
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.772/dist/preview.composition.js'
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.772/dist/preview.docs.mdx'
3
+
4
+ export const compositions = [compositions_0];
5
+ export const overview = [overview_0]
@@ -0,0 +1,28 @@
1
+ import type { PreviewModule, ModuleFile } from './types/preview-module';
2
+
3
+ type ModuleId = string;
4
+
5
+ export class PreviewModules extends Map<ModuleId, PreviewModule> {
6
+ onSet = new Set<() => void>();
7
+
8
+ override set(id: ModuleId, preview: PreviewModule) {
9
+ super.set(id, preview);
10
+ this.onSet.forEach((callback) => callback());
11
+ return this;
12
+ }
13
+
14
+ loadComponentPreviews(compId: string, previews: Record<string, ModuleFile[]>) {
15
+ Object.entries(previews).forEach(([previewName, moduleFile]) => {
16
+ const preview = this.get(previewName);
17
+ if (!preview) return; // TODO - ok for now
18
+
19
+ preview.componentMap[compId] = moduleFile;
20
+ });
21
+ }
22
+ }
23
+
24
+ export const PREVIEW_MODULES = new PreviewModules();
25
+
26
+ export function linkModules(previewName: string, previewModule: PreviewModule) {
27
+ PREVIEW_MODULES.set(previewName, previewModule);
28
+ }
@@ -8,13 +8,15 @@ import { PreviewNotFound } from './exceptions';
8
8
  import { PreviewType } from './preview-type';
9
9
  import { PreviewAspect, PreviewRuntime } from './preview.aspect';
10
10
  import { ClickInsideAnIframeEvent } from './events';
11
- import { PreviewModule } from './types/preview-module';
11
+ import { ModuleFile, PreviewModule } from './types/preview-module';
12
12
  import { RenderingContext } from './rendering-context';
13
13
  import { fetchComponentAspects } from './gql/fetch-component-aspects';
14
+ import { PREVIEW_MODULES } from './preview-modules';
14
15
 
15
- export type PreviewSlot = SlotRegistry<PreviewType>;
16
+ // forward linkModules() for generate-link.ts
17
+ export { linkModules } from './preview-modules';
16
18
 
17
- const PREVIEW_MODULES: Record<string, PreviewModule> = {};
19
+ export type PreviewSlot = SlotRegistry<PreviewType>;
18
20
 
19
21
  export type RenderingContextOptions = { aspectsFilter?: string[] };
20
22
  export type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };
@@ -47,6 +49,32 @@ export class PreviewPreview {
47
49
 
48
50
  private isDev = false;
49
51
 
52
+ private isReady() {
53
+ const { previewName } = this.getLocation();
54
+ const name = previewName || this.getDefault();
55
+
56
+ if (!PREVIEW_MODULES.has(name)) return false;
57
+ const preview = this.getPreview(name);
58
+ if (!preview) return false;
59
+ const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;
60
+ if (!includedReady) return false;
61
+
62
+ return true;
63
+ }
64
+
65
+ private _setupPromise?: Promise<void>;
66
+ setup = () => {
67
+ if (this.isReady()) return Promise.resolve();
68
+
69
+ this._setupPromise ??= new Promise((resolve) => {
70
+ PREVIEW_MODULES.onSet.add(() => {
71
+ if (this.isReady()) resolve();
72
+ });
73
+ });
74
+
75
+ return this._setupPromise;
76
+ };
77
+
50
78
  /**
51
79
  * render the preview.
52
80
  */
@@ -61,14 +89,12 @@ export class PreviewPreview {
61
89
  }
62
90
 
63
91
  const includesAll = await Promise.all(
64
- (preview.include || []).map(async (prevName) => {
65
- const includedPreview = this.getPreview(prevName);
92
+ (preview.include || []).map(async (inclPreviewName) => {
93
+ const includedPreview = this.getPreview(inclPreviewName);
66
94
  if (!includedPreview) return undefined;
67
95
 
68
- return includedPreview.selectPreviewModel?.(
69
- componentId.fullName,
70
- await this.getPreviewModule(prevName, componentId, name)
71
- );
96
+ const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);
97
+ return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);
72
98
  })
73
99
  );
74
100
 
@@ -84,18 +110,17 @@ export class PreviewPreview {
84
110
  );
85
111
  };
86
112
 
87
- async getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule> {
88
- const relevantModel = PREVIEW_MODULES[name];
89
- if (relevantModel.componentMap[id.fullName]) return relevantModel;
90
-
91
- let component;
92
- // Handle case when there is overview but no composition on the workspace dev server
93
- if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {
94
- // if (!window[name]) throw new PreviewNotFound(name);
95
- // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;
96
- // const component = window[id.toStringWithoutVersion()];
97
- component = await this.fetchComponentPreview(id, name);
98
- }
113
+ async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {
114
+ const compShortId = id.fullName;
115
+
116
+ const relevantModel = PREVIEW_MODULES.get(previewName);
117
+ if (!relevantModel) throw new Error(`[preview.preview] missing preview "${previewName}"`);
118
+ if (relevantModel.componentMap[compShortId]) return relevantModel;
119
+
120
+ const componentPreviews = await this.fetchComponentPreview(id, previewName);
121
+ PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);
122
+
123
+ const component = componentPreviews[previewName];
99
124
 
100
125
  return {
101
126
  mainModule: relevantModel.mainModule,
@@ -105,13 +130,12 @@ export class PreviewPreview {
105
130
  };
106
131
  }
107
132
 
108
- async fetchComponentPreview(id: ComponentID, name: string) {
109
- let previewFile;
133
+ async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {
134
+ let previewFile: string | undefined;
110
135
  const allFiles = await this.fetchComponentPreviewFiles(id, name);
111
136
  // It's a component bundled with the env
112
- if (allFiles === null) {
113
- return Promise.resolve(undefined);
114
- }
137
+ if (allFiles === null) return {};
138
+
115
139
  allFiles.forEach((file) => {
116
140
  // We want to run the preview file always last
117
141
  if (file.endsWith('-preview.js')) {
@@ -120,10 +144,9 @@ export class PreviewPreview {
120
144
  this.addComponentFileElement(id, file);
121
145
  }
122
146
  });
123
- return new Promise((resolve, reject) => {
124
- const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);
125
- document.head.appendChild(previewScriptElement);
126
- });
147
+
148
+ if (!previewFile) return {};
149
+ return this.loadPreviewScript(id, name, previewFile);
127
150
  }
128
151
 
129
152
  private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {
@@ -177,23 +200,24 @@ export class PreviewPreview {
177
200
  return link;
178
201
  }
179
202
 
180
- private getPreviewScriptElement(id: ComponentID, name: string, previewBundleFileName: string, resolve, reject) {
181
- const script = document.createElement('script');
182
- script.setAttribute('defer', 'defer');
183
- const stringId = id.toString();
184
- // const previewRoute = `~aspect/preview`;
185
- const previewRoute = `~aspect/component-preview`;
186
- const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
187
- script.src = src; // generate path to remote scope. [scope url]/
188
- script.onload = () => {
189
- const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];
190
- if (!componentPreview) return reject(new PreviewNotFound(name));
191
- const targetPreview = componentPreview[name];
192
- if (!targetPreview) return resolve(undefined);
193
-
194
- return resolve(targetPreview);
195
- };
196
- return script;
203
+ private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {
204
+ await new Promise<void>((resolve, reject) => {
205
+ const script = document.createElement('script');
206
+ const previewRoute = `~aspect/component-preview`;
207
+ const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;
208
+ script.src = src;
209
+ script.setAttribute('defer', 'defer');
210
+ script.onload = () => resolve();
211
+ script.onerror = (message, _, _1, _2, error) =>
212
+ reject(error || new Error(`[preview.preview] failed to load preview script: ${message}`));
213
+ document.head.appendChild(script);
214
+ });
215
+
216
+ const globalId = `${id.toStringWithoutVersion()}-preview`;
217
+ const componentPreview = window[globalId];
218
+ if (!componentPreview) throw new PreviewNotFound(previewName);
219
+
220
+ return componentPreview as Record<string, ModuleFile[]>;
197
221
  }
198
222
 
199
223
  private getComponentAspects = memoize(fetchComponentAspects, {
@@ -276,8 +300,4 @@ export class PreviewPreview {
276
300
  }
277
301
  }
278
302
 
279
- export function linkModules(previewName: string, previewModule: PreviewModule) {
280
- PREVIEW_MODULES[previewName] = previewModule;
281
- }
282
-
283
303
  PreviewAspect.addRuntime(PreviewPreview);
@@ -365,10 +365,10 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
365
365
  const moduleMapsPromise = defs.map(async (previewDef) => {
366
366
  const moduleMap = await previewDef.getModuleMap([component]);
367
367
  const maybeFiles = moduleMap.get(component);
368
- if (!maybeFiles || !capsule) return [];
368
+ if (!maybeFiles || !capsule) return { prefix: previewDef.prefix, paths: [] };
369
+
369
370
  const [, files] = maybeFiles;
370
371
  const compiledPaths = this.getPaths(context, component, files);
371
- // const files = flatten(paths.toArray().map(([, file]) => file));
372
372
 
373
373
  return {
374
374
  prefix: previewDef.prefix,
@@ -376,7 +376,7 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
376
376
  };
377
377
  });
378
378
 
379
- const moduleMaps = flatten(await Promise.all(moduleMapsPromise));
379
+ const moduleMaps = await Promise.all(moduleMapsPromise);
380
380
 
381
381
  const contents = generateComponentLink(moduleMaps);
382
382
  return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');
@@ -12,7 +12,7 @@ import { PkgMain } from '@teambit/pkg';
12
12
  import type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
13
13
  import { PreviewDefinition } from '../preview-definition';
14
14
  import { PreviewMain } from '../preview.main.runtime';
15
- import { html } from '../webpack';
15
+ import { html } from '../bundler/html-template';
16
16
 
17
17
  export const ENV_STRATEGY_ARTIFACT_NAME = 'preview';
18
18
 
@@ -6,14 +6,26 @@ export type ModuleVar = {
6
6
  };
7
7
 
8
8
  export function generateComponentLink(modules: ModuleVar[]): string {
9
- return `${modules
10
- .map((moduleVar) => {
11
- return `export const ${moduleVar.prefix} = [${moduleVar.paths
12
- .map((path) => `require('${toWindowsCompatiblePath(path)}')`)
13
- .join(', ')}]`;
9
+ const links = modules.map(({ prefix, paths }) => ({
10
+ name: prefix,
11
+ entries: paths.map((path, idx) => ({
12
+ path: toWindowsCompatiblePath(path),
13
+ linkName: `${prefix}_${idx}`,
14
+ })),
15
+ }));
14
16
 
15
- // return `export { * as ${moduleVar.prefix} } from '${toWindowsCompatiblePath(moduleVar.paths)}'`;
16
- })
17
- .join('\n')}
17
+ // import per preview file
18
+ const importStr: string = links
19
+ .map(({ entries }) => entries.map(({ path, linkName }) => `import * as ${linkName} from '${path}'`).join(';\n'))
20
+ .join('\n');
21
+
22
+ // export files group per preview
23
+ const exportsString: string = links
24
+ .map(({ name, entries }) => `export const ${name} = [${entries.map((entry) => entry.linkName).join(', ')}]`)
25
+ .join(';\n');
26
+
27
+ return `${importStr}
28
+
29
+ ${exportsString}
18
30
  `;
19
31
  }
@@ -1 +0,0 @@
1
- {"version":3,"names":["html","title"],"sources":["html.ts"],"sourcesContent":["/** html template for Previews (docs, compositions, etc) */\nexport function html(title: string) {\n return `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <script>\n // Allow to use react dev-tools inside the examples\n try { window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__; } catch {}\n </script>\n <!-- minimal css resets -->\n <style> html { height: 100%; } body { margin: 0; height: 100%; } #root { height: 100%; } </style>\n </head>\n <body>\n <div id=\"root\"></div>\n </body>\n </html>\n `;\n}\n"],"mappings":";;;;;;;AAAA;AACO,SAASA,IAAT,CAAcC,KAAd,EAA6B;EAClC,OAAQ;AACV;AACA;AACA;AACA;AACA;AACA,eAAeA,KAAM;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBE;AAmBD"}
@@ -1 +0,0 @@
1
- export { html } from './html';
@@ -1,23 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- Object.defineProperty(exports, "html", {
7
- enumerable: true,
8
- get: function () {
9
- return _html().html;
10
- }
11
- });
12
-
13
- function _html() {
14
- const data = require("./html");
15
-
16
- _html = function () {
17
- return data;
18
- };
19
-
20
- return data;
21
- }
22
-
23
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"names":[],"sources":["index.ts"],"sourcesContent":["export { html } from './html';\n"],"mappings":";;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA"}
@@ -1,2 +0,0 @@
1
- export const compositions = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.769/dist/preview.composition.js')]
2
- export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.769/dist/preview.docs.mdx')]
package/webpack/index.ts DELETED
@@ -1 +0,0 @@
1
- export { html } from './html';