@teambit/preview 1.0.106 → 1.0.108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/artifact-file-middleware.ts +66 -0
  2. package/bundling-strategy.ts +30 -0
  3. package/component-preview.route.ts +52 -0
  4. package/component-preview.ts +3 -0
  5. package/dist/artifact-file-middleware.d.ts +2 -2
  6. package/dist/artifact-file-middleware.js +2 -2
  7. package/dist/artifact-file-middleware.js.map +1 -1
  8. package/dist/bundler/chunks.d.ts +1 -1
  9. package/dist/bundler/html-plugin.js +1 -1
  10. package/dist/bundler/html-plugin.js.map +1 -1
  11. package/dist/bundling-strategy.d.ts +2 -2
  12. package/dist/env-preview-template.task.d.ts +1 -1
  13. package/dist/env-preview-template.task.js +1 -1
  14. package/dist/env-preview-template.task.js.map +1 -1
  15. package/dist/env-template.route.d.ts +1 -1
  16. package/dist/execution-ref.d.ts +1 -1
  17. package/dist/generate-link.d.ts +1 -1
  18. package/dist/gql/fetch-component-aspects.d.ts +1 -1
  19. package/dist/{preview-1703505948637.js → preview-1703647408454.js} +2 -2
  20. package/dist/preview-artifact.d.ts +2 -2
  21. package/dist/preview-env.d.ts +1 -1
  22. package/dist/preview-modules.d.ts +1 -1
  23. package/dist/preview.composition.d.ts +2 -2
  24. package/dist/preview.main.runtime.d.ts +14 -14
  25. package/dist/preview.main.runtime.js +17 -24
  26. package/dist/preview.main.runtime.js.map +1 -1
  27. package/dist/preview.preview.runtime.d.ts +5 -5
  28. package/dist/preview.preview.runtime.js +5 -8
  29. package/dist/preview.preview.runtime.js.map +1 -1
  30. package/dist/preview.service.d.ts +1 -1
  31. package/dist/preview.service.js +1 -1
  32. package/dist/preview.service.js.map +1 -1
  33. package/dist/preview.start-plugin.d.ts +2 -2
  34. package/dist/rendering-context.d.ts +3 -3
  35. package/dist/rendering-context.js +1 -1
  36. package/dist/rendering-context.js.map +1 -1
  37. package/dist/size-event.d.ts +1 -1
  38. package/dist/strategies/component-strategy.d.ts +1 -1
  39. package/dist/strategies/component-strategy.js +12 -15
  40. package/dist/strategies/component-strategy.js.map +1 -1
  41. package/dist/strategies/env-strategy.js +1 -1
  42. package/dist/strategies/env-strategy.js.map +1 -1
  43. package/dist/strategies/generate-component-link.d.ts +1 -1
  44. package/dist/types/preview-module.d.ts +3 -3
  45. package/env-preview-template.task.ts +280 -0
  46. package/env-template.route.ts +72 -0
  47. package/execution-ref.ts +25 -0
  48. package/generate-link.ts +73 -0
  49. package/index.ts +18 -0
  50. package/mk-temp-dir.ts +7 -0
  51. package/package.json +31 -38
  52. package/preview-artifact.ts +24 -0
  53. package/preview-assets.route.ts +36 -0
  54. package/preview-context.ts +5 -0
  55. package/preview-definition.ts +41 -0
  56. package/preview-env.ts +46 -0
  57. package/preview-type.ts +36 -0
  58. package/preview.aspect.ts +12 -0
  59. package/preview.graphql.ts +48 -0
  60. package/preview.route.ts +58 -0
  61. package/preview.task.ts +85 -0
  62. package/preview.ts +13 -0
  63. package/rendering-context.ts +16 -0
  64. package/size-event.ts +14 -0
  65. package/tsconfig.json +16 -21
  66. package/types/asset.d.ts +15 -3
