@canva/cli 0.0.1-beta.1

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 (109) hide show
  1. package/LICENSE.md +48 -0
  2. package/README.md +206 -0
  3. package/cli.js +566 -0
  4. package/package.json +30 -0
  5. package/templates/base/backend/database/database.ts +42 -0
  6. package/templates/base/backend/routers/auth.ts +285 -0
  7. package/templates/base/declarations/declarations.d.ts +29 -0
  8. package/templates/base/eslint.config.mjs +309 -0
  9. package/templates/base/package.json +83 -0
  10. package/templates/base/scripts/ssl/ssl.ts +131 -0
  11. package/templates/base/scripts/start/app_runner.ts +164 -0
  12. package/templates/base/scripts/start/context.ts +165 -0
  13. package/templates/base/scripts/start/start.ts +35 -0
  14. package/templates/base/styles/components.css +38 -0
  15. package/templates/base/tsconfig.json +54 -0
  16. package/templates/base/utils/backend/base_backend/create.ts +104 -0
  17. package/templates/base/utils/backend/jwt_middleware/index.ts +1 -0
  18. package/templates/base/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  19. package/templates/base/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  20. package/templates/base/webpack.config.cjs +270 -0
  21. package/templates/common/.env.template +6 -0
  22. package/templates/common/.gitignore.template +9 -0
  23. package/templates/common/LICENSE.md +48 -0
  24. package/templates/common/README.md +250 -0
  25. package/templates/common/jest.config.mjs +8 -0
  26. package/templates/dam/backend/database/database.ts +42 -0
  27. package/templates/dam/backend/routers/auth.ts +285 -0
  28. package/templates/dam/backend/routers/dam.ts +86 -0
  29. package/templates/dam/backend/server.ts +65 -0
  30. package/templates/dam/declarations/declarations.d.ts +29 -0
  31. package/templates/dam/eslint.config.mjs +309 -0
  32. package/templates/dam/package.json +90 -0
  33. package/templates/dam/scripts/ssl/ssl.ts +131 -0
  34. package/templates/dam/scripts/start/app_runner.ts +164 -0
  35. package/templates/dam/scripts/start/context.ts +165 -0
  36. package/templates/dam/scripts/start/start.ts +35 -0
  37. package/templates/dam/src/adapter.ts +44 -0
  38. package/templates/dam/src/app.tsx +147 -0
  39. package/templates/dam/src/config.ts +95 -0
  40. package/templates/dam/src/index.css +10 -0
  41. package/templates/dam/src/index.tsx +22 -0
  42. package/templates/dam/tsconfig.json +54 -0
  43. package/templates/dam/utils/backend/base_backend/create.ts +104 -0
  44. package/templates/dam/utils/backend/jwt_middleware/index.ts +1 -0
  45. package/templates/dam/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  46. package/templates/dam/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  47. package/templates/dam/webpack.config.cjs +270 -0
  48. package/templates/gen_ai/README.md +27 -0
  49. package/templates/gen_ai/backend/database/database.ts +42 -0
  50. package/templates/gen_ai/backend/routers/auth.ts +285 -0
  51. package/templates/gen_ai/backend/routers/image.ts +234 -0
  52. package/templates/gen_ai/backend/server.ts +56 -0
  53. package/templates/gen_ai/declarations/declarations.d.ts +29 -0
  54. package/templates/gen_ai/eslint.config.mjs +309 -0
  55. package/templates/gen_ai/package.json +92 -0
  56. package/templates/gen_ai/scripts/ssl/ssl.ts +131 -0
  57. package/templates/gen_ai/scripts/start/app_runner.ts +164 -0
  58. package/templates/gen_ai/scripts/start/context.ts +165 -0
  59. package/templates/gen_ai/scripts/start/start.ts +35 -0
  60. package/templates/gen_ai/src/api/api.ts +228 -0
  61. package/templates/gen_ai/src/api/index.ts +1 -0
  62. package/templates/gen_ai/src/app.tsx +13 -0
  63. package/templates/gen_ai/src/components/app_error.tsx +18 -0
  64. package/templates/gen_ai/src/components/footer.messages.ts +53 -0
  65. package/templates/gen_ai/src/components/footer.tsx +157 -0
  66. package/templates/gen_ai/src/components/image_grid.tsx +96 -0
  67. package/templates/gen_ai/src/components/index.ts +8 -0
  68. package/templates/gen_ai/src/components/loading_results.tsx +169 -0
  69. package/templates/gen_ai/src/components/logged_in_status.tsx +44 -0
  70. package/templates/gen_ai/src/components/prompt_input.messages.ts +14 -0
  71. package/templates/gen_ai/src/components/prompt_input.tsx +149 -0
  72. package/templates/gen_ai/src/components/remaining_credits.tsx +75 -0
  73. package/templates/gen_ai/src/components/report_box.tsx +53 -0
  74. package/templates/gen_ai/src/config.ts +21 -0
  75. package/templates/gen_ai/src/context/app_context.tsx +174 -0
  76. package/templates/gen_ai/src/context/context.messages.ts +41 -0
  77. package/templates/gen_ai/src/context/index.ts +2 -0
  78. package/templates/gen_ai/src/context/use_app_context.ts +17 -0
  79. package/templates/gen_ai/src/index.tsx +31 -0
  80. package/templates/gen_ai/src/pages/error.tsx +41 -0
  81. package/templates/gen_ai/src/pages/generate.tsx +9 -0
  82. package/templates/gen_ai/src/pages/index.ts +3 -0
  83. package/templates/gen_ai/src/pages/results.tsx +31 -0
  84. package/templates/gen_ai/src/routes/index.ts +1 -0
  85. package/templates/gen_ai/src/routes/routes.tsx +26 -0
  86. package/templates/gen_ai/src/services/auth.tsx +31 -0
  87. package/templates/gen_ai/src/services/index.ts +1 -0
  88. package/templates/gen_ai/src/utils/index.ts +1 -0
  89. package/templates/gen_ai/src/utils/obscenity_filter.ts +33 -0
  90. package/templates/gen_ai/styles/components.css +38 -0
  91. package/templates/gen_ai/styles/utils.css +3 -0
  92. package/templates/gen_ai/tsconfig.json +54 -0
  93. package/templates/gen_ai/utils/backend/base_backend/create.ts +104 -0
  94. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +1 -0
  95. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  96. package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  97. package/templates/gen_ai/webpack.config.cjs +270 -0
  98. package/templates/hello_world/declarations/declarations.d.ts +29 -0
  99. package/templates/hello_world/eslint.config.mjs +309 -0
  100. package/templates/hello_world/package.json +73 -0
  101. package/templates/hello_world/scripts/ssl/ssl.ts +131 -0
  102. package/templates/hello_world/scripts/start/app_runner.ts +164 -0
  103. package/templates/hello_world/scripts/start/context.ts +165 -0
  104. package/templates/hello_world/scripts/start/start.ts +35 -0
  105. package/templates/hello_world/src/app.tsx +41 -0
  106. package/templates/hello_world/src/index.tsx +22 -0
  107. package/templates/hello_world/styles/components.css +38 -0
  108. package/templates/hello_world/tsconfig.json +54 -0
  109. package/templates/hello_world/webpack.config.cjs +270 -0
