create-plasmic-app 0.0.36 → 0.0.39

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,7 +1,16 @@
1
+ import { promises as fs } from "fs";
1
2
  import path from "path";
3
+ import {
4
+ makeNextjsCatchallPage,
5
+ makeNextjsHostPage,
6
+ makeNextjsInitPage,
7
+ wrapAppRootForCodegen,
8
+ } from "../templates/nextjs";
2
9
  import { spawnOrFail } from "../utils/cmd-utils";
3
- import { deleteGlob, writeDefaultNextjsConfig } from "../utils/file-utils";
10
+ import { deleteGlob, overwriteIndex } from "../utils/file-utils";
11
+ import { ensure } from "../utils/lang-utils";
4
12
  import { installUpgrade } from "../utils/npm-utils";
13
+ import { installCodegenDeps, runCodegenSync } from "./common";
5
14
  import { CPAStrategy } from "./types";
6
15
 
7
16
  const nextjsStrategy: CPAStrategy = {
@@ -16,35 +25,88 @@ const nextjsStrategy: CPAStrategy = {
16
25
  // See where we `touch tsconfig.json` later on
17
26
  await spawnOrFail(`${createCommand}${templateArg}`);
18
27
  },
19
- configLoader: async (args) => {
20
- const { projectId, projectPath, projectApiToken, useTypescript } = args;
21
-
22
- const installResult = await installUpgrade("@plasmicapp/loader-nextjs", {
23
- workingDir: projectPath,
24
- });
25
-
26
- if (!installResult) {
27
- throw new Error("Failed to install the Plasmic dependency");
28
+ installDeps: async ({ scheme, projectPath }) => {
29
+ if (scheme === "loader") {
30
+ return await installUpgrade("@plasmicapp/loader-nextjs", {
31
+ workingDir: projectPath,
32
+ });
33
+ } else {
34
+ return await installCodegenDeps({ projectPath });
28
35
  }
36
+ },
37
+ overwriteConfig: async (args) => {
38
+ const { projectPath, scheme } = args;
29
39
 
30
- await writeDefaultNextjsConfig(
31
- projectPath,
32
- projectId,
33
- true,
34
- projectApiToken,
35
- useTypescript
36
- );
40
+ if (scheme === "codegen") {
41
+ const nextjsConfigFile = path.join(projectPath, "next.config.js");
42
+ await fs.writeFile(
43
+ nextjsConfigFile,
44
+ `
45
+ module.exports = {
46
+ eslint: {
47
+ ignoreDuringBuilds: true,
48
+ },
49
+ trailingSlash: true,
50
+ // Your NextJS config.
51
+ };
52
+ `
53
+ );
54
+ }
37
55
  },
38
- overwriteFiles: async (args) => {
56
+ generateFiles: async (args) => {
39
57
  // this is supposed to be called for loader case, so we are supposed to remove
40
58
  // all the files from pages/ since we have inserted a optional catch all
41
- const { projectPath } = args;
59
+ const {
60
+ projectPath,
61
+ scheme,
62
+ useTypescript,
63
+ projectId,
64
+ projectApiToken,
65
+ } = args;
42
66
 
67
+ // Always start fresh
43
68
  const pagesPath = path.join(projectPath, "pages");
44
- deleteGlob(path.join(pagesPath, `*.*`), [
45
- "[[...catchall]]",
46
- "plasmic-host",
47
- ]);
69
+ deleteGlob(path.join(pagesPath, `*.*`));
70
+
71
+ const hostPage = path.join(
72
+ pagesPath,
73
+ `plasmic-host.${useTypescript ? "tsx" : "jsx"}`
74
+ );
75
+ await fs.writeFile(hostPage, makeNextjsHostPage(scheme));
76
+
77
+ if (scheme === "loader") {
78
+ const initFile = path.join(
79
+ projectPath,
80
+ `plasmic-init.${useTypescript ? "ts" : "js"}`
81
+ );
82
+ await fs.writeFile(
83
+ initFile,
84
+ makeNextjsInitPage(projectId, ensure(projectApiToken))
85
+ );
86
+
87
+ // Write catch-all page for loader
88
+ const loaderPage = path.join(
89
+ pagesPath,
90
+ `[[...catchall]].${useTypescript ? "tsx" : "jsx"}`
91
+ );
92
+ await fs.writeFile(
93
+ loaderPage,
94
+ makeNextjsCatchallPage(useTypescript ? "ts" : "js")
95
+ );
96
+ } else {
97
+ await runCodegenSync({
98
+ projectId,
99
+ projectApiToken,
100
+ projectPath,
101
+ });
102
+
103
+ // Overwrite the index file
104
+ await overwriteIndex(projectPath, "nextjs", scheme);
105
+
106
+ // Overwrite the wrapper files to wrap PlasmicRootProvider
107
+ const appFilePath = path.join(projectPath, "pages", `_app.js`);
108
+ await fs.writeFile(appFilePath, wrapAppRootForCodegen());
109
+ }
48
110
  },
49
111
  build: async (args) => {
50
112
  const { npmRunCmd, projectPath } = args;
@@ -1,5 +1,7 @@
1
1
  import { spawnOrFail } from "../utils/cmd-utils";
2
+ import { overwriteIndex } from "../utils/file-utils";
2
3
  import { installUpgrade } from "../utils/npm-utils";
4
+ import { installCodegenDeps, runCodegenSync } from "./common";
3
5
  import { CPAStrategy } from "./types";
4
6
 
5
7
  const reactStrategy: CPAStrategy = {
@@ -15,19 +17,36 @@ const reactStrategy: CPAStrategy = {
15
17
  const templateArg = template ? ` --template ${template}` : "";
16
18
  await spawnOrFail(`${createCommand}${templateArg}`);
17
19
  },
18
- configLoader: async (args) => {
19
- // this is unreachable for now, but should we have it ??
20
- const { projectPath } = args;
21
-
22
- const installResult = await installUpgrade("@plasmicapp/loader-react", {
23
- workingDir: projectPath,
24
- });
25
-
26
- if (!installResult) {
27
- throw new Error("Failed to install the Plasmic dependency");
20
+ installDeps: async ({ projectPath, scheme }) => {
21
+ if (scheme === "loader") {
22
+ return await installUpgrade("@plasmicapp/loader-react", {
23
+ workingDir: projectPath,
24
+ });
25
+ } else {
26
+ return await installCodegenDeps({ projectPath });
28
27
  }
29
28
  },
30
- overwriteFiles: async () => {
29
+ overwriteConfig: async (args) => {
30
+ // No config to overwrite
31
+ },
32
+ generateFiles: async ({
33
+ scheme,
34
+ projectApiToken,
35
+ projectId,
36
+ projectPath,
37
+ }) => {
38
+ if (scheme === "loader") {
39
+ // Nothing to do
40
+ } else {
41
+ await runCodegenSync({
42
+ projectId,
43
+ projectApiToken,
44
+ projectPath,
45
+ });
46
+
47
+ // Overwrite the index file
48
+ await overwriteIndex(projectPath, "react", scheme);
49
+ }
31
50
  return;
32
51
  },
33
52
  build: async (args) => {
@@ -1,3 +1,5 @@
1
+ import { CodeScheme } from "..";
2
+
1
3
  interface CreateArgs {
2
4
  projectPath: string;
3
5
  template?: string;
@@ -7,13 +9,17 @@ interface CreateArgs {
7
9
  interface ConfigArgs {
8
10
  projectId: string;
9
11
  projectPath: string;
10
- projectApiToken: string;
11
12
  useTypescript: boolean;
13
+ scheme: CodeScheme;
14
+ projectApiToken: string | undefined;
12
15
  }
13
16
 
14
- interface OverwriteFilesArgs {
17
+ interface GenerateFilesArgs {
15
18
  projectPath: string;
16
19
  useTypescript: boolean;
20
+ scheme: CodeScheme;
21
+ projectId: string;
22
+ projectApiToken: string | undefined;
17
23
  }
18
24
 
19
25
  interface BuildArgs {
@@ -21,9 +27,15 @@ interface BuildArgs {
21
27
  npmRunCmd: string;
22
28
  }
23
29
 
30
+ interface InstallArgs {
31
+ scheme: CodeScheme;
32
+ projectPath: string;
33
+ }
34
+
24
35
  export interface CPAStrategy {
25
36
  create: (args: CreateArgs) => Promise<void>;
26
- configLoader: (args: ConfigArgs) => Promise<void>;
27
- overwriteFiles: (args: OverwriteFilesArgs) => Promise<void>;
37
+ installDeps: (args: InstallArgs) => Promise<boolean>;
38
+ overwriteConfig: (args: ConfigArgs) => Promise<void>;
39
+ generateFiles: (args: GenerateFilesArgs) => Promise<void>;
28
40
  build: (args: BuildArgs) => Promise<void>;
29
41
  }
@@ -1,3 +1,4 @@
1
+ import { CodeScheme } from "..";
1
2
  import { ifTs } from "../utils/file-utils";
2
3
 
3
4
  export const makeGatsbyDefaultPage = (format: "ts" | "js"): string => {
@@ -89,16 +90,16 @@ export const GATSBY_PLUGIN_CONFIG = (
89
90
  },
90
91
  `;
91
92
 
92
- export const makeGatsbyHostPage = (format: "ts" | "js"): string => {
93
- const ts = format === "ts";
94
- return `
93
+ export const makeGatsbyHostPage = (opts: {
94
+ useTypescript: boolean;
95
+ scheme: CodeScheme;
96
+ }): string => {
97
+ const { useTypescript, scheme } = opts;
98
+ if (scheme === "loader") {
99
+ return `
95
100
  import * as React from "react"
96
101
  import {
97
- PlasmicCanvasHost,${ifTs(
98
- ts,
99
- `
100
- InitOptions,`
101
- )}
102
+ PlasmicCanvasHost${ifTs(useTypescript, `, InitOptions`)}
102
103
  } from "@plasmicapp/loader-gatsby"
103
104
  import { graphql } from "gatsby"
104
105
  import { initPlasmicLoaderWithRegistrations } from "../plasmic-init"
@@ -110,7 +111,7 @@ export const query = graphql\`
110
111
  \`
111
112
 
112
113
  ${ifTs(
113
- ts,
114
+ useTypescript,
114
115
  `interface HostProps {
115
116
  data: {
116
117
  plasmicOptions: InitOptions;
@@ -118,12 +119,33 @@ ${ifTs(
118
119
  }
119
120
  `
120
121
  )}
121
- export default function Host({ data }${ifTs(ts, ": HostProps")}) {
122
+ export default function Host({ data }${ifTs(useTypescript, ": HostProps")}) {
122
123
  const { plasmicOptions } = data
123
124
  initPlasmicLoaderWithRegistrations(plasmicOptions)
124
125
  return <PlasmicCanvasHost />
125
126
  }
126
- `.trim();
127
+ `.trim();
128
+ } else {
129
+ return `
130
+ import * as React from "react"
131
+ import { PlasmicCanvasHost, registerComponent } from "@plasmicapp/host";
132
+
133
+ // You can register any code components that you want to use here; see
134
+ // https://docs.plasmic.app/learn/code-components-ref/
135
+ // And configure your Plasmic project to use the host url pointing at
136
+ // the /plasmic-host page of your nextjs app (for example,
137
+ // http://localhost:3000/plasmic-host). See
138
+ // https://docs.plasmic.app/learn/app-hosting/#set-a-plasmic-project-to-use-your-app-host
139
+
140
+ // registerComponent(...)
141
+
142
+ export default function PlasmicHost() {
143
+ return (
144
+ <PlasmicCanvasHost />
145
+ );
146
+ }
147
+ `;
148
+ }
127
149
  };
128
150
 
129
151
  export const GATSBY_SSR_CONFIG = `
@@ -145,6 +167,27 @@ const HeadComponents = [
145
167
  key="plasmic-preamble"
146
168
  src="https://static1.plasmic.app/preamble.js"
147
169
  />,
170
+ <script
171
+ key="plasmic-hmr"
172
+ type="text/javascript"
173
+ dangerouslySetInnerHTML={{
174
+ __html: \`
175
+ if (typeof window !== "undefined" && /\\\\/plasmic-host\\\\/?$/.test(window.location.pathname)) {
176
+ const RealEventSource = window.EventSource;
177
+ window.EventSource = function(url, config) {
178
+ if (/[^a-zA-Z]hmr($|[^a-zA-Z])/.test(url)) {
179
+ console.warn("Plasmic: disabled EventSource request for", url);
180
+ return {
181
+ onerror() {}, onmessage() {}, onopen() {}, close() {}
182
+ };
183
+ } else {
184
+ return new RealEventSource(url, config);
185
+ }
186
+ }
187
+ }
188
+ \`,
189
+ }}
190
+ />
148
191
  ]
149
192
 
150
193
  const isProduction = process.env.NODE_ENV === "production"
@@ -191,3 +234,18 @@ export function initPlasmicLoaderWithRegistrations(plasmicOptions${ifTs(
191
234
  }
192
235
  `.trim();
193
236
  };
237
+
238
+ export function wrapAppRootForCodegen() {
239
+ return `
240
+ import React from "react";
241
+ import { PlasmicRootProvider } from "@plasmicapp/react-web";
242
+
243
+ export const wrapRootElement = ({ element }) => {
244
+ return (
245
+ <PlasmicRootProvider>
246
+ {element}
247
+ </PlasmicRootProvider>
248
+ );
249
+ }
250
+ `;
251
+ }
@@ -1,3 +1,4 @@
1
+ import { CodeScheme } from "..";
1
2
  import { ifTs } from "../utils/file-utils";
2
3
 
3
4
  export const makeNextjsInitPage = (
@@ -103,14 +104,19 @@ export const getStaticPaths${ifTs(ts, `: GetStaticPaths`)} = async () => {
103
104
  `.trim();
104
105
  }
105
106
 
106
- export function makeNextjsHostPage(): string {
107
- return `
107
+ export function makeNextjsHostPage(scheme: CodeScheme): string {
108
+ const commonImports = `
108
109
  import * as React from 'react';
109
- import { PlasmicCanvasHost } from '@plasmicapp/loader-nextjs';
110
110
  import Script from 'next/script';
111
+ `.trim();
112
+
113
+ if (scheme === "loader") {
114
+ return `
115
+ ${commonImports}
116
+ import { PlasmicCanvasHost } from '@plasmicapp/loader-nextjs';
111
117
  import { PLASMIC } from '../plasmic-init';
112
118
 
113
- export default function Host() {
119
+ export default function PlasmicHost() {
114
120
  return PLASMIC && (
115
121
  <div>
116
122
  <Script
@@ -121,5 +127,49 @@ export default function Host() {
121
127
  </div>
122
128
  );
123
129
  }
124
- `.trim();
130
+ `;
131
+ } else {
132
+ return `
133
+ ${commonImports}
134
+ import { PlasmicCanvasHost, registerComponent } from '@plasmicapp/host';
135
+
136
+ // You can register any code components that you want to use here; see
137
+ // https://docs.plasmic.app/learn/code-components-ref/
138
+ // And configure your Plasmic project to use the host url pointing at
139
+ // the /plasmic-host page of your nextjs app (for example,
140
+ // http://localhost:3000/plasmic-host). See
141
+ // https://docs.plasmic.app/learn/app-hosting/#set-a-plasmic-project-to-use-your-app-host
142
+
143
+ // registerComponent(...)
144
+
145
+ export default function PlasmicHost() {
146
+ return (
147
+ <div>
148
+ <Script
149
+ src="https://static1.plasmic.app/preamble.js"
150
+ strategy="beforeInteractive"
151
+ />
152
+ <PlasmicCanvasHost />
153
+ </div>
154
+ );
155
+ }
156
+ `;
157
+ }
158
+ }
159
+
160
+ export function wrapAppRootForCodegen() {
161
+ return `
162
+ import '../styles/globals.css'
163
+ import { PlasmicRootProvider } from "@plasmicapp/react-web";
164
+
165
+ function MyApp({ Component, pageProps }) {
166
+ return (
167
+ <PlasmicRootProvider>
168
+ <Component {...pageProps} />
169
+ </PlasmicRootProvider>
170
+ );
171
+ }
172
+
173
+ export default MyApp
174
+ `;
125
175
  }
@@ -4,11 +4,6 @@ import L from "lodash";
4
4
  import * as path from "upath";
5
5
  import { PlatformType } from "../lib";
6
6
  import { GATSBY_404 } from "../templates/gatsby";
7
- import {
8
- makeNextjsCatchallPage,
9
- makeNextjsHostPage,
10
- makeNextjsInitPage,
11
- } from "../templates/nextjs";
12
7
  import { README } from "../templates/readme";
13
8
  import { WELCOME_PAGE } from "../templates/welcomePage";
14
9
  import { ensure, ensureString } from "./lang-utils";
@@ -45,67 +40,6 @@ export function stripExtension(
45
40
  return filename.substring(0, filename.lastIndexOf(ext));
46
41
  }
47
42
 
48
- /**
49
- * create-next-app doesn't create next.config.js,
50
- * so it's safe to just write the file
51
- * @param absPath
52
- * @param projectId
53
- * @returns
54
- */
55
- export async function writeDefaultNextjsConfig(
56
- projectDir: string,
57
- projectId: string,
58
- loader: boolean,
59
- projectApiToken?: string,
60
- useTypescript?: boolean
61
- ): Promise<void> {
62
- const nextjsConfigFile = path.join(projectDir, "next.config.js");
63
-
64
- if (!loader) {
65
- await fs.writeFile(
66
- nextjsConfigFile,
67
- `
68
- module.exports = {
69
- eslint: {
70
- ignoreDuringBuilds: true,
71
- },
72
- trailingSlash: true,
73
- // Your NextJS config.
74
- };
75
- `
76
- );
77
- return;
78
- }
79
-
80
- if (loader && projectApiToken) {
81
- const initFile = path.join(
82
- projectDir,
83
- `plasmic-init.${useTypescript ? "ts" : "js"}`
84
- );
85
- await fs.writeFile(
86
- initFile,
87
- makeNextjsInitPage(projectId, projectApiToken)
88
- );
89
-
90
- const pagesFolder = path.join(projectDir, "pages");
91
- const loaderPage = path.join(
92
- pagesFolder,
93
- `[[...catchall]].${useTypescript ? "tsx" : "jsx"}`
94
- );
95
- await fs.writeFile(
96
- loaderPage,
97
- makeNextjsCatchallPage(useTypescript ? "ts" : "js")
98
- );
99
-
100
- const hostPage = path.join(
101
- pagesFolder,
102
- `plasmic-host.${useTypescript ? "tsx" : "jsx"}`
103
- );
104
-
105
- await fs.writeFile(hostPage, makeNextjsHostPage());
106
- }
107
- }
108
-
109
43
  export async function writePlasmicLoaderJson(
110
44
  projectDir: string,
111
45
  projectId: string,
@@ -336,55 +270,6 @@ export async function ensureTsconfig(projectPath: string): Promise<void> {
336
270
  }
337
271
  }
338
272
 
339
- export async function wrapAppRoot(
340
- projectPath: string,
341
- platform: string,
342
- scheme: string
343
- ): Promise<void> {
344
- // with create-plasmic-app v2, isLoader=false
345
- const isLoader = scheme === "loader";
346
- const importPkg = isLoader ? `@plasmicapp/loader` : "@plasmicapp/react-web";
347
- if (platform === "nextjs") {
348
- const appFilePath = path.join(projectPath, "pages", `_app.js`);
349
- await fs.writeFile(
350
- appFilePath,
351
- `
352
- import '../styles/globals.css'
353
- import { PlasmicRootProvider } from "${importPkg}"
354
-
355
- function MyApp({ Component, pageProps }) {
356
- return (
357
- <PlasmicRootProvider>
358
- <Component {...pageProps} />
359
- </PlasmicRootProvider>
360
- )
361
- }
362
-
363
- export default MyApp
364
- `.trim()
365
- );
366
- } else if (platform === "gatsby") {
367
- const wrapperContent = `
368
- import React from "react";
369
- import { PlasmicRootProvider } from "${importPkg}";
370
-
371
- export const wrapRootElement = ({ element }) => {
372
- return (
373
- <PlasmicRootProvider>
374
- {element}
375
- </PlasmicRootProvider>
376
- );
377
- }
378
- `.trim();
379
-
380
- const browserFilePath = path.join(projectPath, "gatsby-browser.js");
381
- await fs.writeFile(browserFilePath, wrapperContent);
382
-
383
- const ssrFilePath = path.join(projectPath, "gatsby-ssr.js");
384
- await fs.writeFile(ssrFilePath, wrapperContent);
385
- }
386
- }
387
-
388
273
  export function ifTs(ts: boolean, str: string) {
389
274
  return ts ? str : "";
390
275
  }