@@ -0,0 +1,41 @@
1
+ import type { Component, ComponentMap } from '@teambit/component';
2
+ import type { Environment, ExecutionContext } from '@teambit/envs';
3
+ import type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
4
+
5
+ export interface PreviewDefinition {
6
+ /**
7
+ * extension preview prefix
8
+ */
9
+ prefix: string;
10
+
11
+ /**
12
+ * which other extension modules to include in the preview context.
13
+ */
14
+ include?: string[];
15
+
16
+ /**
17
+ * path of the default template to be executed.
18
+ */
19
+ renderTemplatePath: (context: ExecutionContext) => Promise<string | undefined>;
20
+
21
+ /**
22
+ * get the template by env.
23
+ * TODO: refactor `renderTemplatePath` to accept only an env and remove this method.
24
+ */
25
+ renderTemplatePathByEnv: (env: Environment) => Promise<string | undefined>;
26
+
27
+ /**
28
+ * get all files to require in the preview runtime.
29
+ */
30
+ getModuleMap(components: Component[]): Promise<ComponentMap<AbstractVinyl[]>>;
31
+
32
+ /**
33
+ * Whether to include the peers chunk in the output html
34
+ */
35
+ includePeers?: boolean;
36
+
37
+ /**
38
+ * Get metadata for the preview
39
+ */
40
+ getMetadata?: (component: Component) => Promise<unknown>;
41
+ }
package/preview-env.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { Bundler, BundlerContext, DevServer, DevServerContext } from '@teambit/bundler';
2
+ import { AsyncEnvHandler, EnvHandler } from '@teambit/envs';
3
+
4
+ /**
5
+ * interface for implementing component previews
6
+ * using bit's development environments.
7
+ */
8
+ export interface PreviewEnv {
9
+ preview(): EnvHandler<Preview>;
10
+ }
11
+
12
+ export type Preview = {
13
+ /**
14
+ * return an instance of a mounter.
15
+ */
16
+ getMounter: () => string;
17
+
18
+ /**
19
+ * return a path to a docs template.
20
+ */
21
+ getDocsTemplate: () => string;
22
+
23
+ /**
24
+ * return a dev server instance to use for previews.
25
+ */
26
+ getDevServer: (context: DevServerContext) => EnvHandler<DevServer> | AsyncEnvHandler<DevServer>;
27
+
28
+ /**
29
+ * return an instance for a preview bundler.
30
+ */
31
+ getBundler: (context: BundlerContext) => EnvHandler<Bundler> | AsyncEnvHandler<Bundler>;
32
+
33
+ /**
34
+ * return the id of the dev server.
35
+ * used for deduplication of dev servers
36
+ */
37
+ getDevEnvId: () => string;
38
+
39
+ /**
40
+ * dependencies that will bundled as part of the env template and will configured as externals for the component bundle
41
+ * these dependencies will be available in the preview on the window.
42
+ * these dependencies will have only one instance on the page.
43
+ * for dev server these dependencies will be aliased
44
+ */
45
+ getHostDependencies: () => string[];
46
+ };
@@ -0,0 +1,36 @@
1
+ import { ComponentID } from '@teambit/component-id';
2
+ import { RenderingContext } from './rendering-context';
3
+ import { PreviewModule } from './types/preview-module';
4
+
5
+ export interface PreviewType {
6
+ /**
7
+ * preview name to register.
8
+ */
9
+ name: string;
10
+
11
+ /**
12
+ * preview render method.
13
+ */
14
+ render(
15
+ componentId: ComponentID,
16
+ envId: string,
17
+ linkedModules: PreviewModule<any>,
18
+ includedPreviews: string[],
19
+ renderingContext: RenderingContext
20
+ ): void;
21
+
22
+ /**
23
+ * determine if this will be the default preview to render.
24
+ */
25
+ default?: boolean;
26
+
27
+ /**
28
+ * which other extension modules to include in the preview context.
29
+ */
30
+ include?: string[];
31
+
32
+ /**
33
+ * select relevant information to show in preview context
34
+ */
35
+ selectPreviewModel?: (componentId: string, module: PreviewModule) => any;
36
+ }
@@ -0,0 +1,12 @@
1
+ import { Aspect, RuntimeDefinition } from '@teambit/harmony';
2
+
3
+ export const PreviewRuntime = new RuntimeDefinition('preview');
4
+
5
+ export const PreviewAspect = Aspect.create({
6
+ id: 'teambit.preview/preview',
7
+ dependencies: [],
8
+ defaultConfig: {},
9
+ declareRuntime: PreviewRuntime,
10
+ });
11
+
12
+ export default PreviewAspect;
@@ -0,0 +1,48 @@
1
+ import { Component } from '@teambit/component';
2
+ import gql from 'graphql-tag';
3
+
4
+ import { PreviewMain } from './preview.main.runtime';
5
+
6
+ export function previewSchema(previewExtension: PreviewMain) {
7
+ return {
8
+ typeDefs: gql`
9
+ type Preview {
10
+ # url: String!
11
+ """
12
+ Check if the component supports scaling
13
+ """
14
+ isScaling: Boolean
15
+ includesEnvTemplate: Boolean
16
+ legacyHeader: Boolean
17
+ skipIncludes: Boolean
18
+ }
19
+
20
+ extend type Component {
21
+ preview: Preview
22
+ }
23
+ `,
24
+ resolvers: {
25
+ Component: {
26
+ preview: (component: Component) => {
27
+ // return previewExtension.getPreview(component);
28
+ return { component };
29
+ },
30
+ },
31
+ Preview: {
32
+ includesEnvTemplate: ({ component }) => {
33
+ return previewExtension.isBundledWithEnv(component);
34
+ },
35
+ isScaling: ({ component }) => {
36
+ return previewExtension.doesScaling(component);
37
+ },
38
+ legacyHeader: ({ component }) => {
39
+ return previewExtension.isLegacyHeader(component);
40
+ },
41
+ skipIncludes: ({ component }) => {
42
+ // return true;
43
+ return previewExtension.isSupportSkipIncludes(component);
44
+ },
45
+ },
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,58 @@
1
+ import type { NextFunction, Request, Response, Route } from '@teambit/express';
2
+ import type { Component } from '@teambit/component';
3
+ import { noPreview, serverError } from '@teambit/ui-foundation.ui.pages.static-error';
4
+ import type { Logger } from '@teambit/logger';
5
+
6
+ import { PreviewMain } from './preview.main.runtime';
7
+ import { PreviewArtifact } from './preview-artifact';
8
+ import { getArtifactFileMiddleware } from './artifact-file-middleware';
9
+ import type { PreviewUrlParams } from './artifact-file-middleware';
10
+
11
+ export class PreviewRoute implements Route {
12
+ constructor(
13
+ /**
14
+ * preview extension.
15
+ */
16
+ private preview: PreviewMain,
17
+ private logger: Logger
18
+ ) {}
19
+
20
+ route = `/preview/:previewName?/:filePath(*)`;
21
+ method = 'get';
22
+
23
+ middlewares = [
24
+ async (req: Request<PreviewUrlParams>, res: Response, next: NextFunction) => {
25
+ try {
26
+ // @ts-ignore TODO: @guy please fix.
27
+ const component = req.component as Component | undefined;
28
+ if (!component) return res.status(404).send(noPreview());
29
+ const isLegacyPath = await this.preview.isBundledWithEnv(component);
30
+
31
+ let artifact: PreviewArtifact | undefined;
32
+ // TODO - prevent error `getVinylsAndImportIfMissing is not a function` #4680
33
+ try {
34
+ // Taking the env template (in this case we will take the component only bundle throw component-preview route)
35
+ // We use this route for the env template for backward compatibility - new scopes which contain components tagged with old versions of bit
36
+ if (!isLegacyPath) {
37
+ artifact = await this.preview.getEnvTemplateFromComponentEnv(component);
38
+ } else {
39
+ // If it's legacy (bundled together with the env template) take the preview bundle from the component directly
40
+ artifact = await this.preview.getPreview(component);
41
+ }
42
+ } catch (e: any) {
43
+ this.logger.error(`getEnvTemplateFromComponentEnv or getPreview has failed`, e);
44
+ return res.status(404).send(noPreview());
45
+ }
46
+ // @ts-ignore
47
+ req.artifact = artifact;
48
+ // @ts-ignore
49
+ req.isLegacyPath = isLegacyPath;
50
+ return next();
51
+ } catch (e: any) {
52
+ this.logger.error('failed getting preview', e);
53
+ return res.status(500).send(serverError());
54
+ }
55
+ },
56
+ getArtifactFileMiddleware(this.logger),
57
+ ];
58
+ }
@@ -0,0 +1,85 @@
1
+ import { resolve, join } from 'path';
2
+ import { ExecutionContext } from '@teambit/envs';
3
+ import { BuildContext, BuiltTaskResult, BuildTask, TaskLocation, CAPSULE_ARTIFACTS_DIR } from '@teambit/builder';
4
+ import { Bundler, BundlerContext, BundlerMain, Target } from '@teambit/bundler';
5
+ import { Compiler } from '@teambit/compiler';
6
+ import { ComponentMap } from '@teambit/component';
7
+ import { Capsule } from '@teambit/isolator';
8
+ import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
9
+ import { DependencyResolverMain } from '@teambit/dependency-resolver';
10
+ import { Logger } from '@teambit/logger';
11
+ import { PreviewMain } from './preview.main.runtime';
12
+
13
+ export const PREVIEW_TASK_NAME = 'GeneratePreview';
14
+ export class PreviewTask implements BuildTask {
15
+ constructor(
16
+ /**
17
+ * bundler extension.
18
+ */
19
+ private bundler: BundlerMain,
20
+
21
+ /**
22
+ * preview extension.
23
+ */
24
+ private preview: PreviewMain,
25
+
26
+ private dependencyResolver: DependencyResolverMain,
27
+ private logger: Logger
28
+ ) {}
29
+
30
+ aspectId = 'teambit.preview/preview';
31
+ name = PREVIEW_TASK_NAME;
32
+ description = 'Bundling components for preview';
33
+ location: TaskLocation = 'end';
34
+ // readonly dependencies = [CompilerAspect.id];
35
+
36
+ async execute(context: BuildContext): Promise<BuiltTaskResult> {
37
+ const defs = this.preview.getDefs();
38
+ const url = `/preview/${context.envRuntime.id}`;
39
+ const bundlingStrategy = this.preview.getBundlingStrategy(context.env);
40
+ const envPreviewConfig = this.preview.getEnvPreviewConfig(context.env);
41
+ const splitComponentBundle = envPreviewConfig.splitComponentBundle ?? false;
42
+ const computeTargetsContext = Object.assign(context, { splitComponentBundle });
43
+
44
+ const targets: Target[] = await bundlingStrategy.computeTargets(computeTargetsContext, defs, this);
45
+
46
+ const bundlerContext: BundlerContext = Object.assign(context, {
47
+ targets,
48
+ compress: bundlingStrategy.name !== 'env' && splitComponentBundle,
49
+ entry: [],
50
+ publicPath: this.getPreviewDirectory(context),
51
+ rootPath: url,
52
+ development: context.dev,
53
+ metaData: {
54
+ initiator: `${PREVIEW_TASK_NAME} task`,
55
+ envId: context.id,
56
+ },
57
+ });
58
+
59
+ const bundler: Bundler = await context.env.getBundler(bundlerContext);
60
+ const bundlerResults = await bundler.run();
61
+
62
+ const results = bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);
63
+ return results;
64
+ }
65
+
66
+ getLinkFileDirectory() {
67
+ return join(CAPSULE_ARTIFACTS_DIR, 'preview-links');
68
+ }
69
+
70
+ getPreviewDirectory(context: ExecutionContext) {
71
+ const outputPath = resolve(`${context.id}/public`);
72
+ return outputPath;
73
+ }
74
+
75
+ getPathsFromMap(
76
+ capsule: Capsule,
77
+ moduleMap: ComponentMap<AbstractVinyl[]>,
78
+ context: BuildContext
79
+ ): ComponentMap<string[]> {
80
+ const compiler: Compiler = context.env.getCompiler(context);
81
+ return moduleMap.map((files) => {
82
+ return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));
83
+ });
84
+ }
85
+ }
package/preview.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Bundler, BundlerContext, DevServer, DevServerContext } from '@teambit/bundler';
2
+
3
+ export interface Preview {
4
+ /**
5
+ * get a dev server instance of the.
6
+ */
7
+ getDevServer(context: DevServerContext): DevServer;
8
+
9
+ /**
10
+ * get bundler instance.
11
+ */
12
+ getBundler(context: BundlerContext): Bundler;
13
+ }
@@ -0,0 +1,16 @@
1
+ import { RenderingContextSlot } from './preview.preview.runtime';
2
+
3
+ export type RenderingContextOptions = { aspectsFilter?: string[] };
4
+ export type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };
5
+
6
+ export class RenderingContext {
7
+ constructor(private contexts: RenderingContextSlot, private options: RenderingContextOptions = {}) {}
8
+
9
+ /**
10
+ * obtain rendering context of a specific aspect.
11
+ */
12
+ get(aspectId: string) {
13
+ const contextFactory = this.contexts.get(aspectId);
14
+ return contextFactory?.(this.options);
15
+ }
16
+ }
package/size-event.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { BitBaseEvent } from '@teambit/pubsub';
2
+
3
+ export type SizeEventType = {
4
+ height: number;
5
+ width: number;
6
+ };
7
+
8
+ export class SizeEvent extends BitBaseEvent<SizeEventType> {
9
+ static readonly TYPE = 'preview-size';
10
+
11
+ constructor(sizeEvent: SizeEventType) {
12
+ super(SizeEvent.TYPE, '0.0.1', new Date().getTime(), sizeEvent);
13
+ }
14
+ }
package/tsconfig.json CHANGED
@@ -1,38 +1,33 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "lib": [
4
- "es2019",
5
- "DOM",
6
- "ES6",
7
- "DOM.Iterable",
8
- "ScriptHost"
4
+ "esnext",
5
+ "dom",
6
+ "dom.Iterable"
9
7
  ],
