create-plasmic-app 0.0.144 → 0.0.145

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,25 +1,29 @@
1
- /**
2
- * @type {import('gatsby').GatsbyConfig}
3
- */
4
- module.exports = {
1
+ const path = require("path");
2
+
3
+ /** @type {import("gatsby").GatsbyConfig} */
4
+ const config = {
5
5
  siteMetadata: {
6
6
  siteUrl: `https://www.yourdomain.tld`,
7
7
  },
8
- plugins: [{
9
- resolve: "@plasmicapp/loader-gatsby",
10
- options: {
11
- projects: [
12
- {
13
- id: "47tFXWjN2C4NyHFGGpaYQ3",
14
- token: "7BRFratDxPLMGZHnd2grV5QP6mlHcZ1AK3BJSIeh7xzUlHgWh25XpgXvUaKAqHXFMXQQuzpADqboibF6nqNWQ",
8
+ graphqlTypegen: true,
9
+ plugins: [
10
+ {
11
+ resolve: "@plasmicapp/loader-gatsby",
12
+ options: {
13
+ projects: [
14
+ {
15
+ id: "47tFXWjN2C4NyHFGGpaYQ3",
16
+ token: "7BRFratDxPLMGZHnd2grV5QP6mlHcZ1AK3BJSIeh7xzUlHgWh25XpgXvUaKAqHXFMXQQuzpADqboibF6nqNWQ",
17
+ },
18
+ ], // An array of project ids.
19
+ preview: false,
20
+ defaultPlasmicPage: path.resolve("./src/templates/defaultPlasmicPage.jsx"),
15
21
  },
16
- ], // An array of project ids.
17
- preview: false,
18
- defaultPlasmicPage: require.resolve("./src/templates/defaultPlasmicPage.jsx"),
19
- },
20
- },
21
- {
22
- resolve: "gatsby-plugin-react-helmet",
23
- }
24
- ]
25
- }
22
+ },
23
+ {
24
+ resolve: "gatsby-plugin-react-helmet",
25
+ },
26
+ ],
27
+ };
28
+
29
+ module.exports = config;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Implement Gatsby's Node APIs in this file.
3
+ *
4
+ * See: https://www.gatsbyjs.com/docs/node-apis/
5
+ *
6
+ * `onCreatePage` runs `extractPlasmicQueryData` at build time so that the
7
+ * SSG'd HTML for each Plasmic page contains its actual rendered content,
8
+ * rather than the `<Suspense fallback>` ("Loading...") of unresolved data
9
+ * queries.
10
+ */
11
+ const React = require("react");
12
+ const {
13
+ extractPlasmicQueryData,
14
+ PlasmicComponent,
15
+ PlasmicRootProvider,
16
+ } = require("@plasmicapp/loader-gatsby");
17
+ const gatsbyConfig = require("./gatsby-config");
18
+ const { initPlasmicLoaderWithRegistrations } = require("./src/plasmic-init");
19
+
20
+ const plasmicLoaderOptions = gatsbyConfig.plugins.find(
21
+ (p) => p && p.resolve === "@plasmicapp/loader-gatsby"
22
+ ).options;
23
+ const PLASMIC = initPlasmicLoaderWithRegistrations(plasmicLoaderOptions);
24
+
25
+ exports.onCreatePage = async ({ page, actions }) => {
26
+ if (page.component !== plasmicLoaderOptions.defaultPlasmicPage) {
27
+ return;
28
+ }
29
+ if (page.context?.queryCache) {
30
+ return;
31
+ }
32
+
33
+ const componentData = await PLASMIC.maybeFetchComponentData(page.path);
34
+ if (!componentData) {
35
+ return;
36
+ }
37
+ const meta = componentData.entryCompMetas[0];
38
+
39
+ const queryCache = await extractPlasmicQueryData(
40
+ React.createElement(
41
+ PlasmicRootProvider,
42
+ {
43
+ loader: PLASMIC,
44
+ prefetchedData: componentData,
45
+ pageRoute: meta.path,
46
+ pageParams: meta.params,
47
+ pageQuery: {},
48
+ },
49
+ React.createElement(PlasmicComponent, { component: meta.displayName })
50
+ )
51
+ );
52
+
53
+ actions.deletePage(page);
54
+ actions.createPage({
55
+ ...page,
56
+ context: { ...page.context, queryCache },
57
+ });
58
+ };
@@ -1,8 +1,6 @@
1
- import {
2
- initPlasmicLoader,
3
- } from "@plasmicapp/loader-gatsby";
1
+ const { initPlasmicLoader } = require("@plasmicapp/loader-gatsby");
4
2
 
5
- export function initPlasmicLoaderWithRegistrations(plasmicOptions) {
3
+ function initPlasmicLoaderWithRegistrations(plasmicOptions) {
6
4
  const PLASMIC = initPlasmicLoader(plasmicOptions);
7
5
 
8
6
  // You can register any code components that you want to use here; see
@@ -16,3 +14,5 @@ export function initPlasmicLoaderWithRegistrations(plasmicOptions) {
16
14
 
17
15
  return PLASMIC;
18
16
  }
17
+
18
+ module.exports = { initPlasmicLoaderWithRegistrations };
@@ -15,7 +15,7 @@ export const query = graphql`
15
15
  `;
16
16
 
17
17
 
18
- const PlasmicGatsbyPage = ({ data, location }) => {
18
+ const PlasmicGatsbyPage = ({ data, location, pageContext }) => {
19
19
  const {
20
20
  plasmicComponents,
21
21
  plasmicOptions,
@@ -26,6 +26,7 @@ const PlasmicGatsbyPage = ({ data, location }) => {
26
26
  <PlasmicRootProvider
27
27
  loader={initPlasmicLoaderWithRegistrations(plasmicOptions)}
28
28
  prefetchedData={plasmicComponents}
29
+ prefetchedQueryData={pageContext.queryCache}
29
30
  pageRoute={pageMeta.path}
30
31
  pageParams={pageMeta.params}
31
32
  pageQuery={Object.fromEntries(new URLSearchParams(location.search))}
@@ -1,31 +1,29 @@
1
1
  import path from "path";
2
- import type { GatsbyConfig } from "gatsby"
2
+ import type { GatsbyConfig } from "gatsby";
3
3
 
4
4
  const config: GatsbyConfig = {
5
5
  siteMetadata: {
6
6
  siteUrl: `https://www.yourdomain.tld`,
7
7
  },
8
- // More easily incorporate content into your pages through automatic TypeScript type generation and better GraphQL IntelliSense.
9
- // If you use VSCode you can also use the GraphQL plugin
10
- // Learn more at: https://gatsby.dev/graphql-typegen
11
8
  graphqlTypegen: true,
12
- plugins: [{
13
- resolve: "@plasmicapp/loader-gatsby",
14
- options: {
15
- projects: [
16
- {
17
- id: "47tFXWjN2C4NyHFGGpaYQ3",
18
- token: "7BRFratDxPLMGZHnd2grV5QP6mlHcZ1AK3BJSIeh7xzUlHgWh25XpgXvUaKAqHXFMXQQuzpADqboibF6nqNWQ",
9
+ plugins: [
10
+ {
11
+ resolve: "@plasmicapp/loader-gatsby",
12
+ options: {
13
+ projects: [
14
+ {
15
+ id: "47tFXWjN2C4NyHFGGpaYQ3",
16
+ token: "7BRFratDxPLMGZHnd2grV5QP6mlHcZ1AK3BJSIeh7xzUlHgWh25XpgXvUaKAqHXFMXQQuzpADqboibF6nqNWQ",
17
+ },
18
+ ], // An array of project ids.
19
+ preview: false,
20
+ defaultPlasmicPage: path.resolve("./src/templates/defaultPlasmicPage.tsx"),
19
21
  },
20
- ], // An array of project ids.
21
- preview: false,
22
- defaultPlasmicPage: path.resolve("./src/templates/defaultPlasmicPage.tsx"),
23
- },
24
- },
25
- {
26
- resolve: "gatsby-plugin-react-helmet",
27
- }
28
- ]
29
- }
22
+ },
23
+ {
24
+ resolve: "gatsby-plugin-react-helmet",
25
+ },
26
+ ],
27
+ };
30
28
 
31
- export default config
29
+ export default config;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Implement Gatsby's Node APIs in this file.
3
+ *
4
+ * See: https://www.gatsbyjs.com/docs/node-apis/
5
+ *
6
+ * `onCreatePage` runs `extractPlasmicQueryData` at build time so that the
7
+ * SSG'd HTML for each Plasmic page contains its actual rendered content,
8
+ * rather than the `<Suspense fallback>` ("Loading...") of unresolved data
9
+ * queries.
10
+ */
11
+ import type { CreatePageArgs } from "gatsby";
12
+ import * as React from "react";
13
+ import {
14
+ extractPlasmicQueryData,
15
+ PlasmicComponent,
16
+ PlasmicRootProvider,
17
+ } from "@plasmicapp/loader-gatsby";
18
+ import type { GatsbyPluginOptions } from "@plasmicapp/loader-gatsby";
19
+ import gatsbyConfig from "./gatsby-config";
20
+ import { initPlasmicLoaderWithRegistrations } from "./src/plasmic-init";
21
+ import type { PlasmicGatsbyPageProps } from "./src/templates/defaultPlasmicPage";
22
+
23
+ const plasmicLoaderOptions = gatsbyConfig.plugins.find(
24
+ (p) => p && p.resolve === "@plasmicapp/loader-gatsby"
25
+ )!.options as GatsbyPluginOptions;
26
+ const PLASMIC = initPlasmicLoaderWithRegistrations(plasmicLoaderOptions);
27
+
28
+ export const onCreatePage = async ({ page, actions }: CreatePageArgs<PlasmicGatsbyPageProps["pageContext"]>) => {
29
+ if (page.component !== plasmicLoaderOptions.defaultPlasmicPage) {
30
+ return;
31
+ }
32
+ if (page.context?.queryCache) {
33
+ return;
34
+ }
35
+
36
+ const componentData = await PLASMIC.maybeFetchComponentData(page.path);
37
+ if (!componentData) {
38
+ return;
39
+ }
40
+ const meta = componentData.entryCompMetas[0];
41
+
42
+ const queryCache = await extractPlasmicQueryData(
43
+ React.createElement(
44
+ PlasmicRootProvider,
45
+ {
46
+ loader: PLASMIC,
47
+ prefetchedData: componentData,
48
+ pageRoute: meta.path,
49
+ pageParams: meta.params,
50
+ pageQuery: {},
51
+ },
52
+ React.createElement(PlasmicComponent, { component: meta.displayName })
53
+ )
54
+ );
55
+
56
+ actions.deletePage(page);
57
+ actions.createPage({
58
+ ...page,
59
+ context: { ...page.context, queryCache },
60
+ });
61
+ };
@@ -16,14 +16,17 @@ export const query = graphql`
16
16
  }
17
17
  `;
18
18
 
19
- interface PlasmicGatsbyPageProps extends PageProps {
19
+ export interface PlasmicGatsbyPageProps extends PageProps {
20
20
  data: {
21
21
  plasmicOptions: InitOptions
22
22
  plasmicComponents: ComponentRenderData
23
23
  }
24
+ pageContext: {
25
+ queryCache?: Record<string, any>
26
+ }
24
27
  }
25
28
 
26
- const PlasmicGatsbyPage = ({ data, location }: PlasmicGatsbyPageProps) => {
29
+ const PlasmicGatsbyPage = ({ data, location, pageContext }: PlasmicGatsbyPageProps) => {
27
30
  const {
28
31
  plasmicComponents,
29
32
  plasmicOptions,
@@ -34,6 +37,7 @@ const PlasmicGatsbyPage = ({ data, location }: PlasmicGatsbyPageProps) => {
34
37
  <PlasmicRootProvider
35
38
  loader={initPlasmicLoaderWithRegistrations(plasmicOptions)}
36
39
  prefetchedData={plasmicComponents}
40
+ prefetchedQueryData={pageContext.queryCache}
37
41
  pageRoute={pageMeta.path}
38
42
  pageParams={pageMeta.params}
39
43
  pageQuery={Object.fromEntries(new URLSearchParams(location.search))}
@@ -1,27 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -31,13 +8,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
9
  });
33
10
  };
34
- var __asyncValues = (this && this.__asyncValues) || function (o) {
35
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
36
- var m = o[Symbol.asyncIterator], i;
37
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
38
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
39
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
40
- };
41
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
42
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
43
13
  };
@@ -46,7 +16,6 @@ exports.gatsbyStrategy = exports.GATSBY_TEMPLATES = void 0;
46
16
  const fs_1 = require("fs");
47
17
  const lodash_1 = __importDefault(require("lodash"));
48
18
  const path_1 = __importDefault(require("path"));
49
- const readline = __importStar(require("readline"));
50
19
  const cmd_utils_1 = require("../utils/cmd-utils");
51
20
  const codegen_1 = require("../utils/codegen");
52
21
  const file_utils_1 = require("../utils/file-utils");
@@ -95,7 +64,6 @@ exports.gatsbyStrategy = {
95
64
  }
96
65
  }),
97
66
  overwriteConfig: (args) => __awaiter(void 0, void 0, void 0, function* () {
98
- var _a, e_1, _b, _c;
99
67
  const { projectId, projectPath, projectApiToken, jsOrTs, scheme } = args;
100
68
  const packageName = path_1.default.basename(projectPath);
101
69
  // Update package.json: adding name and description, removing license and author
@@ -108,40 +76,8 @@ exports.gatsbyStrategy = {
108
76
  delete packageJsonObject.author;
109
77
  yield fs_1.promises.writeFile(packageJsonPath, JSON.stringify(packageJsonObject, null, 2));
110
78
  if (scheme === "loader") {
111
- // create-gatsby will create a default gatsby-config that we need to modify
112
79
  const gatsbyConfigFile = path_1.default.join(projectPath, `gatsby-config.${jsOrTs}`);
113
- const rl = readline.createInterface({
114
- input: (0, fs_1.createReadStream)(gatsbyConfigFile),
115
- crlfDelay: Infinity,
116
- });
117
- // Typescript doesn't accept require.resolve
118
- // https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/#requireresolve
119
- let result = (0, file_utils_1.ifTs)(jsOrTs, `import path from "path";\n`);
120
- const pluginConfig = (0, template_1.GATSBY_PLUGIN_CONFIG)(projectId, (0, lang_utils_1.ensure)(projectApiToken, "Missing projectApiToken"), jsOrTs);
121
- try {
122
- for (var _d = true, rl_1 = __asyncValues(rl), rl_1_1; rl_1_1 = yield rl_1.next(), _a = rl_1_1.done, !_a; _d = true) {
123
- _c = rl_1_1.value;
124
- _d = false;
125
- const line = _c;
126
- if (line.includes("plugins: []")) {
127
- result += " plugins: [" + pluginConfig + "]\n";
128
- }
129
- else if (line.includes("plugins: [")) {
130
- result += line + pluginConfig + "\n";
131
- }
132
- else {
133
- result += line + "\n";
134
- }
135
- }
136
- }
137
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
138
- finally {
139
- try {
140
- if (!_d && !_a && (_b = rl_1.return)) yield _b.call(rl_1);
141
- }
142
- finally { if (e_1) throw e_1.error; }
143
- }
144
- yield fs_1.promises.writeFile(gatsbyConfigFile, result);
80
+ yield fs_1.promises.writeFile(gatsbyConfigFile, (0, template_1.makeGatsbyConfig)(projectId, (0, lang_utils_1.ensure)(projectApiToken, "Missing projectApiToken"), jsOrTs));
145
81
  }
146
82
  }),
147
83
  generateFiles: (args) => __awaiter(void 0, void 0, void 0, function* () {
@@ -156,8 +92,9 @@ exports.gatsbyStrategy = {
156
92
  jsOrTs,
157
93
  scheme,
158
94
  }));
159
- // Start with an empty gatsby-node
160
- yield fs_1.promises.writeFile(path_1.default.join(projectPath, `gatsby-node.${jsOrTs}`), "");
95
+ // gatsby-node implements onCreatePage to prefetch query data for SSG.
96
+ // For codegen scheme, leave it empty.
97
+ yield fs_1.promises.writeFile(path_1.default.join(projectPath, `gatsby-node.${jsOrTs}`), scheme === "loader" ? (0, template_1.makeGatsbyNode)(jsOrTs) : "");
161
98
  // Updates `gatsby-ssr` to include script tag for preamble
162
99
  yield fs_1.promises.writeFile(path_1.default.join(projectPath, `gatsby-ssr.${jsOrTs}x`), template_1.GATSBY_SSR_CONFIG);
163
100
  if (scheme === "loader") {
@@ -1,7 +1,8 @@
1
1
  import { JsOrTs, SchemeType } from "../utils/types";
2
2
  export declare function makeGatsbyDefaultPage(jsOrTs: JsOrTs): string;
3
3
  export declare const GATSBY_404 = "const NotFound = () => {\n return \"Not Found\";\n};\nexport default NotFound;\n";
4
- export declare function GATSBY_PLUGIN_CONFIG(projectId: string, projectApiToken: string, jsOrTs: JsOrTs): string;
4
+ export declare function makeGatsbyConfig(projectId: string, projectApiToken: string, jsOrTs: JsOrTs): string;
5
+ export declare function makeGatsbyNode(jsOrTs: JsOrTs): string;
5
6
  export declare function makeGatsbyHostPage(opts: {
6
7
  jsOrTs: JsOrTs;
7
8
  scheme: SchemeType;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.wrapAppRootForCodegen = exports.makeGatsbyPlasmicInit = exports.GATSBY_SSR_CONFIG = exports.makeGatsbyHostPage = exports.GATSBY_PLUGIN_CONFIG = exports.GATSBY_404 = exports.makeGatsbyDefaultPage = void 0;
3
+ exports.wrapAppRootForCodegen = exports.makeGatsbyPlasmicInit = exports.GATSBY_SSR_CONFIG = exports.makeGatsbyHostPage = exports.makeGatsbyNode = exports.makeGatsbyConfig = exports.GATSBY_404 = exports.makeGatsbyDefaultPage = void 0;
4
4
  const file_utils_1 = require("../utils/file-utils");
5
5
  function makeGatsbyDefaultPage(jsOrTs) {
6
6
  return `import React from "react";
@@ -21,14 +21,17 @@ export const query = graphql\`
21
21
  }
22
22
  \`;
23
23
 
24
- ${(0, file_utils_1.ifTs)(jsOrTs, `interface PlasmicGatsbyPageProps extends PageProps {
24
+ ${(0, file_utils_1.ifTs)(jsOrTs, `export interface PlasmicGatsbyPageProps extends PageProps {
25
25
  data: {
26
26
  plasmicOptions: InitOptions
27
27
  plasmicComponents: ComponentRenderData
28
28
  }
29
+ pageContext: {
30
+ queryCache?: Record<string, any>
31
+ }
29
32
  }
30
33
  `)}
31
- const PlasmicGatsbyPage = ({ data, location }${(0, file_utils_1.ifTs)(jsOrTs, ": PlasmicGatsbyPageProps")}) => {
34
+ const PlasmicGatsbyPage = ({ data, location, pageContext }${(0, file_utils_1.ifTs)(jsOrTs, ": PlasmicGatsbyPageProps")}) => {
32
35
  const {
33
36
  plasmicComponents,
34
37
  plasmicOptions,
@@ -39,6 +42,7 @@ const PlasmicGatsbyPage = ({ data, location }${(0, file_utils_1.ifTs)(jsOrTs, ":
39
42
  <PlasmicRootProvider
40
43
  loader={initPlasmicLoaderWithRegistrations(plasmicOptions)}
41
44
  prefetchedData={plasmicComponents}
45
+ prefetchedQueryData={pageContext.queryCache}
42
46
  pageRoute={pageMeta.path}
43
47
  pageParams={pageMeta.params}
44
48
  pageQuery={Object.fromEntries(new URLSearchParams(location.search))}
@@ -64,26 +68,115 @@ exports.GATSBY_404 = `const NotFound = () => {
64
68
  };
65
69
  export default NotFound;
66
70
  `;
67
- function GATSBY_PLUGIN_CONFIG(projectId, projectApiToken, jsOrTs) {
68
- return `{
69
- resolve: "@plasmicapp/loader-gatsby",
70
- options: {
71
- projects: [
72
- {
73
- id: "${projectId}",
74
- token: "${projectApiToken}",
75
- },
76
- ], // An array of project ids.
77
- preview: false,
78
- defaultPlasmicPage: ${jsOrTs === "ts" ? "path" : "require"}.resolve("./src/templates/defaultPlasmicPage.${jsOrTs}x"),
71
+ function makeGatsbyConfig(projectId, projectApiToken, jsOrTs) {
72
+ return `${jsOrTs === "ts"
73
+ ? `import path from "path";
74
+ import type { GatsbyConfig } from "gatsby";`
75
+ : `const path = require("path");`}
76
+
77
+ ${jsOrTs === "ts" ? `` : `/** @type {import("gatsby").GatsbyConfig} */\n`}const config${(0, file_utils_1.ifTs)(jsOrTs, `: GatsbyConfig`)} = {
78
+ siteMetadata: {
79
+ siteUrl: \`https://www.yourdomain.tld\`,
79
80
  },
80
- },
81
- {
82
- resolve: "gatsby-plugin-react-helmet",
81
+ graphqlTypegen: true,
82
+ plugins: [
83
+ {
84
+ resolve: "@plasmicapp/loader-gatsby",
85
+ options: {
86
+ projects: [
87
+ {
88
+ id: "${projectId}",
89
+ token: "${projectApiToken}",
90
+ },
91
+ ], // An array of project ids.
92
+ preview: false,
93
+ defaultPlasmicPage: path.resolve("./src/templates/defaultPlasmicPage.${jsOrTs}x"),
94
+ },
95
+ },
96
+ {
97
+ resolve: "gatsby-plugin-react-helmet",
98
+ },
99
+ ],
100
+ };
101
+
102
+ ${jsOrTs === "ts" ? `export default config` : `module.exports = config`};
103
+ `;
83
104
  }
105
+ exports.makeGatsbyConfig = makeGatsbyConfig;
106
+ function makeGatsbyNode(jsOrTs) {
107
+ return `/**
108
+ * Implement Gatsby's Node APIs in this file.
109
+ *
110
+ * See: https://www.gatsbyjs.com/docs/node-apis/
111
+ *
112
+ * \`onCreatePage\` runs \`extractPlasmicQueryData\` at build time so that the
113
+ * SSG'd HTML for each Plasmic page contains its actual rendered content,
114
+ * rather than the \`<Suspense fallback>\` ("Loading...") of unresolved data
115
+ * queries.
116
+ */
117
+ ${jsOrTs === "ts"
118
+ ? `import type { CreatePageArgs } from "gatsby";
119
+ import * as React from "react";
120
+ import {
121
+ extractPlasmicQueryData,
122
+ PlasmicComponent,
123
+ PlasmicRootProvider,
124
+ } from "@plasmicapp/loader-gatsby";
125
+ import type { GatsbyPluginOptions } from "@plasmicapp/loader-gatsby";
126
+ import gatsbyConfig from "./gatsby-config";
127
+ import { initPlasmicLoaderWithRegistrations } from "./src/plasmic-init";
128
+ import type { PlasmicGatsbyPageProps } from "./src/templates/defaultPlasmicPage";`
129
+ : `const React = require("react");
130
+ const {
131
+ extractPlasmicQueryData,
132
+ PlasmicComponent,
133
+ PlasmicRootProvider,
134
+ } = require("@plasmicapp/loader-gatsby");
135
+ const gatsbyConfig = require("./gatsby-config");
136
+ const { initPlasmicLoaderWithRegistrations } = require("./src/plasmic-init");`}
137
+
138
+ const plasmicLoaderOptions = gatsbyConfig.plugins.find(
139
+ (p) => p && p.resolve === "@plasmicapp/loader-gatsby"
140
+ )${(0, file_utils_1.ifTs)(jsOrTs, `!`)}.options${(0, file_utils_1.ifTs)(jsOrTs, ` as GatsbyPluginOptions`)};
141
+ const PLASMIC = initPlasmicLoaderWithRegistrations(plasmicLoaderOptions);
142
+
143
+ ${jsOrTs === "ts" ? `export const onCreatePage =` : `exports.onCreatePage =`} async ({ page, actions }${(0, file_utils_1.ifTs)(jsOrTs, `: CreatePageArgs<PlasmicGatsbyPageProps["pageContext"]>`)}) => {
144
+ if (page.component !== plasmicLoaderOptions.defaultPlasmicPage) {
145
+ return;
146
+ }
147
+ if (page.context?.queryCache) {
148
+ return;
149
+ }
150
+
151
+ const componentData = await PLASMIC.maybeFetchComponentData(page.path);
152
+ if (!componentData) {
153
+ return;
154
+ }
155
+ const meta = componentData.entryCompMetas[0];
156
+
157
+ const queryCache = await extractPlasmicQueryData(
158
+ React.createElement(
159
+ PlasmicRootProvider,
160
+ {
161
+ loader: PLASMIC,
162
+ prefetchedData: componentData,
163
+ pageRoute: meta.path,
164
+ pageParams: meta.params,
165
+ pageQuery: {},
166
+ },
167
+ React.createElement(PlasmicComponent, { component: meta.displayName })
168
+ )
169
+ );
170
+
171
+ actions.deletePage(page);
172
+ actions.createPage({
173
+ ...page,
174
+ context: { ...page.context, queryCache },
175
+ });
176
+ };
84
177
  `;
85
178
  }
86
- exports.GATSBY_PLUGIN_CONFIG = GATSBY_PLUGIN_CONFIG;
179
+ exports.makeGatsbyNode = makeGatsbyNode;
87
180
  function makeGatsbyHostPage(opts) {
88
181
  const { jsOrTs, scheme } = opts;
89
182
  if (scheme === "loader") {
@@ -181,12 +274,14 @@ exports.onRenderBody = ({ pathname, setHeadComponents }) => {
181
274
  }
182
275
  `;
183
276
  function makeGatsbyPlasmicInit(jsOrTs) {
184
- return `import {
185
- initPlasmicLoader,${(0, file_utils_1.ifTs)(jsOrTs, `
186
- InitOptions,`)}
187
- } from "@plasmicapp/loader-gatsby";
277
+ return `${jsOrTs === "ts"
278
+ ? `import {
279
+ initPlasmicLoader,
280
+ InitOptions,
281
+ } from "@plasmicapp/loader-gatsby";`
282
+ : `const { initPlasmicLoader } = require("@plasmicapp/loader-gatsby");`}
188
283
 
189
- export function initPlasmicLoaderWithRegistrations(plasmicOptions${(0, file_utils_1.ifTs)(jsOrTs, ": InitOptions")}) {
284
+ ${(0, file_utils_1.ifTs)(jsOrTs, `export `)}function initPlasmicLoaderWithRegistrations(plasmicOptions${(0, file_utils_1.ifTs)(jsOrTs, `: InitOptions`)}) {
190
285
  const PLASMIC = initPlasmicLoader(plasmicOptions);
191
286
 
192
287
  // You can register any code components that you want to use here; see
@@ -200,7 +295,9 @@ export function initPlasmicLoaderWithRegistrations(plasmicOptions${(0, file_util
200
295
 
201
296
  return PLASMIC;
202
297
  }
203
- `;
298
+ ${jsOrTs === "ts"
299
+ ? ``
300
+ : `\nmodule.exports = { initPlasmicLoaderWithRegistrations };\n`}`;
204
301
  }
205
302
  exports.makeGatsbyPlasmicInit = makeGatsbyPlasmicInit;
206
303
  function wrapAppRootForCodegen() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-plasmic-app",
3
- "version": "0.0.144",
3
+ "version": "0.0.145",
4
4
  "description": "Create Plasmic-powered React apps",
5
5
  "main": "./dist/lib.js",
6
6
  "types": "./dist/lib.d.ts",
@@ -47,5 +47,5 @@
47
47
  "validate-npm-package-name": "^3.0.0",
48
48
  "yargs": "^16.2.0"
49
49
  },
50
- "gitHead": "94026327bd519c5a334ca974ef9d6d3d12855f25"
50
+ "gitHead": "a20807890e3caf3707c6bd214440d539ae53c01f"
51
51
  }
@@ -1,24 +1,23 @@
1
- import { createReadStream, existsSync, promises as fs } from "fs";
1
+ import { existsSync, promises as fs } from "fs";
2
2
  import L from "lodash";
3
3
  import path from "path";
4
- import * as readline from "readline";
5
4
  import { spawnOrFail } from "../utils/cmd-utils";
6
5
  import { installCodegenDeps, runCodegenSync } from "../utils/codegen";
7
6
  import {
8
7
  deleteGlob,
9
8
  generateWelcomePage,
10
9
  getPlasmicConfig,
11
- ifTs,
12
10
  } from "../utils/file-utils";
13
11
  import { ensure } from "../utils/lang-utils";
14
12
  import { installUpgrade } from "../utils/npm-utils";
15
13
  import { CPAStrategy } from "../utils/strategy";
16
14
  import {
17
15
  GATSBY_404,
18
- GATSBY_PLUGIN_CONFIG,
19
16
  GATSBY_SSR_CONFIG,
17
+ makeGatsbyConfig,
20
18
  makeGatsbyDefaultPage,
21
19
  makeGatsbyHostPage,
20
+ makeGatsbyNode,
22
21
  makeGatsbyPlasmicInit,
23
22
  wrapAppRootForCodegen,
24
23
  } from "./template";
@@ -89,33 +88,18 @@ export const gatsbyStrategy: CPAStrategy = {
89
88
  );
90
89
 
91
90
  if (scheme === "loader") {
92
- // create-gatsby will create a default gatsby-config that we need to modify
93
91
  const gatsbyConfigFile = path.join(
94
92
  projectPath,
95
93
  `gatsby-config.${jsOrTs}`
96
94
  );
97
- const rl = readline.createInterface({
98
- input: createReadStream(gatsbyConfigFile),
99
- crlfDelay: Infinity,
100
- });
101
- // Typescript doesn't accept require.resolve
102
- // https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/#requireresolve
103
- let result = ifTs(jsOrTs, `import path from "path";\n`);
104
- const pluginConfig = GATSBY_PLUGIN_CONFIG(
105
- projectId,
106
- ensure(projectApiToken, "Missing projectApiToken"),
107
- jsOrTs
95
+ await fs.writeFile(
96
+ gatsbyConfigFile,
97
+ makeGatsbyConfig(
98
+ projectId,
99
+ ensure(projectApiToken, "Missing projectApiToken"),
100
+ jsOrTs
101
+ )
108
102
  );
109
- for await (const line of rl) {
110
- if (line.includes("plugins: []")) {
111
- result += " plugins: [" + pluginConfig + "]\n";
112
- } else if (line.includes("plugins: [")) {
113
- result += line + pluginConfig + "\n";
114
- } else {
115
- result += line + "\n";
116
- }
117
- }
118
- await fs.writeFile(gatsbyConfigFile, result);
119
103
  }
120
104
  },
121
105
  generateFiles: async (args) => {
@@ -140,8 +124,12 @@ export const gatsbyStrategy: CPAStrategy = {
140
124
  })
141
125
  );
142
126
 
143
- // Start with an empty gatsby-node
144
- await fs.writeFile(path.join(projectPath, `gatsby-node.${jsOrTs}`), "");
127
+ // gatsby-node implements onCreatePage to prefetch query data for SSG.
128
+ // For codegen scheme, leave it empty.
129
+ await fs.writeFile(
130
+ path.join(projectPath, `gatsby-node.${jsOrTs}`),
131
+ scheme === "loader" ? makeGatsbyNode(jsOrTs) : ""
132
+ );
145
133
 
146
134
  // Updates `gatsby-ssr` to include script tag for preamble
147
135
  await fs.writeFile(
@@ -25,15 +25,18 @@ export const query = graphql\`
25
25
 
26
26
  ${ifTs(
27
27
  jsOrTs,
28
- `interface PlasmicGatsbyPageProps extends PageProps {
28
+ `export interface PlasmicGatsbyPageProps extends PageProps {
29
29
  data: {
30
30
  plasmicOptions: InitOptions
31
31
  plasmicComponents: ComponentRenderData
32
32
  }
33
+ pageContext: {
34
+ queryCache?: Record<string, any>
35
+ }
33
36
  }
34
37
  `
35
38
  )}
36
- const PlasmicGatsbyPage = ({ data, location }${ifTs(
39
+ const PlasmicGatsbyPage = ({ data, location, pageContext }${ifTs(
37
40
  jsOrTs,
38
41
  ": PlasmicGatsbyPageProps"
39
42
  )}) => {
@@ -47,6 +50,7 @@ const PlasmicGatsbyPage = ({ data, location }${ifTs(
47
50
  <PlasmicRootProvider
48
51
  loader={initPlasmicLoaderWithRegistrations(plasmicOptions)}
49
52
  prefetchedData={plasmicComponents}
53
+ prefetchedQueryData={pageContext.queryCache}
50
54
  pageRoute={pageMeta.path}
51
55
  pageParams={pageMeta.params}
52
56
  pageQuery={Object.fromEntries(new URLSearchParams(location.search))}
@@ -73,29 +77,127 @@ export const GATSBY_404 = `const NotFound = () => {
73
77
  export default NotFound;
74
78
  `;
75
79
 
76
- export function GATSBY_PLUGIN_CONFIG(
80
+ export function makeGatsbyConfig(
77
81
  projectId: string,
78
82
  projectApiToken: string,
79
83
  jsOrTs: JsOrTs
80
84
  ): string {
81
- return `{
82
- resolve: "@plasmicapp/loader-gatsby",
83
- options: {
84
- projects: [
85
- {
86
- id: "${projectId}",
87
- token: "${projectApiToken}",
88
- },
89
- ], // An array of project ids.
90
- preview: false,
91
- defaultPlasmicPage: ${
92
- jsOrTs === "ts" ? "path" : "require"
93
- }.resolve("./src/templates/defaultPlasmicPage.${jsOrTs}x"),
85
+ return `${
86
+ jsOrTs === "ts"
87
+ ? `import path from "path";
88
+ import type { GatsbyConfig } from "gatsby";`
89
+ : `const path = require("path");`
90
+ }
91
+
92
+ ${
93
+ jsOrTs === "ts" ? `` : `/** @type {import("gatsby").GatsbyConfig} */\n`
94
+ }const config${ifTs(jsOrTs, `: GatsbyConfig`)} = {
95
+ siteMetadata: {
96
+ siteUrl: \`https://www.yourdomain.tld\`,
94
97
  },
95
- },
96
- {
97
- resolve: "gatsby-plugin-react-helmet",
98
+ graphqlTypegen: true,
99
+ plugins: [
100
+ {
101
+ resolve: "@plasmicapp/loader-gatsby",
102
+ options: {
103
+ projects: [
104
+ {
105
+ id: "${projectId}",
106
+ token: "${projectApiToken}",
107
+ },
108
+ ], // An array of project ids.
109
+ preview: false,
110
+ defaultPlasmicPage: path.resolve("./src/templates/defaultPlasmicPage.${jsOrTs}x"),
111
+ },
112
+ },
113
+ {
114
+ resolve: "gatsby-plugin-react-helmet",
115
+ },
116
+ ],
117
+ };
118
+
119
+ ${jsOrTs === "ts" ? `export default config` : `module.exports = config`};
120
+ `;
98
121
  }
122
+
123
+ export function makeGatsbyNode(jsOrTs: JsOrTs): string {
124
+ return `/**
125
+ * Implement Gatsby's Node APIs in this file.
126
+ *
127
+ * See: https://www.gatsbyjs.com/docs/node-apis/
128
+ *
129
+ * \`onCreatePage\` runs \`extractPlasmicQueryData\` at build time so that the
130
+ * SSG'd HTML for each Plasmic page contains its actual rendered content,
131
+ * rather than the \`<Suspense fallback>\` ("Loading...") of unresolved data
132
+ * queries.
133
+ */
134
+ ${
135
+ jsOrTs === "ts"
136
+ ? `import type { CreatePageArgs } from "gatsby";
137
+ import * as React from "react";
138
+ import {
139
+ extractPlasmicQueryData,
140
+ PlasmicComponent,
141
+ PlasmicRootProvider,
142
+ } from "@plasmicapp/loader-gatsby";
143
+ import type { GatsbyPluginOptions } from "@plasmicapp/loader-gatsby";
144
+ import gatsbyConfig from "./gatsby-config";
145
+ import { initPlasmicLoaderWithRegistrations } from "./src/plasmic-init";
146
+ import type { PlasmicGatsbyPageProps } from "./src/templates/defaultPlasmicPage";`
147
+ : `const React = require("react");
148
+ const {
149
+ extractPlasmicQueryData,
150
+ PlasmicComponent,
151
+ PlasmicRootProvider,
152
+ } = require("@plasmicapp/loader-gatsby");
153
+ const gatsbyConfig = require("./gatsby-config");
154
+ const { initPlasmicLoaderWithRegistrations } = require("./src/plasmic-init");`
155
+ }
156
+
157
+ const plasmicLoaderOptions = gatsbyConfig.plugins.find(
158
+ (p) => p && p.resolve === "@plasmicapp/loader-gatsby"
159
+ )${ifTs(jsOrTs, `!`)}.options${ifTs(jsOrTs, ` as GatsbyPluginOptions`)};
160
+ const PLASMIC = initPlasmicLoaderWithRegistrations(plasmicLoaderOptions);
161
+
162
+ ${
163
+ jsOrTs === "ts" ? `export const onCreatePage =` : `exports.onCreatePage =`
164
+ } async ({ page, actions }${ifTs(
165
+ jsOrTs,
166
+ `: CreatePageArgs<PlasmicGatsbyPageProps["pageContext"]>`
167
+ )}) => {
168
+ if (page.component !== plasmicLoaderOptions.defaultPlasmicPage) {
169
+ return;
170
+ }
171
+ if (page.context?.queryCache) {
172
+ return;
173
+ }
174
+
175
+ const componentData = await PLASMIC.maybeFetchComponentData(page.path);
176
+ if (!componentData) {
177
+ return;
178
+ }
179
+ const meta = componentData.entryCompMetas[0];
180
+
181
+ const queryCache = await extractPlasmicQueryData(
182
+ React.createElement(
183
+ PlasmicRootProvider,
184
+ {
185
+ loader: PLASMIC,
186
+ prefetchedData: componentData,
187
+ pageRoute: meta.path,
188
+ pageParams: meta.params,
189
+ pageQuery: {},
190
+ },
191
+ React.createElement(PlasmicComponent, { component: meta.displayName })
192
+ )
193
+ );
194
+
195
+ actions.deletePage(page);
196
+ actions.createPage({
197
+ ...page,
198
+ context: { ...page.context, queryCache },
199
+ });
200
+ };
99
201
  `;
100
202
  }
101
203
 
@@ -202,17 +304,21 @@ exports.onRenderBody = ({ pathname, setHeadComponents }) => {
202
304
  `;
203
305
 
204
306
  export function makeGatsbyPlasmicInit(jsOrTs: JsOrTs): string {
205
- return `import {
206
- initPlasmicLoader,${ifTs(
207
- jsOrTs,
208
- `
209
- InitOptions,`
210
- )}
211
- } from "@plasmicapp/loader-gatsby";
307
+ return `${
308
+ jsOrTs === "ts"
309
+ ? `import {
310
+ initPlasmicLoader,
311
+ InitOptions,
312
+ } from "@plasmicapp/loader-gatsby";`
313
+ : `const { initPlasmicLoader } = require("@plasmicapp/loader-gatsby");`
314
+ }
212
315
 
213
- export function initPlasmicLoaderWithRegistrations(plasmicOptions${ifTs(
316
+ ${ifTs(
317
+ jsOrTs,
318
+ `export `
319
+ )}function initPlasmicLoaderWithRegistrations(plasmicOptions${ifTs(
214
320
  jsOrTs,
215
- ": InitOptions"
321
+ `: InitOptions`
216
322
  )}) {
217
323
  const PLASMIC = initPlasmicLoader(plasmicOptions);
218
324
 
@@ -227,7 +333,11 @@ export function initPlasmicLoaderWithRegistrations(plasmicOptions${ifTs(
227
333
 
228
334
  return PLASMIC;
229
335
  }
230
- `;
336
+ ${
337
+ jsOrTs === "ts"
338
+ ? ``
339
+ : `\nmodule.exports = { initPlasmicLoaderWithRegistrations };\n`
340
+ }`;
231
341
  }
232
342
 
233
343
  export function wrapAppRootForCodegen(): string {