@teambit/preview 0.0.866 → 0.0.868

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 +1 @@
1
- {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","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","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","calcDoesScalingForComponent","isUsingCoreEnv","isNew","envComponent","getEnvComponent","isEnvSupportScaling","doesScaling","inWorkspace","hasId","envSupportScaling","calculateIsEnvSupportScaling","previewData","state","aspects","isScaling","isEnv","previewAspectConfig","getPreviewConfig","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","allComponentContextAspects","reduce","acc","curr","concat","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","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","onComponentLoad","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"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 {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} 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, UIRoot } 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 { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-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 PreviewVariantConfig = {\n isScaling?: boolean;\n}\n\n/**\n * Preview data that stored on the component on load\n */\nexport type PreviewComponentData = {\n doesScaling?: boolean;\n isScaling?: boolean;\n}\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\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.getArtifactsVinylByAspectAndTaskName(\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.getArtifactsVinylByAspectAndName(\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\n // This used on component load to calc the final result of support is scaling for a given component\n // This calc based on the env, env data, env preview config and more\n // if you want to get the final result use the `doesScaling` method below\n // This should be used only for component load\n private async calcDoesScalingForComponent(component: Component): Promise<boolean> {\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality\n if (this.envs.isUsingCoreEnv(component)){\n // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)\n // If it's new, and we are here, it means that we already use a version of the env that support scaling\n const isNew = await component.isNew();\n if (isNew){\n return true;\n }\n return isBundledWithEnv === false\n }\n // For envs that bundled with the env return true always\n if (isBundledWithEnv){\n return true;\n }\n const envComponent = await this.envs.getEnvComponent(component);\n return this.isEnvSupportScaling(envComponent)\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n * this calculation is based on the env of the component and if the env of the component support it.\n */\n async doesScaling(component: Component): Promise<boolean> {\n const inWorkspace = await this.workspace?.hasId(component.id);\n // Support case when we have the dev server for the env, in that case we calc the data of the env as we can't rely on the env data from the scope\n // since we bundle it for the dev server again\n if (inWorkspace) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = await this.calculateIsEnvSupportScaling(envComponent);\n return envSupportScaling ?? true;\n }\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n if (!previewData) return false;\n // Get the does scaling (the new calculation) or the old calc used in isScaling (between versions (about) 848 and 860)\n if (previewData.doesScaling !== undefined) return previewData.doesScaling;\n // in case this component were tagged with versions between 848 and 860 we need to use the old calculation\n // together with the env calculation\n // In that case it means the component already tagged, so we take the env calc from the env data and not re-calc it\n if (previewData.isScaling) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = this.isEnvSupportScaling(envComponent);\n return !!envSupportScaling;\n }\n return false;\n }\n\n /**\n * Check if the current version of the env support scaling\n * @param envComponent\n * @returns\n */\n isEnvSupportScaling(envComponent: Component): boolean {\n const previewData = envComponent.state.aspects.get(PreviewAspect.id)?.data;\n return (!!previewData?.isScaling);\n }\n\n /**\n * This function is calculate the isScaling support flag for the component preview.\n * This is calculated only for the env component and not for the component itself.\n * It should be only used during the (env) component on load.\n * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.\n * If you want to check if an env for a given component support scaling, use the `isScaling` function.\n * @param component\n * @returns\n */\n private async calculateIsEnvSupportScaling(envComponent: Component): Promise<boolean | undefined> {\n const isEnv = this.envs.isEnv(envComponent);\n // If the component is not an env, we don't want to store anything in the data\n if (!isEnv) return undefined;\n const previewAspectConfig = this.getPreviewConfig(envComponent);\n // default to true if the env doesn't have a preview config\n return previewAspectConfig?.isScaling ?? true;\n }\n\n /**\n * Get the preview config of the component.\n * (config that was set by variants or on bitmap)\n * @param component\n * @returns\n */\n getPreviewConfig(component: Component): PreviewVariantConfig | undefined {\n return component.state.aspects.get(PreviewAspect.id)?.config;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\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.getArtifactsVinylByAspectAndTaskName(\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 isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(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 [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\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 async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\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 [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\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([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.onComponentLoad(async (component) => {\n const doesScaling = await preview.calcDoesScalingForComponent(component);\n const isScaling = await preview.calculateIsEnvSupportScaling(component);\n const data: PreviewComponentData = {\n doesScaling,\n }\n // If there is no isScaling result at all, it's probably not an env. don't store any data.\n if (isScaling !== undefined){\n data.isScaling = isScaling\n }\n return data;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;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CD,eAAA,CAAKC,QAAL,EAArC,C;gCAtfJvP,W,aAwfMmL,kB;gCAxfNnL,W,kBAyfW,CACpBwP,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAzfXnQ,W,mBAwgBY;EACrB0O,QAAQ,EAAE;AADW,C;;AAyGzB5O,wBAAA,CAAcsQ,UAAd,CAAyBpQ,WAAzB"}
1
+ {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","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","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","calcDoesScalingForComponent","isUsingCoreEnv","isNew","envComponent","getEnvComponent","isEnvSupportScaling","doesScaling","inWorkspace","hasId","envSupportScaling","calculateIsEnvSupportScaling","previewData","state","aspects","isScaling","isEnv","previewAspectConfig","getPreviewConfig","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","allComponentContextAspects","reduce","acc","curr","concat","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","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","onComponentLoad","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"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 {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} 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, UIRoot } 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 { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-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 PreviewVariantConfig = {\n isScaling?: boolean;\n};\n\n/**\n * Preview data that stored on the component on load\n */\nexport type PreviewComponentData = {\n doesScaling?: boolean;\n isScaling?: boolean;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\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.getArtifactsVinylByAspectAndTaskName(\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.getArtifactsVinylByAspectAndName(\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 // This used on component load to calc the final result of support is scaling for a given component\n // This calc based on the env, env data, env preview config and more\n // if you want to get the final result use the `doesScaling` method below\n // This should be used only for component load\n private async calcDoesScalingForComponent(component: Component): Promise<boolean> {\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality\n if (this.envs.isUsingCoreEnv(component)) {\n // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)\n // If it's new, and we are here, it means that we already use a version of the env that support scaling\n const isNew = await component.isNew();\n if (isNew) {\n return true;\n }\n return isBundledWithEnv === false;\n }\n // For envs that bundled with the env return true always\n if (isBundledWithEnv) {\n return true;\n }\n const envComponent = await this.envs.getEnvComponent(component);\n return this.isEnvSupportScaling(envComponent);\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n * this calculation is based on the env of the component and if the env of the component support it.\n */\n async doesScaling(component: Component): Promise<boolean> {\n const inWorkspace = await this.workspace?.hasId(component.id);\n // Support case when we have the dev server for the env, in that case we calc the data of the env as we can't rely on the env data from the scope\n // since we bundle it for the dev server again\n if (inWorkspace) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = await this.calculateIsEnvSupportScaling(envComponent);\n return envSupportScaling ?? true;\n }\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n if (!previewData) return false;\n // Get the does scaling (the new calculation) or the old calc used in isScaling (between versions (about) 848 and 860)\n if (previewData.doesScaling !== undefined) return previewData.doesScaling;\n // in case this component were tagged with versions between 848 and 860 we need to use the old calculation\n // together with the env calculation\n // In that case it means the component already tagged, so we take the env calc from the env data and not re-calc it\n if (previewData.isScaling) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = this.isEnvSupportScaling(envComponent);\n return !!envSupportScaling;\n }\n return false;\n }\n\n /**\n * Check if the current version of the env support scaling\n * @param envComponent\n * @returns\n */\n isEnvSupportScaling(envComponent: Component): boolean {\n const previewData = envComponent.state.aspects.get(PreviewAspect.id)?.data;\n return !!previewData?.isScaling;\n }\n\n /**\n * This function is calculate the isScaling support flag for the component preview.\n * This is calculated only for the env component and not for the component itself.\n * It should be only used during the (env) component on load.\n * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.\n * If you want to check if an env for a given component support scaling, use the `isScaling` function.\n * @param component\n * @returns\n */\n private async calculateIsEnvSupportScaling(envComponent: Component): Promise<boolean | undefined> {\n const isEnv = this.envs.isEnv(envComponent);\n // If the component is not an env, we don't want to store anything in the data\n if (!isEnv) return undefined;\n const previewAspectConfig = this.getPreviewConfig(envComponent);\n // default to true if the env doesn't have a preview config\n return previewAspectConfig?.isScaling ?? true;\n }\n\n /**\n * Get the preview config of the component.\n * (config that was set by variants or on bitmap)\n * @param component\n * @returns\n */\n getPreviewConfig(component: Component): PreviewVariantConfig | undefined {\n return component.state.aspects.get(PreviewAspect.id)?.config;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\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.getArtifactsVinylByAspectAndTaskName(\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 isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(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 [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\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 async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\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 [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\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([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.onComponentLoad(async (component) => {\n const doesScaling = await preview.calcDoesScalingForComponent(component);\n const isScaling = await preview.calculateIsEnvSupportScaling(component);\n const data: PreviewComponentData = {\n doesScaling,\n };\n // If there is no isScaling result at all, it's probably not an env. don't store any data.\n if (isScaling !== undefined) {\n data.isScaling = isScaling;\n }\n return data;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;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GAN,SAAS,CAACuO,yBAAV,CAAqCrN,GAAD,IAASiM,OAAO,CAACqB,sBAAR,CAA+BtN,GAA/B,CAA7C;IACD;;IAED+L,OAAO,CAACR,QAAR,CAAiB,IAAAgC,yBAAA,EAActB,OAAd,CAAjB;IAEA,OAAOA,OAAP;EACD;;AA5mBsB;;;gCAAZ/N,W,WAofI,CAACsP,eAAA,CAAKC,QAAL,EAAD,EAAqCD,eAAA,CAAKC,QAAL,EAArC,C;gCApfJvP,W,aAsfMmL,kB;gCAtfNnL,W,kBAufW,CACpBwP,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAvfXnQ,W,mBAsgBY;EACrB0O,QAAQ,EAAE;AADW,C;;AAyGzB5O,wBAAA,CAAcsQ,UAAd,CAAyBpQ,WAAzB"}
@@ -1 +1 @@
1
- {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\nimport { debounce } from 'lodash';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n // fit content always.\n window.document.body.style.width = 'fit-content';\n\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(\n componentId,\n previewModule,\n includes,\n this.getRenderingContext(componentAspects)\n );\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }\n\n window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }, 200);\n }\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;A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CAAKC,QAAL,EAA/B,C;;AAkBjB/F,wBAAA,CAAcgG,UAAd,CAAyB/J,cAAzB"}
1
+ {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\nimport { debounce } from 'lodash';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n // fit content always.\n window.document.body.style.width = 'fit-content';\n\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n };\n\n window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(\n PreviewAspect.id,\n new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight,\n })\n );\n }, 200);\n }\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAMA,cAAN,CAAqB;EAC1BC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GAAlB,CAAxB;IAEA,OAAO;MACLnI,WAAW,EAAE,KAAKuD,QAAL,CAAc2E,KAAd,EAAqB,SAArB,CADR;MAELjI,WAAW,EAAEoI,0BAAA,CAAYC,aAAZ,CAA0BF,MAA1B;IAFR,CAAP;EAID;;EAQoB,aAARG,QAAQ,CACnB,CAACvJ,MAAD,CADmB,EAEnBwJ,MAFmB,EAGnB,CAACvJ,WAAD,EAAcC,oBAAd,CAHmB,EAInB;IACA,MAAMoB,OAAO,GAAG,IAAIxB,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEAS,MAAM,CAACyC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA9B,OAAO,CAACqB,MAAR;IACD,CAHD;IAKA,OAAOrB,OAAP;EACD;;AAxUyB;;;gCAAfxB,c,aAqTM2J,yB;gCArTN3J,c,kBAuTW,CAAC4J,iBAAD,C;gCAvTX5J,c,WAyTI,CAAC6J,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB/F,wBAAA,CAAcgG,UAAd,CAAyB/J,cAAzB"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.866",
3
+ "version": "0.0.868",
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.866"
9
+ "version": "0.0.868"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -23,29 +23,29 @@
23
23
  "@babel/runtime": "7.12.18",
24
24
  "core-js": "^3.0.0",
25
25
  "@teambit/harmony": "0.3.3",
26
- "@teambit/express": "0.0.675",
27
- "@teambit/logger": "0.0.670",
26
+ "@teambit/express": "0.0.677",
27
+ "@teambit/logger": "0.0.672",
28
28
  "@teambit/ui-foundation.ui.pages.static-error": "0.0.82",
29
- "@teambit/builder": "0.0.866",
30
- "@teambit/bundler": "0.0.866",
31
- "@teambit/component": "0.0.866",
32
- "@teambit/preview.ui.component-preview": "0.0.503",
33
- "@teambit/aspect-loader": "0.0.866",
34
- "@teambit/cli": "0.0.577",
35
- "@teambit/dependency-resolver": "0.0.866",
36
- "@teambit/envs": "0.0.866",
29
+ "@teambit/builder": "0.0.868",
30
+ "@teambit/bundler": "0.0.868",
31
+ "@teambit/component": "0.0.868",
32
+ "@teambit/preview.ui.component-preview": "0.0.504",
33
+ "@teambit/aspect-loader": "0.0.868",
34
+ "@teambit/cli": "0.0.579",
35
+ "@teambit/dependency-resolver": "0.0.868",
36
+ "@teambit/envs": "0.0.868",
37
37
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.489",
38
38
  "@teambit/component-id": "0.0.417",
39
39
  "@teambit/bit-error": "0.0.400",
40
- "@teambit/graphql": "0.0.866",
41
- "@teambit/pkg": "0.0.866",
42
- "@teambit/pubsub": "0.0.866",
43
- "@teambit/ui": "0.0.866",
44
- "@teambit/workspace": "0.0.866",
45
- "@teambit/compiler": "0.0.866",
40
+ "@teambit/graphql": "0.0.868",
41
+ "@teambit/pkg": "0.0.868",
42
+ "@teambit/pubsub": "0.0.868",
43
+ "@teambit/ui": "0.0.868",
44
+ "@teambit/workspace": "0.0.868",
45
+ "@teambit/compiler": "0.0.868",
46
46
  "@teambit/preview.cli.preview-server-status": "0.0.498",
47
47
  "@teambit/preview.cli.webpack-events-listener": "0.0.167",
48
- "@teambit/isolator": "0.0.866"
48
+ "@teambit/isolator": "0.0.868"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@types/mime": "2.0.3",
@@ -63,7 +63,7 @@
63
63
  "@teambit/preview.aspect-docs.preview": "0.0.145"
64
64
  },
65
65
  "peerDependencies": {
66
- "@teambit/legacy": "1.0.358",
66
+ "@teambit/legacy": "1.0.360",
67
67
  "react-dom": "^16.8.0 || ^17.0.0",
68
68
  "react": "^16.8.0 || ^17.0.0"
69
69
  },
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.866/dist/preview.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.866/dist/preview.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.868/dist/preview.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.868/dist/preview.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -86,7 +86,7 @@ export type ComponentPreviewMetaData = {
86
86
 
87
87
  export type PreviewVariantConfig = {
88
88
  isScaling?: boolean;
89
- }
89
+ };
90
90
 
91
91
  /**
92
92
  * Preview data that stored on the component on load
@@ -94,7 +94,7 @@ export type PreviewVariantConfig = {
94
94
  export type PreviewComponentData = {
95
95
  doesScaling?: boolean;
96
96
  isScaling?: boolean;
97
- }
97
+ };
98
98
 
99
99
  export type PreviewConfig = {
100
100
  bundlingStrategy?: string;
@@ -204,8 +204,6 @@ export class PreviewMain {
204
204
  return false;
205
205
  }
206
206
 
207
-
208
-
209
207
  // This used on component load to calc the final result of support is scaling for a given component
210
208
  // This calc based on the env, env data, env preview config and more
211
209
  // if you want to get the final result use the `doesScaling` method below
@@ -213,21 +211,21 @@ export class PreviewMain {
213
211
  private async calcDoesScalingForComponent(component: Component): Promise<boolean> {
214
212
  const isBundledWithEnv = await this.isBundledWithEnv(component);
215
213
  // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality
216
- if (this.envs.isUsingCoreEnv(component)){
214
+ if (this.envs.isUsingCoreEnv(component)) {
217
215
  // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)
218
216
  // If it's new, and we are here, it means that we already use a version of the env that support scaling
219
217
  const isNew = await component.isNew();
220
- if (isNew){
218
+ if (isNew) {
221
219
  return true;
222
220
  }
223
- return isBundledWithEnv === false
221
+ return isBundledWithEnv === false;
224
222
  }
225
223
  // For envs that bundled with the env return true always
226
- if (isBundledWithEnv){
224
+ if (isBundledWithEnv) {
227
225
  return true;
228
226
  }
229
227
  const envComponent = await this.envs.getEnvComponent(component);
230
- return this.isEnvSupportScaling(envComponent)
228
+ return this.isEnvSupportScaling(envComponent);
231
229
  }
232
230
 
233
231
  /**
@@ -265,7 +263,7 @@ export class PreviewMain {
265
263
  */
266
264
  isEnvSupportScaling(envComponent: Component): boolean {
267
265
  const previewData = envComponent.state.aspects.get(PreviewAspect.id)?.data;
268
- return (!!previewData?.isScaling);
266
+ return !!previewData?.isScaling;
269
267
  }
270
268
 
271
269
  /**
@@ -722,10 +720,10 @@ export class PreviewMain {
722
720
  const isScaling = await preview.calculateIsEnvSupportScaling(component);
723
721
  const data: PreviewComponentData = {
724
722
  doesScaling,
725
- }
723
+ };
726
724
  // If there is no isScaling result at all, it's probably not an env. don't store any data.
727
- if (isScaling !== undefined){
728
- data.isScaling = isScaling
725
+ if (isScaling !== undefined) {
726
+ data.isScaling = isScaling;
729
727
  }
730
728
  return data;
731
729
  });
@@ -108,12 +108,7 @@ export class PreviewPreview {
108
108
  // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering
109
109
  const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;
110
110
  const previewModule = await this.getPreviewModule(name, componentId);
111
- const render = preview.render(
112
- componentId,
113
- previewModule,
114
- includes,
115
- this.getRenderingContext(componentAspects)
116
- );
111
+ const render = preview.render(componentId, previewModule, includes, this.getRenderingContext(componentAspects));
117
112
 
118
113
  this.reportSize();
119
114
  this.setViewport();
@@ -136,11 +131,14 @@ export class PreviewPreview {
136
131
  // TODO: discuss with gilad for a better way to resolve page loaded here.
137
132
 
138
133
  const sendPubsubEvent = () => {
139
- this.pubsub.pub(PreviewAspect.id, new SizeEvent({
140
- width: window.document.body.offsetWidth,
141
- height: window.document.body.offsetHeight
142
- }));
143
- }
134
+ this.pubsub.pub(
135
+ PreviewAspect.id,
136
+ new SizeEvent({
137
+ width: window.document.body.offsetWidth,
138
+ height: window.document.body.offsetHeight,
139
+ })
140
+ );
141
+ };
144
142
 
145
143
  window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));
146
144
 
@@ -152,10 +150,13 @@ export class PreviewPreview {
152
150
  clearInterval(interval);
153
151
  return;
154
152
  }
155
- this.pubsub.pub(PreviewAspect.id, new SizeEvent({
156
- width: window.document.body.offsetWidth,
157
- height: window.document.body.offsetHeight
158
- }));
153
+ this.pubsub.pub(
154
+ PreviewAspect.id,
155
+ new SizeEvent({
156
+ width: window.document.body.offsetWidth,
157
+ height: window.document.body.offsetHeight,
158
+ })
159
+ );
159
160
  }, 200);
160
161
  }
161
162