10
- "target": "es2015",
11
- "module": "CommonJS",
12
- "jsx": "react",
13
- "allowJs": true,
14
- "composite": true,
8
+ "target": "es2020",
9
+ "module": "es2020",
10
+ "jsx": "react-jsx",
15
11
  "declaration": true,
16
12
  "sourceMap": true,
17
- "skipLibCheck": true,
18
13
  "experimentalDecorators": true,
19
- "outDir": "dist",
14
+ "skipLibCheck": true,
20
15
  "moduleResolution": "node",
21
16
  "esModuleInterop": true,
22
- "rootDir": ".",
23
17
  "resolveJsonModule": true,
24
- "emitDeclarationOnly": true,
25
- "emitDecoratorMetadata": true,
26
- "allowSyntheticDefaultImports": true,
27
- "strictPropertyInitialization": false,
28
- "strict": true,
29
- "noImplicitAny": false,
30
- "preserveConstEnums": true
18
+ "allowJs": true,
19
+ "outDir": "dist",
20
+ "emitDeclarationOnly": true
31
21
  },
32
22
  "exclude": [
23
+ "artifacts",
24
+ "public",
33
25
  "dist",
26
+ "node_modules",
27
+ "package.json",
34
28
  "esm.mjs",
35
- "package.json"
29
+ "**/*.cjs",
30
+ "./dist"
36
31
  ],
37
32
  "include": [
38
33
  "**/*",
package/types/asset.d.ts CHANGED
@@ -5,12 +5,12 @@ declare module '*.png' {
5
5
  declare module '*.svg' {
6
6
  import type { FunctionComponent, SVGProps } from 'react';
7
7
 
8
- export const ReactComponent: FunctionComponent<SVGProps<SVGSVGElement> & { title?: string }>;
8
+ export const ReactComponent: FunctionComponent<
9
+ SVGProps<SVGSVGElement> & { title?: string }
10
+ >;
9
11
  const src: string;
10
12
  export default src;
11
13
  }
12
-
13
- // @TODO Gilad
14
14
  declare module '*.jpg' {
15
15
  const value: any;
16
16
  export = value;
@@ -27,3 +27,15 @@ declare module '*.bmp' {
27
27
  const value: any;
28
28
  export = value;
29
29
  }
30
+ declare module '*.otf' {
31
+ const value: any;
32
+ export = value;
33
+ }
34
+ declare module '*.woff' {
35
+ const value: any;
36
+ export = value;
37
+ }
38
+ declare module '*.woff2' {
39
+ const value: any;
40
+ export = value;
41
+ }