@@ -0,0 +1,270 @@
1
+ require("dotenv").config();
2
+ const path = require("path");
3
+ const TerserPlugin = require("terser-webpack-plugin");
4
+ const { DefinePlugin, optimize } = require("webpack");
5
+ const chalk = require("chalk");
6
+ const { transform } = require("@formatjs/ts-transformer");
7
+
8
+ /**
9
+ *
10
+ * @param {Object} [options]
11
+ * @param {string} [options.appEntry=./src/index.tsx]
12
+ * @param {string} [options.backendHost]
13
+ * @param {Object} [options.devConfig]
14
+ * @param {number} [options.devConfig.port]
15
+ * @param {boolean} [options.devConfig.enableHmr]
16
+ * @param {boolean} [options.devConfig.enableHttps]
17
+ * @param {string} [options.devConfig.appOrigin]
18
+ * @param {string} [options.devConfig.appId] - Deprecated in favour of appOrigin
19
+ * @param {string} [options.devConfig.certFile]
20
+ * @param {string} [options.devConfig.keyFile]
21
+ * @returns {Object}
22
+ */
23
+ function buildConfig({
24
+ devConfig,
25
+ appEntry = path.join(process.cwd(), "src", "index.tsx"),
26
+ backendHost = process.env.CANVA_BACKEND_HOST,
27
+ } = {}) {
28
+ const mode = devConfig ? "development" : "production";
29
+
30
+ if (!backendHost) {
31
+ console.error(
32
+ chalk.redBright.bold("BACKEND_HOST is undefined."),
33
+ `Refer to "Customizing the backend host" in the README.md for more information.`,
34
+ );
35
+ process.exit(-1);
36
+ } else if (backendHost.includes("localhost") && mode === "production") {
37
+ console.error(
38
+ chalk.redBright.bold(
39
+ "BACKEND_HOST should not be set to localhost for production builds!",
40
+ ),
41
+ `Refer to "Customizing the backend host" in the README.md for more information.`,
42
+ );
43
+ }
44
+
45
+ return {
46
+ mode,
47
+ context: path.resolve(process.cwd(), "./"),
48
+ entry: {
49
+ app: appEntry,
50
+ },
51
+ target: "web",
52
+ resolve: {
53
+ alias: {
54
+ assets: path.resolve(process.cwd(), "assets"),
55
+ utils: path.resolve(process.cwd(), "utils"),
56
+ styles: path.resolve(process.cwd(), "styles"),
57
+ src: path.resolve(process.cwd(), "src"),
58
+ },
59
+ extensions: [".ts", ".tsx", ".js", ".css", ".svg", ".woff", ".woff2"],
60
+ },
61
+ infrastructureLogging: {
62
+ level: "none",
63
+ },
64
+ module: {
65
+ rules: [
66
+ {
67
+ test: /\.tsx?$/,
68
+ exclude: /node_modules/,
69
+ use: [
70
+ {
71
+ loader: "ts-loader",
72
+ options: {
73
+ transpileOnly: true,
74
+ getCustomTransformers() {
75
+ return {
76
+ before: [
77
+ transform({
78
+ overrideIdFn: "[sha512:contenthash:base64:6]",
79
+ }),
80
+ ],
81
+ };
82
+ },
83
+ },
84
+ },
85
+ ],
86
+ },
87
+ {
88
+ test: /\.css$/,
89
+ exclude: /node_modules/,
90
+ use: [
91
+ "style-loader",
92
+ {
93
+ loader: "css-loader",
94
+ options: {
95
+ modules: true,
96
+ },
97
+ },
98
+ {
99
+ loader: "postcss-loader",
100
+ options: {
101
+ postcssOptions: {
102
+ plugins: [require("cssnano")({ preset: "default" })],
103
+ },
104
+ },
105
+ },
106
+ ],
107
+ },
108
+ {
109
+ test: /\.(png|jpg|jpeg)$/i,
110
+ type: "asset/inline",
111
+ },
112
+ {
113
+ test: /\.(woff|woff2)$/,
114
+ type: "asset/inline",
115
+ },
116
+ {
117
+ test: /\.svg$/,
118
+ oneOf: [
119
+ {
120
+ issuer: /\.[jt]sx?$/,
121
+ resourceQuery: /react/, // *.svg?react
122
+ use: ["@svgr/webpack", "url-loader"],
123
+ },
124
+ {
125
+ type: "asset/resource",
126
+ parser: {
127
+ dataUrlCondition: {
128
+ maxSize: 200,
129
+ },
130
+ },
131
+ },
132
+ ],
133
+ },
134
+ {
135
+ test: /\.css$/,
136
+ include: /node_modules/,
137
+ use: [
138
+ "style-loader",
139
+ "css-loader",
140
+ {
141
+ loader: "postcss-loader",
142
+ options: {
143
+ postcssOptions: {
144
+ plugins: [require("cssnano")({ preset: "default" })],
145
+ },
146
+ },
147
+ },
148
+ ],
149
+ },
150
+ ],
151
+ },
152
+ optimization: {
153
+ minimizer: [
154
+ new TerserPlugin({
155
+ terserOptions: {
156
+ format: {
157
+ // Turned on because emoji and regex is not minified properly using default
158
+ // https://github.com/facebook/create-react-app/issues/2488
159
+ ascii_only: true,
160
+ },
161
+ },
162
+ }),
163
+ ],
164
+ },
165
+ output: {
166
+ filename: `[name].js`,
167
+ path: path.resolve(process.cwd(), "dist"),
168
+ clean: true,
169
+ },
170
+ plugins: [
171
+ new DefinePlugin({
172
+ BACKEND_HOST: JSON.stringify(backendHost),
173
+ }),
174
+ // Apps can only submit a single JS file via the developer portal
175
+ new optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
176
+ ],
177
+ ...buildDevConfig(devConfig),
178
+ };
179
+ }
180
+
181
+ /**
182
+ *
183
+ * @param {Object} [options]
184
+ * @param {number} [options.port]
185
+ * @param {boolean} [options.enableHmr]
186
+ * @param {boolean} [options.enableHttps]
187
+ * @param {string} [options.appOrigin]
188
+ * @param {string} [options.appId] - Deprecated in favour of appOrigin
189
+ * @param {string} [options.certFile]
190
+ * @param {string} [options.keyFile]
191
+ * @returns {Object|null}
192
+ */
193
+ function buildDevConfig(options) {
194
+ if (!options) {
195
+ return null;
196
+ }
197
+
198
+ const { port, enableHmr, appOrigin, appId, enableHttps, certFile, keyFile } =
199
+ options;
200
+
201
+ let devServer = {
202
+ server: enableHttps
203
+ ? {
204
+ type: "https",
205
+ options: {
206
+ cert: certFile,
207
+ key: keyFile,
208
+ },
209
+ }
210
+ : "http",
211
+ host: "localhost",
212
+ historyApiFallback: {
213
+ rewrites: [{ from: /^\/$/, to: "/app.js" }],
214
+ },
215
+ port,
216
+ client: {
217
+ logging: "verbose",
218
+ },
219
+ static: {
220
+ directory: path.resolve(process.cwd(), "assets"),
221
+ publicPath: "/assets",
222
+ },
223
+ };
224
+
225
+ if (enableHmr && appOrigin) {
226
+ devServer = {
227
+ ...devServer,
228
+ allowedHosts: new URL(appOrigin).hostname,
229
+ headers: {
230
+ "Access-Control-Allow-Origin": appOrigin,
231
+ "Access-Control-Allow-Credentials": "true",
232
+ "Access-Control-Allow-Private-Network": "true",
233
+ },
234
+ };
235
+ } else if (enableHmr && appId) {
236
+ // Deprecated - App ID should not be used to configure HMR in the future and can be safely removed
237
+ // after a few months.
238
+
239
+ console.warn(
240
+ "Enabling Hot Module Replacement (HMR) with an App ID is deprecated, please see the README.md on how to update.",
241
+ );
242
+
243
+ const appDomain = `app-${appId.toLowerCase().trim()}.canva-apps.com`;
244
+ devServer = {
245
+ ...devServer,
246
+ allowedHosts: appDomain,
247
+ headers: {
248
+ "Access-Control-Allow-Origin": `https://${appDomain}`,
249
+ "Access-Control-Allow-Credentials": "true",
250
+ "Access-Control-Allow-Private-Network": "true",
251
+ },
252
+ };
253
+ } else {
254
+ if (enableHmr && !appOrigin) {
255
+ console.warn(
256
+ "Attempted to enable Hot Module Replacement (HMR) without configuring App Origin... Disabling HMR.",
257
+ );
258
+ }
259
+ devServer.webSocketServer = false;
260
+ }
261
+
262
+ return {
263
+ devtool: "source-map",
264
+ devServer,
265
+ };
266
+ }
267
+
268
+ module.exports = () => buildConfig();
269
+
270
+ module.exports.buildConfig = buildConfig;
@@ -0,0 +1,6 @@
1
+ CANVA_FRONTEND_PORT=8080
2
+ CANVA_BACKEND_PORT=3001
3
+ CANVA_BACKEND_HOST=http://localhost:3001 # TODO: replace this with your production URL before submitting your app
4
+ CANVA_APP_ID=YOUR_APP_ID_HERE # TODO: Add your app's ID here to configure your backend for JWT verification
5
+ CANVA_APP_ORIGIN=# TODO: Add your app's origin here from the "Developer Portal -> Configure your app -> App Origin" to enable HMR
6
+ CANVA_HMR_ENABLED=FALSE # TODO: set to TRUE to enable HMR
@@ -0,0 +1,9 @@
1
+ .idea
2
+ .ssl
3
+ node_modules
4
+ .DS_Store
5
+ yarn-error.log
6
+ dist
7
+ secrets.json
8
+ .env
9
+ **/*/db.json
@@ -0,0 +1,48 @@
1
+ # A message from Canva
2
+
3
+ By making these software components available to you, our goal is to give you
4
+ the right to use the components to build your apps for Canva's ecosystem. See
5
+ below for the specific licence terms that apply to your use.
6
+
7
+ # Licence
8
+
9
+ Canva Pty Ltd (ACN 158 929 938) ("Canva") owns the copyright in the software and
10
+ associated documentation files to which this Licence relates (each a "Software
11
+ Component"). Canva reserves all of its rights.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
14
+ the Software Components ("You"), to use the Software Components, but strictly
15
+ subject to the following restrictions and conditions:
16
+
17
+ 1. You must only use the Software Components and any Derivative on the Canva
18
+ Platform.
19
+
20
+ 2. You must only use the Software Components and any Derivative for the purpose
21
+ of building or updating Permitted Apps, and for no other purpose.
22
+
23
+ 3. You must include a copy of this Licence in all copies of any Software
24
+ Component and Derivative.
25
+
26
+ 4. To the fullest extent permitted by law, the Software Components are provided
27
+ "as is", without warranty of any kind, express or implied, including but not
28
+ limited to the warranties of merchantability, fitness for a particular
29
+ purpose and non-infringement. To the fullest extent permitted by law, in no
30
+ event shall the authors or copyright holders be liable for any claim,
31
+ damages or other liability, whether in an action of contract, tort or
32
+ otherwise, arising from, out of or in connection with the Software Components
33
+ or any Derivative, or the use of or other dealings in the Software Components
34
+ or any Derivative.
35
+
36
+ 5. In this Licence:
37
+
38
+ (a) "Canva Platform" means the visual communications platform owned and
39
+ operated by Canva that is made available on Canva.com (as well as any
40
+ sub-domains and international versions) and via mobile applications, desktop
41
+ applications, and in other forms provided or made available by Canva;
42
+
43
+ (b) "Derivative" means any software, document or other material that: (i)
44
+ contains any Software Component; and/or (ii) comprises or contains a
45
+ derivative, adaptation or substantial part of any Software Component; and
46
+
47
+ (c) "Permitted App" means a software application that is solely offered to
48
+ end-users on the Canva Platform.
@@ -0,0 +1,250 @@
1
+ # Canva App
2
+
3
+ Welcome to your Canva App! 🎉
4
+
5
+ This is a starting point for your app using your chosen template. The complete documentation for the platform is at [canva.dev/docs/apps](https://www.canva.dev/docs/apps/).
6
+
7
+ **Note:** This code and documentation assumes some experience with TypeScript and React.
8
+
9
+ ## Requirements
10
+
11
+ - Node.js `v18` or `v20.10.0`
12
+ - npm `v9` or `v10`
13
+
14
+ **Note:** To make sure you're running the correct version of Node.js, we recommend using a version manager, such as [nvm](https://github.com/nvm-sh/nvm#intro). The [.nvmrc](/.nvmrc) file in the root directory of this repo will ensure the correct version is used once you run `nvm install`.
15
+
16
+ ## Quick start
17
+
18
+ ```bash
19
+ npm install
20
+ ```
21
+
22
+ ## Running your Canva App
23
+
24
+ ### Step 1: Start the local development server
25
+
26
+ To start the boilerplate's development server, run the following command:
27
+
28
+ ```bash
29
+ npm start
30
+ ```
31
+
32
+ The server becomes available at <http://localhost:8080>.
33
+
34
+ The app's source code is in the `src/app.tsx` file.
35
+
36
+ ### Step 2: Preview the app
37
+
38
+ The local development server only exposes a JavaScript bundle, so you can't preview an app by visiting <http://localhost:8080>. You can only preview an app via the Canva editor.
39
+
40
+ To preview an app:
41
+
42
+ 1. Create an app via the [Developer Portal](https://www.canva.com/developers/apps).
43
+ 2. Select **App source > Development URL**.
44
+ 3. In the **Development URL** field, enter the URL of the development server.
45
+ 4. Click **Preview**. This opens the Canva editor (and the app) in a new tab.
46
+ 5. Click **Open**. (This screen only appears when using an app for the first time.)
47
+
48
+ The app will appear in the side panel.
49
+
50
+ <details>
51
+ <summary>Previewing apps in Safari</summary>
52
+
53
+ By default, the development server is not HTTPS-enabled. This is convenient, as there's no need for a security certificate, but it prevents apps from being previewed in Safari.
54
+
55
+ **Why Safari requires the development server to be HTTPS-enabled?**
56
+
57
+ Canva itself is served via HTTPS and most browsers prevent HTTPS pages from loading scripts via non-HTTPS connections. Chrome and Firefox make exceptions for local servers, such as `localhost`, but Safari does not, so if you're using Safari, the development server must be HTTPS-enabled.
58
+
59
+ To learn more, see [Loading mixed-content resources](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content#loading_mixed-content_resources).
60
+
61
+ To preview apps in Safari:
62
+
63
+ 1. Start the development server with HTTPS enabled:
64
+
65
+ ```bash
66
+ # Run the main app
67
+ npm start --use-https
68
+
69
+ # Run an example
70
+ npm start <example-name> --use-https
71
+ ```
72
+
73
+ 2. Navigate to <https://localhost:8080>.
74
+ 3. Bypass the invalid security certificate warning:
75
+ 4. Click **Show details**.
76
+ 5. Click **Visit website**.
77
+ 6. In the Developer Portal, set the app's **Development URL** to <https://localhost:8080>.
78
+
79
+ You need to bypass the invalid security certificate warning every time you start the local server. A similar warning will appear in other browsers (and will need to be bypassed) whenever HTTPS is enabled.
80
+
81
+ </details>
82
+
83
+ ### (Optional) Step 3: Enable Hot Module Replacement
84
+
85
+ By default, every time you make a change to an app, you have to reload the entire app to see the results of those changes. If you enable [Hot Module Replacement](https://webpack.js.org/concepts/hot-module-replacement/) (HMR), changes will be reflected without a full reload, which significantly speeds up the development loop.
86
+
87
+ **Note:** HMR does **not** work while running the development server in a Docker container.
88
+
89
+ To enable HMR:
90
+
91
+ 1. Navigate to an app via the [Your apps](https://www.canva.com/developers/apps).
92
+ 2. Select **Configure your app**.
93
+ 3. Copy the value from the **App origin** field. This value is unique to each app and cannot be customized.
94
+ 4. In the root directory, open the `.env` file.
95
+ 5. Set the `CANVA_APP_ORIGIN` environment variable to the value copied from the **App origin** field:
96
+
97
+ ```bash
98
+ CANVA_APP_ORIGIN=# YOUR APP ORIGIN GOES HERE
99
+ ```
100
+
101
+ 6. Set the `CANVA_HMR_ENABLED` environment variable to `true`:
102
+
103
+ ```bash
104
+ CANVA_HMR_ENABLED=true
105
+ ```
106
+
107
+ 7. Restart the local development server.
108
+ 8. Reload the app manually to ensure that HMR takes effect.
109
+
110
+ ## Running an app's backend
111
+
112
+ Some templates provide an example backend. This backend is defined in the template's `backend/server.ts` file, automatically starts when the `npm start` command is run, and becomes available at <http://localhost:3001>.
113
+
114
+ To run templates that have a backend:
115
+
116
+ 1. Navigate to the [Your apps](https://www.canva.com/developers/apps) page.
117
+ 2. Copy the ID of an app from the **App ID** column.
118
+ 3. In the starter kit's `.env` file, set `CANVA_APP_ID` to the ID of the app.
119
+
120
+ For example:
121
+
122
+ ```bash
123
+ CANVA_APP_ID=AABBccddeeff
124
+ CANVA_APP_ORIGIN=#
125
+ CANVA_BACKEND_PORT=3001
126
+ CANVA_FRONTEND_PORT=8080
127
+ CANVA_BACKEND_HOST=http://localhost:3001
128
+ CANVA_HMR_ENABLED=FALSE
129
+ ```
130
+
131
+ 4. Start the app:
132
+
133
+ ```bash
134
+ npm start
135
+ ```
136
+
137
+ The ID of the app must be explicitly defined because it's required to [send and verify HTTP requests](https://www.canva.dev/docs/apps/verifying-http-requests/). If you don't set up the ID in the `.env` file, an error will be thrown when attempting to run the example.
138
+
139
+ ## Customizing the backend host
140
+
141
+ If your app has a backend, the URL of the server likely depends on whether it's a development or production build. For example, during development, the backend is probably running on a localhost URL, but once the app's in production, the backend needs to be exposed to the internet.
142
+
143
+ To more easily customize the URL of the server:
144
+
145
+ 1. Open the `.env` file in the text editor of your choice.
146
+ 2. Set the `CANVA_BACKEND_HOST` environment variable to the URL of the server.
147
+ 3. When sending a request, use `BACKEND_HOST` as the base URL:
148
+
149
+ ```ts
150
+ const response = await fetch(`${BACKEND_HOST}/custom-route`);
151
+ ```
152
+
153
+ **Note:** `BACKEND_HOST` is a global constant that contains the value of the `CANVA_BACKEND_HOST` environment variable. The variable is made available to the app via webpack and does not need to be imported.
154
+
155
+ 4. Before bundling the app for production, update `CANVA_BACKEND_HOST` to point to the production backend.
156
+
157
+ ## Configure ngrok (optional)
158
+
159
+ If your app requires authentication with a third party service, your server needs to be exposed via a publicly available URL, so that Canva can send requests to it.
160
+ This step explains how to do this with [ngrok](https://ngrok.com/).
161
+
162
+ **Note:** ngrok is a useful tool, but it has inherent security risks, such as someone figuring out the URL of your server and accessing proprietary information. Be mindful of the risks, and if you're working as part of an organization, talk to your IT department.
163
+ You must replace ngrok urls with hosted API endpoints for production apps.
164
+
165
+ To use ngrok, you'll need to do the following:
166
+
167
+ 1. Sign up for a ngrok account at <https://ngrok.com/>.
168
+ 2. Locate your ngrok [authtoken](https://dashboard.ngrok.com/get-started/your-authtoken).
169
+ 3. Set an environment variable for your authtoken, using the command line. Replace `<YOUR_AUTH_TOKEN>` with your actual ngrok authtoken:
170
+
171
+ For macOS and Linux:
172
+
173
+ ```bash
174
+ export NGROK_AUTHTOKEN=<YOUR_AUTH_TOKEN>
175
+ ```
176
+
177
+ For Windows PowerShell:
178
+
179
+ ```shell
180
+ $Env:NGROK_AUTHTOKEN = "<YOUR_AUTH_TOKEN>"
181
+ ```
182
+
183
+ This environment variable is available for the current terminal session, so the command must be re-run for each new session. Alternatively, you can add the variable to your terminal's default parameters.
184
+
185
+ ## Run the development server with ngrok and add authentication to the app
186
+
187
+ These steps demonstrate how to start the local development server with ngrok.
188
+
189
+ From your app's root directory
190
+
191
+ 1. Stop any running scripts, and run the following command to launch the backend and frontend development servers. The `--ngrok` parameter exposes the backend server via a publicly accessible URL.
192
+
193
+ ```bash
194
+ npm start --ngrok
195
+ ```
196
+
197
+ 2. After ngrok is running, copy your ngrok url
198
+ (e.g. `https://0000-0000.ngrok-free.app`) to the clipboard.
199
+
200
+ 1. Go to your app in the [Developer Portal](https://www.canva.com/developers/apps).
201
+ 2. Navigate to the "Add authentication" section of your app.
202
+ 3. Check "This app requires authentication"
203
+ 4. In the "Redirect URL" text box, enter your ngrok url followed by `/redirect-url` e.g.
204
+ `https://0000-0000.ngrok-free.app/redirect-url`
205
+ 5. In the "Authentication base URL" text box, enter your ngrok url followed by `/` e.g.
206
+ `https://0000-0000.ngrok-free.app/`
207
+ Note: Your ngrok URL changes each time you restart ngrok. Keep these fields up to
208
+ date to ensure your example authentication step will run.
209
+
210
+ 3. Make sure the app is authenticating users by making the following changes:
211
+
212
+ 1. Replace
213
+
214
+ `router.post("/resources/find", async (req, res) => {`
215
+
216
+ with
217
+
218
+ `router.post("/api/resources/find", async (req, res) => {`
219
+
220
+ in [./backend/routers/auth.ts](./backend/routers/auth.ts). Adding `/api/` to the route ensures
221
+ the JWT middleware authenticates requests.
222
+
223
+ 2. Replace
224
+
225
+ ``const url = new URL(`${BACKEND_HOST}/resources/find`);``
226
+
227
+ with
228
+
229
+ ``const url = new URL(`${BACKEND_HOST}/api/resources/find`);``
230
+
231
+ in [./adapter.ts](./adapter.ts)
232
+
233
+ 3. Comment out these lines in [./app.tsx](./app.tsx)
234
+
235
+ ```typescript
236
+ // Comment this next line out for production apps
237
+ setAuthState("authenticated");
238
+ ```
239
+
240
+ 4. Navigate to your app at `https://www.canva.com/developers/apps`, and click **Preview** to preview the app.
241
+ 1. A new screen will appear asking if you want to authenticate.
242
+ Press **Connect** to start the authentication flow.
243
+ 2. A ngrok screen may appear. If it does, select **Visit Site**
244
+ 3. An authentication popup will appear. For the username, enter `username`, and
245
+ for the password enter `password`.
246
+ 4. If successful, you will be redirected back to your app.
247
+ 5. You can now modify the `/redirect-url` function in `server.ts` to authenticate with your third-party
248
+ asset manager, and `/api/resources/find` to pull assets from your third-party asset manager.
249
+
250
+ See `https://www.canva.dev/docs/apps/authenticating-users/` for more details.
@@ -0,0 +1,8 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+
3
+ export default {
4
+ preset: "ts-jest",
5
+ testEnvironment: "node",
6
+ testRegex: "(/tests/.*|(\\.|/)(tests))\\.ts?$",
7
+ modulePathIgnorePatterns: ["./internal/", "./node_modules/"],
8
+ };
@@ -0,0 +1,42 @@
1
+ import * as fs from "fs/promises";
2
+ import * as path from "path";
3
+
4
+ /**
5
+ * This file creates a "database" out of a JSON file. It's only for
6
+ * demonstration purposes. A real app should use a real database.
7
+ */
8
+ const DATABASE_FILE_PATH = path.join(__dirname, "db.json");
9
+
10
+ interface Database<T> {
11
+ read(): Promise<T>;
12
+ write(data: T): Promise<void>;
13
+ }
14
+
15
+ export class JSONFileDatabase<T> implements Database<T> {
16
+ constructor(private readonly seedData: T) {}
17
+
18
+ // Creates a database file if one doesn't already exist
19
+ private async init(): Promise<void> {
20
+ try {
21
+ // Do nothing, since the database is initialized
22
+ await fs.stat(DATABASE_FILE_PATH);
23
+ } catch {
24
+ const file = JSON.stringify(this.seedData);
25
+ await fs.writeFile(DATABASE_FILE_PATH, file);
26
+ }
27
+ }
28
+
29
+ // Loads and parses the database file
30
+ async read(): Promise<T> {
31
+ await this.init();
32
+ const file = await fs.readFile(DATABASE_FILE_PATH, "utf8");
33
+ return JSON.parse(file);
34
+ }
35
+
36
+ // Overwrites the database file with provided data
37
+ async write(data: T): Promise<void> {
38
+ await this.init();
39
+ const file = JSON.stringify(data);
40
+ await fs.writeFile(DATABASE_FILE_PATH, file);
41
+ }
42
+ }