@teambit/preview 0.0.666 → 0.0.669

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.
@@ -1,2 +1,2 @@
1
1
  import type { ComponentMap } from '@teambit/component';
2
- export declare function generateLink(prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string, isSplitComponentBundle?: boolean): string;
2
+ export declare function generateLink(prefix: string, componentMap: ComponentMap<string[]>, mainModule?: string, isSplitComponentBundle?: boolean): string;
@@ -18,17 +18,30 @@ function _toolboxPath() {
18
18
  }
19
19
 
20
20
  // :TODO refactor to building an AST and generate source code based on it.
21
- function generateLink(prefix, componentMap, defaultModule, isSplitComponentBundle = false) {
21
+ function generateLink(prefix, componentMap, mainModule, isSplitComponentBundle = false) {
22
22
  return `
23
23
  import { linkModules } from '${(0, _toolboxPath().toWindowsCompatiblePath)(require.resolve('./preview.preview.runtime'))}';
24
24
  import harmony from '${(0, _toolboxPath().toWindowsCompatiblePath)(require.resolve('@teambit/harmony'))}';
25
- ${defaultModule ? `const defaultModule = require('${(0, _toolboxPath().toWindowsCompatiblePath)(defaultModule)}'` : ''});
26
- linkModules('${prefix}', defaultModule, ${isSplitComponentBundle}, {
27
- ${componentMap.toArray().map(([component, modulePaths]) => {
28
- return `'${component.id.fullName}': [${modulePaths.map(path => `require('${(0, _toolboxPath().toWindowsCompatiblePath)(path)}')`).join(', ')}]`;
25
+ ${mainModule ? `import * as mainModule from '${(0, _toolboxPath().toWindowsCompatiblePath)(mainModule)}';` : 'const mainModule = {};'}
26
+
27
+ ${// generate imports:
28
+ componentMap.toArray().map(([, modulePath], compIdx) => modulePath.map((path, pathIdx) => `import * as ${moduleVarName(compIdx, pathIdx)} from '${(0, _toolboxPath().toWindowsCompatiblePath)(path)}'`).join('\n')).join('\n')}
29
+
30
+ linkModules('${prefix}', {
31
+ mainModule,
32
+ isSplitComponentBundle: ${isSplitComponentBundle},
33
+ componentMap: {
34
+ ${// use imports:
35
+ componentMap.toArray().map(([component, modulePaths], compIdx) => {
36
+ return ` '${component.id.fullName}': [${modulePaths.map((_, pathIdx) => moduleVarName(compIdx, pathIdx)).join(', ')}]`;
29
37
  }).join(',\n')}
38
+ }
30
39
  });
31
40
  `;
32
41
  }
33
42
 
43
+ function moduleVarName(componentIdx, fileIdx) {
44
+ return `file_${componentIdx}_${fileIdx}`;
45
+ }
46
+
34
47
  //# sourceMappingURL=generate-link.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["generate-link.ts"],"names":["generateLink","prefix","componentMap","defaultModule","isSplitComponentBundle","require","resolve","toArray","map","component","modulePaths","id","fullName","path","join"],"mappings":";;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AACO,SAASA,YAAT,CACLC,MADK,EAELC,YAFK,EAGLC,aAHK,EAILC,sBAAsB,GAAG,KAJpB,EAKG;AACR,SAAQ;AACV,+BAA+B,4CAAwBC,OAAO,CAACC,OAAR,CAAgB,2BAAhB,CAAxB,CAAsE;AACrG,uBAAuB,4CAAwBD,OAAO,CAACC,OAAR,CAAgB,kBAAhB,CAAxB,CAA6D;AACpF,EAAEH,aAAa,GAAI,kCAAiC,4CAAwBA,aAAxB,CAAuC,GAA5E,GAAiF,EAAG;AACnG,eAAeF,MAAO,qBAAoBG,sBAAuB;AACjE,IAAIF,YAAY,CACXK,OADD,GAECC,GAFD,CAEK,CAAC,CAACC,SAAD,EAAYC,WAAZ,CAAD,KAAmC;AACtC,WAAQ,IAAGD,SAAS,CAACE,EAAV,CAAaC,QAAS,OAAMF,WAAW,CAC/CF,GADoC,CAC/BK,IAAD,IAAW,YAAW,4CAAwBA,IAAxB,CAA8B,IADpB,EAEpCC,IAFoC,CAE/B,IAF+B,CAEzB,GAFd;AAGD,GAND,EAOCA,IAPD,CAOM,KAPN,CAOa;AACjB;AACA,CAdE;AAeD","sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\nimport type { ComponentMap } from '@teambit/component';\n\n// :TODO refactor to building an AST and generate source code based on it.\nexport function generateLink(\n prefix: string,\n componentMap: ComponentMap<string[]>,\n defaultModule?: string,\n isSplitComponentBundle = false\n): string {\n return `\nimport { linkModules } from '${toWindowsCompatiblePath(require.resolve('./preview.preview.runtime'))}';\nimport harmony from '${toWindowsCompatiblePath(require.resolve('@teambit/harmony'))}';\n${defaultModule ? `const defaultModule = require('${toWindowsCompatiblePath(defaultModule)}'` : ''});\nlinkModules('${prefix}', defaultModule, ${isSplitComponentBundle}, {\n ${componentMap\n .toArray()\n .map(([component, modulePaths]: any) => {\n return `'${component.id.fullName}': [${modulePaths\n .map((path) => `require('${toWindowsCompatiblePath(path)}')`)\n .join(', ')}]`;\n })\n .join(',\\n')}\n});\n`;\n}\n"]}
1
+ {"version":3,"sources":["generate-link.ts"],"names":["generateLink","prefix","componentMap","mainModule","isSplitComponentBundle","require","resolve","toArray","map","modulePath","compIdx","path","pathIdx","moduleVarName","join","component","modulePaths","id","fullName","_","componentIdx","fileIdx"],"mappings":";;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AACO,SAASA,YAAT,CACLC,MADK,EAELC,YAFK,EAGLC,UAHK,EAILC,sBAAsB,GAAG,KAJpB,EAKG;AACR,SAAQ;AACV,+BAA+B,4CAAwBC,OAAO,CAACC,OAAR,CAAgB,2BAAhB,CAAxB,CAAsE;AACrG,uBAAuB,4CAAwBD,OAAO,CAACC,OAAR,CAAgB,kBAAhB,CAAxB,CAA6D;AACpF,EAAEH,UAAU,GAAI,gCAA+B,4CAAwBA,UAAxB,CAAoC,IAAvE,GAA6E,wBAAyB;AAClH;AACA,EACE;AACAD,EAAAA,YAAY,CACTK,OADH,GAEGC,GAFH,CAEO,CAAC,GAAGC,UAAH,CAAD,EAAiBC,OAAjB,KACHD,UAAU,CACPD,GADH,CAEI,CAACG,IAAD,EAAOC,OAAP,KAAoB,eAAcC,aAAa,CAACH,OAAD,EAAUE,OAAV,CAAmB,UAAS,4CAAwBD,IAAxB,CAA8B,GAF7G,EAIGG,IAJH,CAIQ,IAJR,CAHJ,EASGA,IATH,CASQ,IATR,CAUD;AACD;AACA,eAAeb,MAAO;AACtB;AACA,4BAA4BG,sBAAuB;AACnD;AACA,EACE;AACAF,EAAAA,YAAY,CACTK,OADH,GAEGC,GAFH,CAEO,CAAC,CAACO,SAAD,EAAYC,WAAZ,CAAD,EAA2BN,OAA3B,KAAuC;AAC1C,WAAQ,QAAOK,SAAS,CAACE,EAAV,CAAaC,QAAS,OAAMF,WAAW,CACnDR,GADwC,CACpC,CAACW,CAAD,EAAIP,OAAJ,KAAgBC,aAAa,CAACH,OAAD,EAAUE,OAAV,CADO,EAExCE,IAFwC,CAEnC,IAFmC,CAE7B,GAFd;AAGD,GANH,EAOGA,IAPH,CAOQ,KAPR,CAQD;AACD;AACA;AACA,CApCE;AAqCD;;AAED,SAASD,aAAT,CAAuBO,YAAvB,EAA6CC,OAA7C,EAA8D;AAC5D,SAAQ,QAAOD,YAAa,IAAGC,OAAQ,EAAvC;AACD","sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\nimport type { ComponentMap } from '@teambit/component';\n\n// :TODO refactor to building an AST and generate source code based on it.\nexport function generateLink(\n prefix: string,\n componentMap: ComponentMap<string[]>,\n mainModule?: string,\n isSplitComponentBundle = false\n): string {\n return `\nimport { linkModules } from '${toWindowsCompatiblePath(require.resolve('./preview.preview.runtime'))}';\nimport harmony from '${toWindowsCompatiblePath(require.resolve('@teambit/harmony'))}';\n${mainModule ? `import * as mainModule from '${toWindowsCompatiblePath(mainModule)}';` : 'const mainModule = {};'}\n\n${\n // generate imports:\n componentMap\n .toArray()\n .map(([, modulePath], compIdx) =>\n modulePath\n .map(\n (path, pathIdx) => `import * as ${moduleVarName(compIdx, pathIdx)} from '${toWindowsCompatiblePath(path)}'`\n )\n .join('\\n')\n )\n .join('\\n')\n}\n\nlinkModules('${prefix}', {\n mainModule,\n isSplitComponentBundle: ${isSplitComponentBundle},\n componentMap: {\n${\n // use imports:\n componentMap\n .toArray()\n .map(([component, modulePaths], compIdx) => {\n return ` '${component.id.fullName}': [${modulePaths\n .map((_, pathIdx) => moduleVarName(compIdx, pathIdx))\n .join(', ')}]`;\n })\n .join(',\\n')\n}\n }\n});\n`;\n}\n\nfunction moduleVarName(componentIdx: number, fileIdx: number) {\n return `file_${componentIdx}_${fileIdx}`;\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare function fetchComponentAspects(componentId: string): Promise<string[] | undefined>;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+
3
+ require("core-js/modules/es.promise.js");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.fetchComponentAspects = fetchComponentAspects;
9
+
10
+ function _graphqlRequest() {
11
+ const data = require("graphql-request");
12
+
13
+ _graphqlRequest = function () {
14
+ return data;
15
+ };
16
+
17
+ return data;
18
+ }
19
+
20
+ const GQL_SERVER = '/graphql';
21
+ const GET_COMPONENT_ASPECTS = (0, _graphqlRequest().gql)`
22
+ query getComponentAspects($id: String!) {
23
+ getHost {
24
+ id
25
+ get(id: $id) {
26
+ aspects {
27
+ id
28
+ }
29
+ }
30
+ }
31
+ }
32
+ `;
33
+
34
+ async function fetchComponentAspects(componentId) {
35
+ try {
36
+ const response = await (0, _graphqlRequest().request)(GQL_SERVER, GET_COMPONENT_ASPECTS, {
37
+ id: componentId.toString()
38
+ });
39
+ return response.getHost.get.aspects.map(x => x.id);
40
+ } catch (err) {
41
+ // eslint-disable-next-line no-console
42
+ console.error(`[gql] error on "getComponentAspects" - "${err.toString()}"`);
43
+ return undefined;
44
+ }
45
+ }
46
+
47
+ //# sourceMappingURL=fetch-component-aspects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["fetch-component-aspects.tsx"],"names":["GQL_SERVER","GET_COMPONENT_ASPECTS","fetchComponentAspects","componentId","response","id","toString","getHost","get","aspects","map","x","err","console","error","undefined"],"mappings":";;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA,MAAMA,UAAU,GAAG,UAAnB;AACA,MAAMC,qBAAqB,GAAG,0BAAI;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAXA;;AAqBO,eAAeC,qBAAf,CAAqCC,WAArC,EAA0D;AAC/D,MAAI;AACF,UAAMC,QAAQ,GAAG,MAAM,+BAAqBJ,UAArB,EAAiCC,qBAAjC,EAAwD;AAAEI,MAAAA,EAAE,EAAEF,WAAW,CAACG,QAAZ;AAAN,KAAxD,CAAvB;AACA,WAAOF,QAAQ,CAACG,OAAT,CAAiBC,GAAjB,CAAqBC,OAArB,CAA6BC,GAA7B,CAAkCC,CAAD,IAAOA,CAAC,CAACN,EAA1C,CAAP;AACD,GAHD,CAGE,OAAOO,GAAP,EAAiB;AACjB;AACAC,IAAAA,OAAO,CAACC,KAAR,CAAe,2CAA0CF,GAAG,CAACN,QAAJ,EAAe,GAAxE;AACA,WAAOS,SAAP;AACD;AACF","sourcesContent":["import { request, gql } from 'graphql-request';\n\nconst GQL_SERVER = '/graphql';\nconst GET_COMPONENT_ASPECTS = gql`\n query getComponentAspects($id: String!) {\n getHost {\n id\n get(id: $id) {\n aspects {\n id\n }\n }\n }\n }\n`;\ntype QueryResult = {\n getHost: {\n id: string;\n get: {\n aspects: { id: string }[];\n };\n };\n};\n\nexport async function fetchComponentAspects(componentId: string) {\n try {\n const response = await request<QueryResult>(GQL_SERVER, GET_COMPONENT_ASPECTS, { id: componentId.toString() });\n return response.getHost.get.aspects.map((x) => x.id);\n } catch (err: any) {\n // eslint-disable-next-line no-console\n console.error(`[gql] error on \"getComponentAspects\" - \"${err.toString()}\"`);\n return undefined;\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { PreviewAspect as default, PreviewAspect, PreviewRuntime } from './preview.aspect';
2
2
  export * from './events';
3
3
  export type { PreviewMain, EnvPreviewConfig, ComponentPreviewSize } from './preview.main.runtime';
4
- export type { PreviewPreview } from './preview.preview.runtime';
4
+ export type { PreviewPreview, RenderingContextOptions, RenderingContextProvider } from './preview.preview.runtime';
5
5
  export { PreviewDefinition } from './preview-definition';
6
6
  export type { PreviewModule, ModuleFile } from './types/preview-module';
7
7
  export type { RenderingContext } from './rendering-context';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA","sourcesContent":["export { PreviewAspect as default, PreviewAspect, PreviewRuntime } from './preview.aspect';\n\nexport * from './events';\nexport type { PreviewMain, EnvPreviewConfig, ComponentPreviewSize } from './preview.main.runtime';\nexport type { PreviewPreview } from './preview.preview.runtime';\nexport { PreviewDefinition } from './preview-definition';\nexport type { PreviewModule, ModuleFile } from './types/preview-module';\nexport type { RenderingContext } from './rendering-context';\n"]}
1
+ {"version":3,"sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA","sourcesContent":["export { PreviewAspect as default, PreviewAspect, PreviewRuntime } from './preview.aspect';\n\nexport * from './events';\nexport type { PreviewMain, EnvPreviewConfig, ComponentPreviewSize } from './preview.main.runtime';\nexport type { PreviewPreview, RenderingContextOptions, RenderingContextProvider } from './preview.preview.runtime';\nexport { PreviewDefinition } from './preview-definition';\nexport type { PreviewModule, ModuleFile } from './types/preview-module';\nexport type { RenderingContext } from './rendering-context';\n"]}
@@ -1,3 +1,4 @@
1
+ import { ComponentID } from '@teambit/component-id';
1
2
  import { RenderingContext } from './rendering-context';
2
3
  import { PreviewModule } from './types/preview-module';
3
4
  export interface PreviewType {
@@ -8,7 +9,7 @@ export interface PreviewType {
8
9
  /**
9
10
  * preview render method.
10
11
  */
11
- render(componentId: string, linkedModules: PreviewModule<any>, includedPreviews: string[], renderingContext: RenderingContext): void;
12
+ render(componentId: ComponentID, linkedModules: PreviewModule<any>, includedPreviews: string[], renderingContext: RenderingContext): void;
12
13
  /**
13
14
  * determine if this will be the default preview to render.
14
15
  */
@@ -586,7 +586,7 @@ class PreviewMain {
586
586
 
587
587
  writeLinkContents(contents, targetDir, prefix) {
588
588
  const hash = (0, _objectHash().default)(contents);
589
- const targetPath = (0, _path().join)(targetDir, `__${prefix}-${this.timestamp}.js`); // write only if link has changed (prevents triggering fs watches)
589
+ const targetPath = (0, _path().join)(targetDir, `${prefix}-${this.timestamp}.js`); // write only if link has changed (prevents triggering fs watches)
590
590
 
591
591
  if (this.writeHash.get(targetPath) !== hash) {
592
592
  (0, _fsExtra().writeFileSync)(targetPath, contents);
@@ -1 +1 @@
1
- {"version":3,"sources":["preview.main.runtime.tsx"],"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByExtensionAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByExtensionAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","artifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","coreEnvDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","writeLinkContents","targetDir","hash","targetPath","timestamp","writeHash","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","environment","envRuntime","getEnvPreviewConfig","splitComponentBundle","compilerInstance","getCompiler","withPaths","modulePath","getPreviewComponentRootPath","getModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","recursive","link","all","aspectsIdsToNotFilterOut","getUi","Error","name","uiRoot","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","aspects","allComponentContextAspects","reduce","acc","curr","concat","state","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","filtered","filter","aspect","getId","isCoreAspect","includes","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","Slot","withType","MainRuntime","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;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;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;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;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;A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BAAV,CAAkC3L,CAAD,IAC/B4K,OAAO,CAACzJ,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAACkL,GAAlB,CAAsB5L,CAAtB,CAAxD,CADF;AAGAN,MAAAA,SAAS,CAACmM,yBAAV,CAAqC7L,CAAD,IAClC4K,OAAO,CAACzJ,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAACoL,MAAlB,CAAyB9L,CAAzB,CAAxD,CADF;AAGAN,MAAAA,SAAS,CAACqM,yBAAV,CAAqCnL,GAAD,IAASgK,OAAO,CAACoB,sBAAR,CAA+BpL,GAA/B,CAA7C;AACD;;AAED8J,IAAAA,OAAO,CAACR,QAAR,CAAiB,+BAAcU,OAAd,CAAjB;AAEA,WAAOA,OAAP;AACD;;AA7dsB;;;gCAAZ9L,W,WAoXI,CAACmN,gBAAKC,QAAL,EAAD,EAAqCD,gBAAKC,QAAL,EAArC,C;gCApXJpN,W,aAsXMqN,kB;gCAtXNrN,W,kBAuXW,CACpBsN,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAvXXjO,W,mBAsYY;AACrByM,EAAAA,QAAQ,EAAE;AADW,C;;AA0FzB3M,yBAAcoO,UAAd,CAAyBlO,WAAzB","sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport { Component, ComponentAspect, ComponentMain, ComponentMap, ComponentID } from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `__${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const environment = context.envRuntime.env;\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const compilerInstance = environment.getCompiler?.();\n const withPaths = map.map<string[]>((files, component) => {\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n const [name, uiRoot] = ui;\n const resolvedAspects = await uiRoot.resolveAspects(PreviewRuntime.name);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [new EnvBundlingStrategy(this), new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver)];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([new EnvPreviewTemplateTask(preview, envs), new PreviewTask(bundler, preview)]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"]}
1
+ {"version":3,"sources":["preview.main.runtime.tsx"],"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByExtensionAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByExtensionAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","artifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","coreEnvDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","writeLinkContents","targetDir","hash","targetPath","timestamp","writeHash","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","environment","envRuntime","getEnvPreviewConfig","splitComponentBundle","compilerInstance","getCompiler","withPaths","modulePath","getPreviewComponentRootPath","getModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","recursive","link","all","aspectsIdsToNotFilterOut","getUi","Error","name","uiRoot","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","aspects","allComponentContextAspects","reduce","acc","curr","concat","state","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","filtered","filter","aspect","getId","isCoreAspect","includes","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","Slot","withType","MainRuntime","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;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;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;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;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA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C,CAAD,EAA4C,KAAIuM,uBAAJ,EAAgBrB,OAAhB,EAAyBO,OAAzB,CAA5C,CAA3B;;AAEF,QAAIlL,SAAJ,EAAe;AACbA,MAAAA,SAAS,CAACiM,sBAAV,CAAkC3L,CAAD,IAC/B4K,OAAO,CAACzJ,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAACkL,GAAlB,CAAsB5L,CAAtB,CAAxD,CADF;AAGAN,MAAAA,SAAS,CAACmM,yBAAV,CAAqC7L,CAAD,IAClC4K,OAAO,CAACzJ,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAACoL,MAAlB,CAAyB9L,CAAzB,CAAxD,CADF;AAGAN,MAAAA,SAAS,CAACqM,yBAAV,CAAqCnL,GAAD,IAASgK,OAAO,CAACoB,sBAAR,CAA+BpL,GAA/B,CAA7C;AACD;;AAED8J,IAAAA,OAAO,CAACR,QAAR,CAAiB,+BAAcU,OAAd,CAAjB;AAEA,WAAOA,OAAP;AACD;;AA7dsB;;;gCAAZ9L,W,WAoXI,CAACmN,gBAAKC,QAAL,EAAD,EAAqCD,gBAAKC,QAAL,EAArC,C;gCApXJpN,W,aAsXMqN,kB;gCAtXNrN,W,kBAuXW,CACpBsN,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAvXXjO,W,mBAsYY;AACrByM,EAAAA,QAAQ,EAAE;AADW,C;;AA0FzB3M,yBAAcoO,UAAd,CAAyBlO,WAAzB","sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport { Component, ComponentAspect, ComponentMain, ComponentMap, ComponentID } from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByExtensionAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const environment = context.envRuntime.env;\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const compilerInstance = environment.getCompiler?.();\n const withPaths = map.map<string[]>((files, component) => {\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n const [name, uiRoot] = ui;\n const resolvedAspects = await uiRoot.resolveAspects(PreviewRuntime.name);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [new EnvBundlingStrategy(this), new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver)];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([new EnvPreviewTemplateTask(preview, envs), new PreviewTask(bundler, preview)]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"]}
@@ -5,7 +5,10 @@ import { PreviewType } from './preview-type';
5
5
  import { PreviewModule } from './types/preview-module';
6
6
  import { RenderingContext } from './rendering-context';
7
7
  export declare type PreviewSlot = SlotRegistry<PreviewType>;
8
- export declare type RenderingContextProvider = () => {
8
+ export declare type RenderingContextOptions = {
9
+ aspectsFilter?: string[];
10
+ };
11
+ export declare type RenderingContextProvider = (options: RenderingContextOptions) => {
9
12
  [key: string]: any;
10
13
  };
11
14
  export declare type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;
@@ -29,10 +32,11 @@ export declare class PreviewPreview {
29
32
  */
30
33
  previewSlot: PreviewSlot, renderingContextSlot: RenderingContextSlot);
31
34
  private registerClickPubSub;
35
+ private isDev;
32
36
  /**
33
37
  * render the preview.
34
38
  */
35
- render: () => Promise<void>;
39
+ render: (rootExt?: string | undefined) => Promise<void>;
36
40
  getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule>;
37
41
  fetchComponentPreview(id: ComponentID, name: string): Promise<unknown>;
38
42
  private addComponentFileElement;
@@ -40,6 +44,7 @@ export declare class PreviewPreview {
40
44
  private addComponentFileScriptElement;
41
45
  private addComponentFileLinkElement;
42
46
  private getPreviewScriptElement;
47
+ private getComponentAspects;
43
48
  /**
44
49
  * register a new preview.
45
50
  */
@@ -47,7 +52,7 @@ export declare class PreviewPreview {
47
52
  /**
48
53
  * get the preview rendering context.
49
54
  */
50
- getRenderingContext(): RenderingContext;
55
+ getRenderingContext(aspectsFilter?: string[]): RenderingContext;
51
56
  /**
52
57
  * allows aspects to add rendering contexts.
53
58
  * render context is available through all preview definitions.
@@ -62,6 +67,4 @@ export declare class PreviewPreview {
62
67
  static slots: (((registerFn: () => string) => SlotRegistry<PreviewType>) | ((registerFn: () => string) => SlotRegistry<RenderingContextProvider>))[];
63
68
  static provider([pubsub]: [PubsubPreview], config: any, [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]): Promise<PreviewPreview>;
64
69
  }
65
- export declare function linkModules(previewName: string, defaultModule: any, isSplitComponentBundle: boolean, componentMap: {
66
- [key: string]: any;
67
- }): void;
70
+ export declare function linkModules(previewName: string, previewModule: PreviewModule): void;
@@ -66,6 +66,16 @@ function _crossFetch() {
66
66
  return data;
67
67
  }
68
68
 
69
+ function _memoizee() {
70
+ const data = _interopRequireDefault(require("memoizee"));
71
+
72
+ _memoizee = function () {
73
+ return data;
74
+ };
75
+
76
+ return data;
77
+ }
78
+
69
79
  function _exceptions() {
70
80
  const data = require("./exceptions");
71
81
 
@@ -106,6 +116,16 @@ function _renderingContext() {
106
116
  return data;
107
117
  }
108
118
 
119
+ function _fetchComponentAspects() {
120
+ const data = require("./gql/fetch-component-aspects");
121
+
122
+ _fetchComponentAspects = function () {
123
+ return data;
124
+ };
125
+
126
+ return data;
127
+ }
128
+
109
129
  const PREVIEW_MODULES = {};
110
130
 
111
131
  class PreviewPreview {
@@ -121,12 +141,14 @@ class PreviewPreview {
121
141
  this.pubsub = pubsub;
122
142
  this.previewSlot = previewSlot;
123
143
  this.renderingContextSlot = renderingContextSlot;
124
- (0, _defineProperty2().default)(this, "render", async () => {
144
+ (0, _defineProperty2().default)(this, "isDev", false);
145
+ (0, _defineProperty2().default)(this, "render", async rootExt => {
125
146
  const {
126
147
  previewName,
127
148
  componentId
128
149
  } = this.getLocation();
129
150
  const name = previewName || this.getDefault();
151
+ if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';
130
152
  const preview = this.getPreview(name);
131
153
 
132
154
  if (!preview || !componentId) {
@@ -140,9 +162,15 @@ class PreviewPreview {
140
162
  if (!includedPreview) return undefined;
141
163
  return (_includedPreview$sele = includedPreview.selectPreviewModel) === null || _includedPreview$sele === void 0 ? void 0 : _includedPreview$sele.call(includedPreview, componentId.fullName, await this.getPreviewModule(prevName, componentId, name));
142
164
  }));
143
- const includes = includesAll.filter(module => !!module);
144
- return preview.render(componentId.fullName, await this.getPreviewModule(name, componentId), includes, this.getRenderingContext());
165
+ const includes = includesAll.filter(module => !!module); // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
166
+
167
+ const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
168
+ return preview.render(componentId, await this.getPreviewModule(name, componentId), includes, this.getRenderingContext(componentAspects));
145
169
  });
170
+ (0, _defineProperty2().default)(this, "getComponentAspects", (0, _memoizee().default)(_fetchComponentAspects().fetchComponentAspects, {
171
+ max: 100,
172
+ maxAge: 12 * 60 * 60 * 1000
173
+ }));
146
174
  this.registerClickPubSub();
147
175
  }
148
176
 
@@ -153,24 +181,21 @@ class PreviewPreview {
153
181
  this.pubsub.pub(_preview().PreviewAspect.id, new (_events().ClickInsideAnIframeEvent)(timestamp, clickEvent));
154
182
  });
155
183
  }
156
- /**
157
- * render the preview.
158
- */
159
-
160
184
 
161
185
  async getPreviewModule(name, id, parentPreviewName) {
162
- if (PREVIEW_MODULES[name].componentMap[id.fullName]) return PREVIEW_MODULES[name];
186
+ const relevantModel = PREVIEW_MODULES[name];
187
+ if (relevantModel.componentMap[id.fullName]) return relevantModel;
163
188
  let component; // Handle case when there is overview but no composition on the workspace dev server
164
189
 
165
190
  if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {
166
191
  // if (!window[name]) throw new PreviewNotFound(name);
167
- // const isSplitComponentBundle = PREVIEW_MODULES[name].isSplitComponentBundle ?? false;
192
+ // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;
168
193
  // const component = window[id.toStringWithoutVersion()];
169
194
  component = await this.fetchComponentPreview(id, name);
170
195
  }
171
196
 
172
197
  return {
173
- mainModule: PREVIEW_MODULES[name].mainModule,
198
+ mainModule: relevantModel.mainModule,
174
199
  componentMap: {
175
200
  [id.fullName]: component
176
201
  }
@@ -275,11 +300,10 @@ class PreviewPreview {
275
300
 
276
301
  return script;
277
302
  }
303
+
278
304
  /**
279
305
  * register a new preview.
280
306
  */
281
-
282
-
283
307
  registerPreview(preview) {
284
308
  this.previewSlot.register(preview);
285
309
  return this;
@@ -289,8 +313,10 @@ class PreviewPreview {
289
313
  */
290
314
 
291
315
 
292
- getRenderingContext() {
293
- return new (_renderingContext().RenderingContext)(this.renderingContextSlot);
316
+ getRenderingContext(aspectsFilter) {
317
+ return new (_renderingContext().RenderingContext)(this.renderingContextSlot, {
318
+ aspectsFilter
319
+ });
294
320
  }
295
321
  /**
296
322
  * allows aspects to add rendering contexts.
@@ -345,12 +371,8 @@ exports.PreviewPreview = PreviewPreview;
345
371
  (0, _defineProperty2().default)(PreviewPreview, "dependencies", [_pubsub().default]);
346
372
  (0, _defineProperty2().default)(PreviewPreview, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType()]);
347
373
 
348
- function linkModules(previewName, defaultModule, isSplitComponentBundle, componentMap) {
349
- PREVIEW_MODULES[previewName] = {
350
- mainModule: defaultModule,
351
- isSplitComponentBundle,
352
- componentMap
353
- };
374
+ function linkModules(previewName, previewModule) {
375
+ PREVIEW_MODULES[previewName] = previewModule;
354
376
  }
355
377
 
356
378
  _preview().PreviewAspect.addRuntime(PreviewPreview);
@@ -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","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","parentPreviewName","componentMap","component","fetchComponentPreview","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","resolve","forEach","file","endsWith","addComponentFileElement","reject","previewScriptElement","getPreviewScriptElement","document","head","appendChild","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","toString","url","res","status","parsed","json","isBundledWithEnv","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","is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;AACA7C,EAAAA,eAAe,CAACM,WAAD,CAAf,GAA+B;AAC7B0C,IAAAA,UAAU,EAAEyE,aADiB;AAE7BC,IAAAA,sBAF6B;AAG7B7E,IAAAA;AAH6B,GAA/B;AAKD;;AAEDJ,yBAAckF,UAAd,CAAyB1H,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, name)\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, parentPreviewName?: string): Promise<PreviewModule> {\n if (PREVIEW_MODULES[name].componentMap[id.fullName]) return PREVIEW_MODULES[name];\n let component;\n // Handle case when there is overview but no composition on the workspace dev server\n if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {\n // if (!window[name]) throw new PreviewNotFound(name);\n // const isSplitComponentBundle = PREVIEW_MODULES[name].isSplitComponentBundle ?? false;\n // const component = window[id.toStringWithoutVersion()];\n component = await this.fetchComponentPreview(id, name);\n }\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 // It's a component bundled with the env\n if (allFiles === null) {\n return Promise.resolve(undefined);\n }\n allFiles.forEach((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n } else {\n this.addComponentFileElement(id, file);\n }\n });\n return new Promise((resolve, reject) => {\n const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);\n document.head.appendChild(previewScriptElement);\n });\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n document.head.appendChild(script);\n return script;\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const link = document.createElement('link');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n link.setAttribute('href', href);\n if (previewBundleFileName.endsWith('.css')) {\n link.setAttribute('rel', 'stylesheet');\n }\n document.head.appendChild(link);\n return link;\n }\n\n private getPreviewScriptElement(id: ComponentID, name: string, previewBundleFileName: string, resolve, reject) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n // const previewRoute = `~aspect/preview`;\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src; // generate path to remote scope. [scope url]/\n script.onload = () => {\n const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];\n if (!componentPreview) return reject(new PreviewNotFound(name));\n const targetPreview = componentPreview[name];\n if (!targetPreview) return resolve(undefined);\n\n return resolve(targetPreview);\n };\n return script;\n }\n\n /**\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
+ {"version":3,"sources":["preview.preview.runtime.tsx"],"names":["PREVIEW_MODULES","PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","Promise","all","include","map","prevName","includedPreview","undefined","selectPreviewModel","fullName","getPreviewModule","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","parentPreviewName","relevantModel","componentMap","component","fetchComponentPreview","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","resolve","forEach","file","endsWith","addComponentFileElement","reject","previewScriptElement","getPreviewScriptElement","document","head","appendChild","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","url","res","status","parsed","json","isBundledWithEnv","files","length","script","createElement","setAttribute","previewRoute","src","link","href","onload","componentPreview","toStringWithoutVersion","targetPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","get","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","linkModules","previewModule","addRuntime"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;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;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAIA,MAAMA,eAA8C,GAAG,EAAvD;;AAMO,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,mDAYc,KAZd;AAAA,oDAiBO,MAAOC,OAAP,I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AW,GAAG3E,MAAM,CAAC4E,QAAP,CAAgBC,IAAhB,CAAqBC,SAArB,CAA+B,CAA/B,CAApB;AACA,UAAM,CAACC,MAAD,EAASC,KAAT,IAAkBL,WAAW,CAACM,KAAZ,CAAkB,GAAlB,CAAxB;AAEA,WAAO;AACLjH,MAAAA,WAAW,EAAE,KAAKqG,QAAL,CAAcW,KAAd,EAAqB,SAArB,CADR;AAEL/G,MAAAA,WAAW,EAAEiH,2BAAYC,aAAZ,CAA0BJ,MAA1B;AAFR,KAAP;AAID;;AAQoB,eAARK,QAAQ,CACnB,CAACxH,MAAD,CADmB,EAEnByH,MAFmB,EAGnB,CAACxH,WAAD,EAAcC,oBAAd,CAHmB,EAInB;AACA,UAAMQ,OAAO,GAAG,IAAIZ,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;AAEAkC,IAAAA,MAAM,CAACC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;AAC1C;AACA3B,MAAAA,OAAO,CAACoB,MAAR;AACD,KAHD;AAKA,WAAOpB,OAAP;AACD;;AA7PyB;;;gCAAfZ,c,aA0OM4H,yB;gCA1ON5H,c,kBA4OW,CAAC6H,iBAAD,C;gCA5OX7H,c,WA8OI,CAAC8H,gBAAKC,QAAL,EAAD,EAA+BD,gBAAKC,QAAL,EAA/B,C;;AAkBV,SAASC,WAAT,CAAqB1H,WAArB,EAA0C2H,aAA1C,EAAwE;AAC7ElI,EAAAA,eAAe,CAACO,WAAD,CAAf,GAA+B2H,aAA/B;AACD;;AAEDjF,yBAAckF,UAAd,CAAyBlI,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';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nconst PREVIEW_MODULES: Record<string, PreviewModule> = {};\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (prevName) => {\n const includedPreview = this.getPreview(prevName);\n if (!includedPreview) return undefined;\n\n return includedPreview.selectPreviewModel?.(\n componentId.fullName,\n await this.getPreviewModule(prevName, componentId, name)\n );\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule> {\n const relevantModel = PREVIEW_MODULES[name];\n if (relevantModel.componentMap[id.fullName]) return relevantModel;\n\n let component;\n // Handle case when there is overview but no composition on the workspace dev server\n if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {\n // if (!window[name]) throw new PreviewNotFound(name);\n // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;\n // const component = window[id.toStringWithoutVersion()];\n component = await this.fetchComponentPreview(id, name);\n }\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string) {\n let previewFile;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) {\n return Promise.resolve(undefined);\n }\n allFiles.forEach((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n } else {\n this.addComponentFileElement(id, file);\n }\n });\n return new Promise((resolve, reject) => {\n const previewScriptElement = this.getPreviewScriptElement(id, name, previewFile, resolve, reject);\n document.head.appendChild(previewScriptElement);\n });\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n document.head.appendChild(script);\n return script;\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const link = document.createElement('link');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n link.setAttribute('href', href);\n if (previewBundleFileName.endsWith('.css')) {\n link.setAttribute('rel', 'stylesheet');\n }\n document.head.appendChild(link);\n return link;\n }\n\n private getPreviewScriptElement(id: ComponentID, name: string, previewBundleFileName: string, resolve, reject) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n // const previewRoute = `~aspect/preview`;\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src; // generate path to remote scope. [scope url]/\n script.onload = () => {\n const componentPreview = window[`${id.toStringWithoutVersion()}-preview`];\n if (!componentPreview) return reject(new PreviewNotFound(name));\n const targetPreview = componentPreview[name];\n if (!targetPreview) return resolve(undefined);\n\n return resolve(targetPreview);\n };\n return script;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nexport function linkModules(previewName: string, previewModule: PreviewModule) {\n PREVIEW_MODULES[previewName] = previewModule;\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"]}
@@ -1,7 +1,14 @@
1
1
  import { RenderingContextSlot } from './preview.preview.runtime';
2
+ export declare type RenderingContextOptions = {
3
+ aspectsFilter?: string[];
4
+ };
5
+ export declare type RenderingContextProvider = (options: RenderingContextOptions) => {
6
+ [key: string]: any;
7
+ };
2
8
  export declare class RenderingContext {
3
9
  private contexts;
4
- constructor(contexts: RenderingContextSlot);
10
+ private options;
11
+ constructor(contexts: RenderingContextSlot, options?: RenderingContextOptions);
5
12
  /**
6
13
  * obtain rendering context of a specific aspect.
7
14
  */
@@ -6,8 +6,9 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.RenderingContext = void 0;
7
7
 
8
8
  class RenderingContext {
9
- constructor(contexts) {
9
+ constructor(contexts, options = {}) {
10
10
  this.contexts = contexts;
11
+ this.options = options;
11
12
  }
12
13
  /**
13
14
  * obtain rendering context of a specific aspect.
@@ -15,9 +16,8 @@ class RenderingContext {
15
16
 
16
17
 
17
18
  get(aspectId) {
18
- var _this$contexts$get;
19
-
20
- return (_this$contexts$get = this.contexts.get(aspectId)) === null || _this$contexts$get === void 0 ? void 0 : _this$contexts$get();
19
+ const contextFactory = this.contexts.get(aspectId);
20
+ return contextFactory === null || contextFactory === void 0 ? void 0 : contextFactory(this.options);
21
21
  }
22
22
 
23
23
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["rendering-context.ts"],"names":["RenderingContext","constructor","contexts","get","aspectId"],"mappings":";;;;;;;AAEO,MAAMA,gBAAN,CAAuB;AAC5BC,EAAAA,WAAW,CAASC,QAAT,EAAyC;AAAA,SAAhCA,QAAgC,GAAhCA,QAAgC;AAAE;AAEtD;AACF;AACA;;;AACEC,EAAAA,GAAG,CAACC,QAAD,EAAmB;AAAA;;AACpB,iCAAO,KAAKF,QAAL,CAAcC,GAAd,CAAkBC,QAAlB,CAAP,uDAAO,oBAAP;AACD;;AAR2B","sourcesContent":["import { RenderingContextSlot } from './preview.preview.runtime';\n\nexport class RenderingContext {\n constructor(private contexts: RenderingContextSlot) {}\n\n /**\n * obtain rendering context of a specific aspect.\n */\n get(aspectId: string) {\n return this.contexts.get(aspectId)?.();\n }\n}\n"]}
1
+ {"version":3,"sources":["rendering-context.ts"],"names":["RenderingContext","constructor","contexts","options","get","aspectId","contextFactory"],"mappings":";;;;;;;AAKO,MAAMA,gBAAN,CAAuB;AAC5BC,EAAAA,WAAW,CAASC,QAAT,EAAiDC,OAAgC,GAAG,EAApF,EAAwF;AAAA,SAA/ED,QAA+E,GAA/EA,QAA+E;AAAA,SAAvCC,OAAuC,GAAvCA,OAAuC;AAAE;AAErG;AACF;AACA;;;AACEC,EAAAA,GAAG,CAACC,QAAD,EAAmB;AACpB,UAAMC,cAAc,GAAG,KAAKJ,QAAL,CAAcE,GAAd,CAAkBC,QAAlB,CAAvB;AACA,WAAOC,cAAP,aAAOA,cAAP,uBAAOA,cAAc,CAAG,KAAKH,OAAR,CAArB;AACD;;AAT2B","sourcesContent":["import { RenderingContextSlot } from './preview.preview.runtime';\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\n\nexport class RenderingContext {\n constructor(private contexts: RenderingContextSlot, private options: RenderingContextOptions = {}) {}\n\n /**\n * obtain rendering context of a specific aspect.\n */\n get(aspectId: string) {\n const contextFactory = this.contexts.get(aspectId);\n return contextFactory?.(this.options);\n }\n}\n"]}
@@ -25,16 +25,6 @@ function _defineProperty2() {
25
25
  return data;
26
26
  }
27
27
 
28
- function _fs() {
29
- const data = require("fs");
30
-
31
- _fs = function () {
32
- return data;
33
- };
34
-
35
- return data;
36
- }
37
-
38
28
  function _path() {
39
29
  const data = require("path");
40
30
 
@@ -241,6 +231,9 @@ class ComponentBundlingStrategy {
241
231
  if (!capsule) return;
242
232
  const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});
243
233
  if (!files) return;
234
+ const artifactDirFullPath = (0, _path().join)(capsule.path, this.getArtifactDirectory()); // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders
235
+
236
+ (0, _fsExtra().mkdirpSync)(artifactDirFullPath);
244
237
  files.forEach(asset => {
245
238
  const filePath = this.getAssetAbsolutePath(context, asset);
246
239
 
@@ -248,17 +241,9 @@ class ComponentBundlingStrategy {
248
241
  throw new (_exceptions().PreviewOutputFileNotFound)(component.id, filePath);
249
242
  }
250
243
 
251
- const contents = (0, _fs().readFileSync)(filePath); // const exists = capsule.fs.existsSync(this.getArtifactDirectory());
252
- // if (!exists) capsule.fs.mkdirSync(this.getArtifactDirectory());
253
- // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders
254
-
255
- (0, _fsExtra().mkdirpSync)((0, _path().join)(capsule.path, this.getArtifactDirectory()));
256
- const filename = (0, _path().basename)(asset.name); // let filename = asset.name;
257
- // if (filePath.endsWith('.css')){
258
- // filename = this.getCssFileName(capsule.component.id);
259
- // }
260
-
261
- capsule.fs.writeFileSync((0, _path().join)(this.getArtifactDirectory(), filename), contents);
244
+ const destFilePath = (0, _path().join)(artifactDirFullPath, asset.name);
245
+ (0, _fsExtra().mkdirpSync)((0, _path().dirname)(destFilePath));
246
+ capsule.fs.copyFileSync(filePath, destFilePath);
262
247
  });
263
248
  });
264
249
  } // private getCssFileName(componentId: ComponentID): string {
@@ -1 +1 @@
1
- {"version":3,"sources":["component-strategy.ts"],"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","entriesArr","Promise","all","capsuleNetwork","seedersCapsules","map","capsule","computeComponentEntry","component","entries","reduce","entriesMap","entry","Object","assign","components","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","copyAssetsToCapsules","result","forEach","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","filePath","PreviewOutputFileNotFound","contents","getArtifactDirectory","fs","writeFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","errors","componentsResults","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","globPatterns","rootDir","getDirName","envName","replace","capsulesRootDir","compiler","env","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","compiledPaths","prefix","paths","moduleMaps","writeLinkContents"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAMA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEO,MAAMA,oBAAoB,GAAG,SAA7B;;AACA,MAAMC,sBAAsB,GAAG,WAA/B;;AACA,MAAMC,6BAA6B,GAAI,GAAEF,oBAAqB,KAA9D;;AACA,MAAMG,+BAA+B,GAAI,GAAEF,sBAAuB,KAAlE;;AAEA,MAAMG,gCAAgC,GAAG,MAAzC;;AACA,MAAMC,gCAAgC,GAAG,mBAAzC;AACP;AACA;AACA;;;;AACO,MAAMC,yBAAN,CAA4D;AAGjEC,EAAAA,WAAW,CAASC,OAAT,EAAuCC,GAAvC,EAA6DC,kBAA7D,EAAyG;AAAA,SAAhGF,OAAgG,GAAhGA,OAAgG;AAAA,SAAlEC,GAAkE,GAAlEA,GAAkE;AAAA,SAA5CC,kBAA4C,GAA5CA,kBAA4C;AAAA,kDAF7G,WAE6G;AAAE;;AAElG,QAAdC,cAAc,CAACC,OAAD,EAAiCC,WAAjC,EAAmE;AACrF,UAAMC,UAAU,GAAG,KAAKC,aAAL,CAAmBH,OAAnB,CAAnB;AACA,QAAI,C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} from 'fs';\nimport { join, resolve, basename } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const entriesArr = await Promise.all(\n context.capsuleNetwork.seedersCapsules.map((capsule) => {\n return this.computeComponentEntry(previewDefs, capsule.component, context);\n }, {})\n );\n\n const entries: BundlerEntryMap = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n Object.assign(entriesMap, entry);\n return entriesMap;\n }, {});\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n\n return [\n {\n // entries: await this.computePaths(outputPath, previewDefs, context),\n entries,\n components: context.components,\n outputPath,\n // modules,\n },\n ];\n }\n\n async computeComponentEntry(previewDefs: PreviewDefinition[], component: Component, context: ComputeTargetsContext) {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return entries;\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', asset.name);\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const contents = readFileSync(filePath);\n // const exists = capsule.fs.existsSync(this.getArtifactDirectory());\n // if (!exists) capsule.fs.mkdirSync(this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(join(capsule.path, this.getArtifactDirectory()));\n const filename = basename(asset.name);\n // let filename = asset.name;\n // if (filePath.endsWith('.css')){\n // filename = this.getCssFileName(capsule.component.id);\n // }\n capsule.fs.writeFileSync(join(this.getArtifactDirectory(), filename), contents);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n // const files = flatten(paths.toArray().map(([, file]) => file));\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = flatten(await Promise.all(moduleMapsPromise));\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"]}
1
+ {"version":3,"sources":["component-strategy.ts"],"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","entriesArr","Promise","all","capsuleNetwork","seedersCapsules","map","capsule","computeComponentEntry","component","entries","reduce","entriesMap","entry","Object","assign","components","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","copyAssetsToCapsules","result","forEach","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","fs","copyFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","errors","componentsResults","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","globPatterns","rootDir","getDirName","envName","replace","capsulesRootDir","compiler","env","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","compiledPaths","prefix","paths","moduleMaps","contents","writeLinkContents"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAMA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEO,MAAMA,oBAAoB,GAAG,SAA7B;;AACA,MAAMC,sBAAsB,GAAG,WAA/B;;AACA,MAAMC,6BAA6B,GAAI,GAAEF,oBAAqB,KAA9D;;AACA,MAAMG,+BAA+B,GAAI,GAAEF,sBAAuB,KAAlE;;AAEA,MAAMG,gCAAgC,GAAG,MAAzC;;AACA,MAAMC,gCAAgC,GAAG,mBAAzC;AACP;AACA;AACA;;;;AACO,MAAMC,yBAAN,CAA4D;AAGjEC,EAAAA,WAAW,CAASC,OAAT,EAAuCC,GAAvC,EAA6DC,kBAA7D,EAAyG;AAAA,SAAhGF,OAAgG,GAAhGA,OAAgG;AAAA,SAAlEC,GAAkE,GAAlEA,GAAkE;AAAA,SAA5CC,kBAA4C,GAA5CA,kBAA4C;AAAA,kDAF7G,WAE6G;AAAE;;AAElG,QAAdC,cAAc,CAACC,OAA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,CA0BjB;AACD;;AA/TgE","sourcesContent":["import { join, resolve, basename, dirname } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const entriesArr = await Promise.all(\n context.capsuleNetwork.seedersCapsules.map((capsule) => {\n return this.computeComponentEntry(previewDefs, capsule.component, context);\n }, {})\n );\n\n const entries: BundlerEntryMap = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n Object.assign(entriesMap, entry);\n return entriesMap;\n }, {});\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n\n return [\n {\n // entries: await this.computePaths(outputPath, previewDefs, context),\n entries,\n components: context.components,\n outputPath,\n // modules,\n },\n ];\n }\n\n async computeComponentEntry(previewDefs: PreviewDefinition[], component: Component, context: ComputeTargetsContext) {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return entries;\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', asset.name);\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(artifactDirFullPath);\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const destFilePath = join(artifactDirFullPath, asset.name);\n mkdirpSync(dirname(destFilePath));\n capsule.fs.copyFileSync(filePath, destFilePath);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n // const files = flatten(paths.toArray().map(([, file]) => file));\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = flatten(await Promise.all(moduleMapsPromise));\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"]}
@@ -0,0 +1,34 @@
1
+ import { request, gql } from 'graphql-request';
2
+
3
+ const GQL_SERVER = '/graphql';
4
+ const GET_COMPONENT_ASPECTS = gql`
5
+ query getComponentAspects($id: String!) {
6
+ getHost {
7
+ id
8
+ get(id: $id) {
9
+ aspects {
10
+ id
11
+ }
12
+ }
13
+ }
14
+ }
15
+ `;
16
+ type QueryResult = {
17
+ getHost: {
18
+ id: string;
19
+ get: {
20
+ aspects: { id: string }[];
21
+ };
22
+ };
23
+ };
24
+
25
+ export async function fetchComponentAspects(componentId: string) {
26
+ try {
27
+ const response = await request<QueryResult>(GQL_SERVER, GET_COMPONENT_ASPECTS, { id: componentId.toString() });
28
+ return response.getHost.get.aspects.map((x) => x.id);
29
+ } catch (err: any) {
30
+ // eslint-disable-next-line no-console
31
+ console.error(`[gql] error on "getComponentAspects" - "${err.toString()}"`);
32
+ return undefined;
33
+ }
34
+ }
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.666",
3
+ "version": "0.0.669",
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.666"
9
+ "version": "0.0.669"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -16,28 +16,30 @@
16
16
  "graphql-tag": "2.12.1",
17
17
  "object-hash": "2.1.1",
18
18
  "cross-fetch": "3.0.6",
19
+ "memoizee": "0.4.15",
20
+ "graphql-request": "3.4.0",
19
21
  "@babel/runtime": "7.12.18",
20
22
  "core-js": "^3.0.0",
21
- "@teambit/express": "0.0.544",
22
- "@teambit/logger": "0.0.540",
23
+ "@teambit/express": "0.0.545",
24
+ "@teambit/logger": "0.0.541",
23
25
  "@teambit/ui-foundation.ui.pages.static-error": "0.0.71",
24
- "@teambit/builder": "0.0.666",
25
- "@teambit/bundler": "0.0.666",
26
- "@teambit/component": "0.0.666",
27
- "@teambit/envs": "0.0.666",
28
- "@teambit/isolator": "0.0.666",
26
+ "@teambit/builder": "0.0.669",
27
+ "@teambit/bundler": "0.0.669",
28
+ "@teambit/component": "0.0.669",
29
+ "@teambit/envs": "0.0.669",
30
+ "@teambit/isolator": "0.0.669",
29
31
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.483",
30
- "@teambit/aspect-loader": "0.0.666",
31
- "@teambit/bit-error": "0.0.394",
32
- "@teambit/cli": "0.0.450",
33
- "@teambit/dependency-resolver": "0.0.666",
34
- "@teambit/graphql": "0.0.666",
35
- "@teambit/pkg": "0.0.666",
36
- "@teambit/pubsub": "0.0.666",
37
- "@teambit/ui": "0.0.666",
38
- "@teambit/workspace": "0.0.666",
39
32
  "@teambit/component-id": "0.0.401",
40
- "@teambit/compiler": "0.0.666",
33
+ "@teambit/aspect-loader": "0.0.669",
34
+ "@teambit/bit-error": "0.0.394",
35
+ "@teambit/cli": "0.0.451",
36
+ "@teambit/dependency-resolver": "0.0.669",
37
+ "@teambit/graphql": "0.0.669",
38
+ "@teambit/pkg": "0.0.669",
39
+ "@teambit/pubsub": "0.0.669",
40
+ "@teambit/ui": "0.0.669",
41
+ "@teambit/workspace": "0.0.669",
42
+ "@teambit/compiler": "0.0.669",
41
43
  "@teambit/preview.cli.preview-server-status": "0.0.491",
42
44
  "@teambit/preview.cli.webpack-events-listener": "0.0.161"
43
45
  },
@@ -46,6 +48,7 @@
46
48
  "@types/fs-extra": "9.0.7",
47
49
  "@types/lodash": "4.14.165",
48
50
  "@types/object-hash": "1.3.4",
51
+ "@types/memoizee": "0.4.5",
49
52
  "@types/react": "^17.0.8",
50
53
  "@types/mocha": "9.1.0",
51
54
  "@types/testing-library__jest-dom": "5.9.5",
@@ -55,7 +58,7 @@
55
58
  "@teambit/preview.aspect-docs.preview": "0.0.132"
56
59
  },
57
60
  "peerDependencies": {
58
- "@teambit/legacy": "1.0.229",
61
+ "@teambit/legacy": "1.0.230",
59
62
  "react-dom": "^16.8.0 || ^17.0.0",
60
63
  "react": "^16.8.0 || ^17.0.0"
61
64
  },
@@ -83,7 +86,7 @@
83
86
  "react": "-"
84
87
  },
85
88
  "peerDependencies": {
86
- "@teambit/legacy": "1.0.229",
89
+ "@teambit/legacy": "1.0.230",
87
90
  "react-dom": "^16.8.0 || ^17.0.0",
88
91
  "react": "^16.8.0 || ^17.0.0"
89
92
  }
@@ -1 +1 @@
1
- export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.666/dist/preview.docs.mdx')]
1
+ export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.669/dist/preview.docs.mdx')]
@@ -282,7 +282,7 @@ export class PreviewMain {
282
282
 
283
283
  writeLinkContents(contents: string, targetDir: string, prefix: string) {
284
284
  const hash = objectHash(contents);
285
- const targetPath = join(targetDir, `__${prefix}-${this.timestamp}.js`);
285
+ const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);
286
286
 
287
287
  // write only if link has changed (prevents triggering fs watches)
288
288
  if (this.writeHash.get(targetPath) !== hash) {
@@ -2,6 +2,7 @@ import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';
2
2
  import { Slot, SlotRegistry } from '@teambit/harmony';
3
3
  import { ComponentID } from '@teambit/component-id';
4
4
  import crossFetch from 'cross-fetch';
5
+ import memoize from 'memoizee';
5
6
 
6
7
  import { PreviewNotFound } from './exceptions';
7
8
  import { PreviewType } from './preview-type';
@@ -9,12 +10,14 @@ import { PreviewAspect, PreviewRuntime } from './preview.aspect';
9
10
  import { ClickInsideAnIframeEvent } from './events';
10
11
  import { PreviewModule } from './types/preview-module';
11
12
  import { RenderingContext } from './rendering-context';
13
+ import { fetchComponentAspects } from './gql/fetch-component-aspects';
12
14
 
13
15
  export type PreviewSlot = SlotRegistry<PreviewType>;
14
16
 
15
17
  const PREVIEW_MODULES: Record<string, PreviewModule> = {};
16
18
 
17
- export type RenderingContextProvider = () => { [key: string]: any };
19
+ export type RenderingContextOptions = { aspectsFilter?: string[] };
20
+ export type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };
18
21
  export type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;
19
22
 
20
23
  export class PreviewPreview {
@@ -42,17 +45,21 @@ export class PreviewPreview {
42
45
  });
43
46
  }
44
47
 
48
+ private isDev = false;
49
+
45
50
  /**
46
51
  * render the preview.
47
52
  */
48
- render = async () => {
53
+ render = async (rootExt?: string) => {
49
54
  const { previewName, componentId } = this.getLocation();
50
55
  const name = previewName || this.getDefault();
56
+ if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';
51
57
 
52
58
  const preview = this.getPreview(name);
53
59
  if (!preview || !componentId) {
54
60
  throw new PreviewNotFound(previewName);
55
61
  }
62
+
56
63
  const includesAll = await Promise.all(
57
64
  (preview.include || []).map(async (prevName) => {
58
65
  const includedPreview = this.getPreview(prevName);
@@ -66,28 +73,32 @@ export class PreviewPreview {
66
73
  );
67
74
 
68
75
  const includes = includesAll.filter((module) => !!module);
76
+ // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
77
+ const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
69
78
 
70
79
  return preview.render(
71
- componentId.fullName,
80
+ componentId,
72
81
  await this.getPreviewModule(name, componentId),
73
82
  includes,
74
- this.getRenderingContext()
83
+ this.getRenderingContext(componentAspects)
75
84
  );
76
85
  };
77
86
 
78
87
  async getPreviewModule(name: string, id: ComponentID, parentPreviewName?: string): Promise<PreviewModule> {
79
- if (PREVIEW_MODULES[name].componentMap[id.fullName]) return PREVIEW_MODULES[name];
88
+ const relevantModel = PREVIEW_MODULES[name];
89
+ if (relevantModel.componentMap[id.fullName]) return relevantModel;
90
+
80
91
  let component;
81
92
  // Handle case when there is overview but no composition on the workspace dev server
82
93
  if (!parentPreviewName || !PREVIEW_MODULES[parentPreviewName].componentMap[id.fullName]) {
83
94
  // if (!window[name]) throw new PreviewNotFound(name);
84
- // const isSplitComponentBundle = PREVIEW_MODULES[name].isSplitComponentBundle ?? false;
95
+ // const isSplitComponentBundle = relevantModel.isSplitComponentBundle ?? false;
85
96
  // const component = window[id.toStringWithoutVersion()];
86
97
  component = await this.fetchComponentPreview(id, name);
87
98
  }
88
99
 
89
100
  return {
90
- mainModule: PREVIEW_MODULES[name].mainModule,
101
+ mainModule: relevantModel.mainModule,
91
102
  componentMap: {
92
103
  [id.fullName]: component,
93
104
  },
@@ -185,6 +196,11 @@ export class PreviewPreview {
185
196
  return script;
186
197
  }
187
198
 
199
+ private getComponentAspects = memoize(fetchComponentAspects, {
200
+ max: 100,
201
+ maxAge: 12 * 60 * 60 * 1000,
202
+ });
203
+
188
204
  /**
189
205
  * register a new preview.
190
206
  */
@@ -196,8 +212,8 @@ export class PreviewPreview {
196
212
  /**
197
213
  * get the preview rendering context.
198
214
  */
199
- getRenderingContext() {
200
- return new RenderingContext(this.renderingContextSlot);
215
+ getRenderingContext(aspectsFilter?: string[]) {
216
+ return new RenderingContext(this.renderingContextSlot, { aspectsFilter });
201
217
  }
202
218
 
203
219
  /**
@@ -260,17 +276,8 @@ export class PreviewPreview {
260
276
  }
261
277
  }
262
278
 
263
- export function linkModules(
264
- previewName: string,
265
- defaultModule: any,
266
- isSplitComponentBundle: boolean,
267
- componentMap: { [key: string]: any }
268
- ) {
269
- PREVIEW_MODULES[previewName] = {
270
- mainModule: defaultModule,
271
- isSplitComponentBundle,
272
- componentMap,
273
- };
279
+ export function linkModules(previewName: string, previewModule: PreviewModule) {
280
+ PREVIEW_MODULES[previewName] = previewModule;
274
281
  }
275
282
 
276
283
  PreviewAspect.addRuntime(PreviewPreview);
@@ -1,5 +1,4 @@
1
- import { readFileSync } from 'fs';
2
- import { join, resolve, basename } from 'path';
1
+ import { join, resolve, basename, dirname } from 'path';
3
2
  import { existsSync, mkdirpSync } from 'fs-extra';
4
3
  import { Component } from '@teambit/component';
5
4
  import { ComponentID } from '@teambit/component-id';
@@ -162,23 +161,18 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
162
161
  if (!capsule) return;
163
162
  const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});
164
163
  if (!files) return;
164
+ const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());
165
+ // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders
166
+ mkdirpSync(artifactDirFullPath);
165
167
 
166
168
  files.forEach((asset) => {
167
169
  const filePath = this.getAssetAbsolutePath(context, asset);
168
170
  if (!existsSync(filePath)) {
169
171
  throw new PreviewOutputFileNotFound(component.id, filePath);
170
172
  }
171
- const contents = readFileSync(filePath);
172
- // const exists = capsule.fs.existsSync(this.getArtifactDirectory());
173
- // if (!exists) capsule.fs.mkdirSync(this.getArtifactDirectory());
174
- // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders
175
- mkdirpSync(join(capsule.path, this.getArtifactDirectory()));
176
- const filename = basename(asset.name);
177
- // let filename = asset.name;
178
- // if (filePath.endsWith('.css')){
179
- // filename = this.getCssFileName(capsule.component.id);
180
- // }
181
- capsule.fs.writeFileSync(join(this.getArtifactDirectory(), filename), contents);
173
+ const destFilePath = join(artifactDirFullPath, asset.name);
174
+ mkdirpSync(dirname(destFilePath));
175
+ capsule.fs.copyFileSync(filePath, destFilePath);
182
176
  });
183
177
  });
184
178
  }