@canva/cli 1.14.0 → 1.16.0

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 (42) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -0
  3. package/cli.js +308 -308
  4. package/package.json +1 -1
  5. package/templates/base/backend/base_backend/create.ts +10 -0
  6. package/templates/base/backend/routers/auth.ts +12 -9
  7. package/templates/base/package.json +3 -3
  8. package/templates/content_publisher/README.md +58 -0
  9. package/templates/content_publisher/canva-app.json +17 -0
  10. package/templates/content_publisher/declarations/declarations.d.ts +29 -0
  11. package/templates/content_publisher/eslint.config.mjs +14 -0
  12. package/templates/content_publisher/package.json +90 -0
  13. package/templates/content_publisher/scripts/copy_env.ts +13 -0
  14. package/templates/content_publisher/scripts/ssl/ssl.ts +131 -0
  15. package/templates/content_publisher/scripts/start/app_runner.ts +223 -0
  16. package/templates/content_publisher/scripts/start/context.ts +171 -0
  17. package/templates/content_publisher/scripts/start/start.ts +46 -0
  18. package/templates/content_publisher/src/index.tsx +4 -0
  19. package/templates/content_publisher/src/intents/content_publisher/index.tsx +113 -0
  20. package/templates/content_publisher/src/intents/content_publisher/post_preview.tsx +226 -0
  21. package/templates/content_publisher/src/intents/content_publisher/preview_ui.tsx +53 -0
  22. package/templates/content_publisher/src/intents/content_publisher/settings_ui.tsx +71 -0
  23. package/templates/content_publisher/src/intents/content_publisher/types.ts +29 -0
  24. package/templates/content_publisher/styles/components.css +56 -0
  25. package/templates/content_publisher/styles/preview_ui.css +88 -0
  26. package/templates/content_publisher/tsconfig.json +56 -0
  27. package/templates/content_publisher/webpack.config.ts +247 -0
  28. package/templates/dam/backend/server.ts +2 -3
  29. package/templates/dam/package.json +5 -4
  30. package/templates/dam/utils/backend/base_backend/create.ts +10 -0
  31. package/templates/data_connector/package.json +3 -3
  32. package/templates/gen_ai/backend/server.ts +2 -3
  33. package/templates/gen_ai/package.json +4 -3
  34. package/templates/gen_ai/utils/backend/base_backend/create.ts +10 -0
  35. package/templates/hello_world/package.json +3 -3
  36. package/templates/mls/package.json +3 -3
  37. package/templates/base/backend/jwt_middleware/index.ts +0 -1
  38. package/templates/base/backend/jwt_middleware/jwt_middleware.ts +0 -224
  39. package/templates/dam/utils/backend/jwt_middleware/index.ts +0 -1
  40. package/templates/dam/utils/backend/jwt_middleware/jwt_middleware.ts +0 -224
  41. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +0 -1
  42. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +0 -224
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canva/cli",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "description": "The official Canva CLI.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "Canva Pty Ltd.",
@@ -1,4 +1,5 @@
1
1
  /* eslint-disable no-console */
2
+ import { TokenVerificationError } from "@canva/app-middleware";
2
3
  import debug from "debug";
3
4
  import express from "express";
4
5
  import type { NextFunction, Request, Response } from "express";
@@ -63,6 +64,15 @@ export function createBaseServer(router: express.Router): BaseServer {
63
64
 
64
65
  // default error handler
65
66
  app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
67
+ // Handle authentication errors from @canva/app-middleware
68
+ if (err instanceof TokenVerificationError) {
69
+ res.status(err.statusCode).json({
70
+ error: err.code,
71
+ message: err.message,
72
+ });
73
+ return;
74
+ }
75
+
66
76
  console.error(err.stack);
67
77
  res.status(500).send({
68
78
  error: "something went wrong",
@@ -1,11 +1,11 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion -- user is guaranteed by verifyToken middleware */
2
+ import { tokenExtractors, user } from "@canva/app-middleware/express";
1
3
  import chalk from "chalk";
2
4
  import cookieParser from "cookie-parser";
3
5
  import crypto from "crypto";
4
6
  import "dotenv/config";
5
7
  import express from "express";
6
8
  import basicAuth from "express-basic-auth";
7
- import { createJwtMiddleware } from "../../utils/backend/jwt_middleware";
8
- import { getTokenFromQueryString } from "../../utils/backend/jwt_middleware/jwt_middleware";
9
9
  import { JSONFileDatabase } from "../database/database";
10
10
 
11
11
  /**
@@ -95,7 +95,10 @@ export const createAuthRouter = () => {
95
95
  * Use a JSON Web Token (JWT) to verify incoming requests. The JWT is
96
96
  * extracted from the `canva_user_token` parameter.
97
97
  */
98
- createJwtMiddleware(APP_ID, getTokenFromQueryString),
98
+ user.verifyToken({
99
+ appId: APP_ID,
100
+ tokenExtractor: tokenExtractors.fromQuery("canva_user_token"),
101
+ }),
99
102
  /**
100
103
  * Warning: For demonstration purposes, we're using basic authentication and
101
104
  * hard- coding a username and password. This is not a production-ready
@@ -155,8 +158,8 @@ export const createAuthRouter = () => {
155
158
  return failureResponse();
156
159
  }
157
160
 
158
- // Get the userId from JWT middleware
159
- const { userId } = req.canva;
161
+ // Get the userId from user object in the request context
162
+ const { userId } = req.canva.user!;
160
163
 
161
164
  // Load the database
162
165
  const data = await db.read();
@@ -182,7 +185,7 @@ export const createAuthRouter = () => {
182
185
  * TODO: Add this middleware to all routes that will receive requests from
183
186
  * your app.
184
187
  */
185
- const jwtMiddleware = createJwtMiddleware(APP_ID);
188
+ const jwtMiddleware = user.verifyToken({ appId: APP_ID });
186
189
 
187
190
  /**
188
191
  * This endpoint is called when a user disconnects an app from their account.
@@ -197,8 +200,8 @@ export const createAuthRouter = () => {
197
200
  * Developer Portal. Localhost addresses will not work to test this endpoint.
198
201
  */
199
202
  router.post("/configuration/delete", jwtMiddleware, async (req, res) => {
200
- // Get the userId from JWT middleware
201
- const { userId } = req.canva;
203
+ // Get the userId from user object in the request context
204
+ const { userId } = req.canva.user!;
202
205
 
203
206
  // Load the database
204
207
  const data = await db.read();
@@ -227,7 +230,7 @@ export const createAuthRouter = () => {
227
230
  const data = await db.read();
228
231
 
229
232
  // Check if the user is authenticated
230
- const isAuthenticated = data.users.includes(req.canva.userId);
233
+ const isAuthenticated = data.users.includes(req.canva.user!.userId);
231
234
 
232
235
  // Return the authentication status
233
236
  res.send({
@@ -8,11 +8,11 @@
8
8
  "dependencies": {
9
9
  "@canva/app-hooks": "^0.0.0-beta.4",
10
10
  "@canva/app-i18n-kit": "^1.2.0",
11
- "@canva/app-ui-kit": "^5.4.0",
11
+ "@canva/app-ui-kit": "^5.5.0",
12
12
  "@canva/asset": "^2.3.0",
13
13
  "@canva/design": "^2.7.5",
14
- "@canva/error": "^2.1.0",
15
- "@canva/platform": "^2.2.0",
14
+ "@canva/error": "^2.2.0",
15
+ "@canva/platform": "^2.2.1",
16
16
  "@canva/user": "^2.1.2",
17
17
  "cookie-parser": "1.4.7",
18
18
  "react": "^19.2.3",
@@ -0,0 +1,58 @@
1
+ # Content Publisher Template
2
+
3
+ ## Overview
4
+
5
+ This template provides a minimal starting point for building a content publisher app. It demonstrates the basic structure and key concepts of the Content Publisher intent, including:
6
+
7
+ - Implementing the Content Publisher intent with all required functions
8
+ - Rendering a settings UI where users configure publishing options
9
+ - Rendering a preview UI that shows how content will appear after publishing
10
+ - Defining output types and media slot specifications
11
+ - Handling publish operations (with placeholder implementation)
12
+
13
+ This template focuses on the intent structure and UI patterns. You'll need to add your own platform integration, including authentication and API calls to your publishing service.
14
+
15
+ ## What's Included
16
+
17
+ ### Content Publisher Intent Structure
18
+
19
+ The template implements all four required functions:
20
+
21
+ - `renderSettingsUi`: Renders a simple settings form with a caption input field
22
+ - `renderPreviewUi`: Displays a mock social media post preview
23
+ - `getPublishConfiguration`: Defines a "Feed Post" output type with image specifications
24
+ - `publishContent`: Placeholder function that returns mock success response
25
+
26
+ ### UI Components
27
+
28
+ - **Settings UI** (`settings_ui.tsx`): A form using the App UI Kit with a caption field and validation
29
+ - **Preview UI** (`preview_ui.tsx`): A social media post preview showing how the published content will look
30
+
31
+ ### App UI Kit
32
+
33
+ The App UI Kit is a React-based component library designed for creating apps that emulate Canva's look and feel. We strongly recommend using the App UI Kit if you're planning to release an app to the public, as this makes it easier to comply with our [design guidelines](https://www.canva.dev/docs/apps/design-guidelines/).
34
+
35
+ This template uses the App UI Kit for both the settings and preview UIs to demonstrate common patterns. The preview UI is more flexible in production and can be customized to match your target platform's design system.
36
+
37
+ ## Getting Started
38
+
39
+ ### 0. Set up your app
40
+
41
+ - If not already handled by the Canva CLI, you need to create an app via the [Developer Portal](https://www.canva.com/developers/apps).
42
+ - On the **Intents** page, enable the `Content Publisher` intent
43
+
44
+ ### 1. Run the template
45
+
46
+ - Run `npm start` to start the development server
47
+ - Click **Preview URL** in the terminal or **Preview** in the [Developer Portal](https://www.canva.com/developers/apps) to view the app in the Canva editor
48
+ - Try entering a caption and viewing the preview
49
+
50
+ ### 2. Customize for your platform
51
+
52
+ To integrate with your publishing platform, you'll need to:
53
+
54
+ - **Add authentication**: [Implement OAuth](https://www.canva.dev/docs/apps/authenticating-users/oauth/) or your authentication method to connect user accounts
55
+ - **Customize settings**: Modify `settings_ui.tsx` to collect platform-specific publishing options
56
+ - **Update preview**: Modify `preview_ui.tsx` to match your platform's post appearance
57
+ - **Configure output types**: Update `getPublishConfiguration` in `index.tsx` to define your supported formats and media requirements
58
+ - **Implement publishing**: Replace the placeholder in `publishContent` with actual API calls to your platform
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "https://www.canva.dev/schemas/app/v1/manifest-schema.json",
3
+ "manifest_schema_version": 1,
4
+ "runtime": {
5
+ "permissions": [
6
+ {
7
+ "name": "canva:design:content:read",
8
+ "type": "mandatory"
9
+ }
10
+ ]
11
+ },
12
+ "intent": {
13
+ "content_publisher": {
14
+ "enrolled": true
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,29 @@
1
+ declare module "*.css" {
2
+ const styles: { [className: string]: string };
3
+ export = styles;
4
+ }
5
+
6
+ declare module "*.jpg" {
7
+ const content: string;
8
+ export default content;
9
+ }
10
+
11
+ declare module "*.jpeg" {
12
+ const content: string;
13
+ export default content;
14
+ }
15
+
16
+ declare module "*.png" {
17
+ const content: string;
18
+ export default content;
19
+ }
20
+
21
+ declare module "*.svg" {
22
+ const content: React.FunctionComponent<{
23
+ size?: "tiny" | "small" | "medium" | "large";
24
+ className?: string;
25
+ }>;
26
+ export default content;
27
+ }
28
+
29
+ declare const BACKEND_HOST: string;
@@ -0,0 +1,14 @@
1
+ import canvaPlugin from "@canva/app-eslint-plugin";
2
+
3
+ export default [
4
+ {
5
+ ignores: [
6
+ "**/node_modules/",
7
+ "**/dist",
8
+ "**/*.d.ts",
9
+ "**/*.d.tsx",
10
+ "**/*.config.*",
11
+ ],
12
+ },
13
+ ...canvaPlugin.configs.apps,
14
+ ];
@@ -0,0 +1,90 @@
1
+ {
2
+ "private": true,
3
+ "name": "content_publisher",
4
+ "description": "A Canva Content Publisher App",
5
+ "scripts": {
6
+ "extract": "formatjs extract \"src/**/*.{ts,tsx}\" --out-file dist/messages_en.json",
7
+ "build": "webpack --config webpack.config.ts --mode production && npm run extract",
8
+ "format": "prettier '**/*.{css,ts,tsx}' --no-config --write",
9
+ "format:check": "prettier '**/*.{css,ts,tsx}' --no-config --check --ignore-path",
10
+ "format:file": "prettier $1 --no-config --write",
11
+ "lint": "eslint .",
12
+ "lint:fix": "eslint . --fix",
13
+ "lint:types": "tsc",
14
+ "start": "ts-node ./scripts/start/start.ts",
15
+ "start:preview": "npm run start -- --preview",
16
+ "test": "jest --no-cache",
17
+ "test:watch": "jest --watchAll",
18
+ "test:update": "npm run test -- -u",
19
+ "postinstall": "ts-node ./scripts/copy_env.ts"
20
+ },
21
+ "dependencies": {
22
+ "@canva/app-hooks": "^0.0.0-beta.4",
23
+ "@canva/app-i18n-kit": "^1.2.0",
24
+ "@canva/app-ui-kit": "^5.5.0",
25
+ "@canva/asset": "^2.3.0",
26
+ "@canva/design": "^2.7.5",
27
+ "@canva/error": "^2.2.0",
28
+ "@canva/intents": "^2.0.2-beta.3",
29
+ "@canva/platform": "^2.2.1",
30
+ "@canva/user": "^2.1.2",
31
+ "react": "^19.2.3",
32
+ "react-dom": "^19.2.3",
33
+ "react-intl": "^7.1.11"
34
+ },
35
+ "devDependencies": {
36
+ "@canva/app-eslint-plugin": "^1.0.0-beta.7",
37
+ "@canva/cli": ">= 0.0.1-beta.13",
38
+ "@formatjs/cli": "6.7.2",
39
+ "@formatjs/ts-transformer": "3.14.0",
40
+ "@ngrok/ngrok": "1.5.2",
41
+ "@pmmmwh/react-refresh-webpack-plugin": "0.6.1",
42
+ "@svgr/webpack": "8.1.0",
43
+ "@testing-library/react": "16.3.0",
44
+ "@types/debug": "4.1.12",
45
+ "@types/express": "4.17.21",
46
+ "@types/jest": "29.5.14",
47
+ "@types/jsonwebtoken": "9.0.10",
48
+ "@types/node": "20.19.2",
49
+ "@types/node-fetch": "2.6.13",
50
+ "@types/node-forge": "1.3.14",
51
+ "@types/nodemon": "1.19.6",
52
+ "@types/react": "19.2.2",
53
+ "@types/react-dom": "19.2.1",
54
+ "@types/webpack-env": "1.18.8",
55
+ "chalk": "4.1.2",
56
+ "cli-table3": "0.6.5",
57
+ "css-loader": "7.1.2",
58
+ "css-modules-typescript-loader": "4.0.1",
59
+ "cssnano": "7.1.1",
60
+ "debug": "4.4.1",
61
+ "dotenv": "16.6.0",
62
+ "express": "4.22.1",
63
+ "express-basic-auth": "1.2.1",
64
+ "jest": "29.7.0",
65
+ "jest-css-modules-transform": "4.4.2",
66
+ "jest-environment-jsdom": "29.7.0",
67
+ "jsonwebtoken": "9.0.3",
68
+ "jwks-rsa": "3.2.0",
69
+ "mini-css-extract-plugin": "2.9.4",
70
+ "node-fetch": "3.3.2",
71
+ "node-forge": "1.3.2",
72
+ "nodemon": "3.0.1",
73
+ "open": "8.4.2",
74
+ "postcss-loader": "8.1.1",
75
+ "prettier": "3.6.2",
76
+ "react-refresh": "0.17.0",
77
+ "style-loader": "4.0.0",
78
+ "terser-webpack-plugin": "5.3.14",
79
+ "tree-kill": "1.2.2",
80
+ "ts-jest": "29.4.1",
81
+ "ts-loader": "9.5.4",
82
+ "ts-node": "10.9.2",
83
+ "typescript": "5.9.2",
84
+ "url-loader": "4.1.1",
85
+ "webpack": "5.99.9",
86
+ "webpack-cli": "6.0.1",
87
+ "webpack-dev-server": "5.2.2",
88
+ "yargs": "17.7.2"
89
+ }
90
+ }
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
3
+ import fs from "fs";
4
+ import path from "path";
5
+
6
+ const envPath = path.resolve(__dirname, "..", ".env");
7
+ const templatePath = path.resolve(__dirname, "..", ".env.template");
8
+
9
+ if (!fs.existsSync(templatePath)) {
10
+ console.warn(".env.template file does not exist, skipping copy of .env file");
11
+ } else if (!fs.existsSync(envPath)) {
12
+ fs.copyFileSync(templatePath, envPath);
13
+ }
@@ -0,0 +1,131 @@
1
+ import crypto from "crypto";
2
+ import fs from "fs/promises";
3
+ import { pki } from "node-forge";
4
+ import path from "path";
5
+
6
+ const SSL_CERT_DIR = path.resolve(process.cwd(), "..", "..", ".ssl");
7
+ const CERT_FILE = path.resolve(SSL_CERT_DIR, "certificate.pem");
8
+ const KEY_FILE = path.resolve(SSL_CERT_DIR, "private-key.pem");
9
+
10
+ export interface Certificate {
11
+ keyFile: string;
12
+ certFile: string;
13
+ }
14
+
15
+ const CERT_ATTRS: { name: string; value: string }[] = [
16
+ {
17
+ name: "commonName",
18
+ value: "localhost",
19
+ },
20
+ {
21
+ name: "countryName",
22
+ value: "AU",
23
+ },
24
+ {
25
+ name: "stateOrProvinceName",
26
+ value: "New South Wales",
27
+ },
28
+ {
29
+ name: "localityName",
30
+ value: "Sydney",
31
+ },
32
+ {
33
+ name: "organizationName",
34
+ value: "Test",
35
+ },
36
+ {
37
+ name: "organizationalUnitName",
38
+ value: "Test",
39
+ },
40
+ ];
41
+
42
+ const generateRsaKeys = async (): Promise<{
43
+ publicKey: string;
44
+ privateKey: string;
45
+ }> =>
46
+ new Promise((resolve, reject) => {
47
+ crypto.generateKeyPair(
48
+ "rsa",
49
+ {
50
+ modulusLength: 2096,
51
+ publicKeyEncoding: {
52
+ type: "spki",
53
+ format: "pem",
54
+ },
55
+ privateKeyEncoding: {
56
+ type: "pkcs8",
57
+ format: "pem",
58
+ },
59
+ },
60
+ (err, publicKey, privateKey) => {
61
+ if (err) {
62
+ reject(err);
63
+ } else {
64
+ resolve({ publicKey, privateKey });
65
+ }
66
+ },
67
+ );
68
+ });
69
+
70
+ const generateCertificate = (opts: {
71
+ privateKey: string;
72
+ publicKey: string;
73
+ }): string => {
74
+ const privateKey = pki.privateKeyFromPem(opts.privateKey);
75
+ const publicKey = pki.publicKeyFromPem(opts.publicKey);
76
+
77
+ const cert = pki.createCertificate();
78
+
79
+ cert.publicKey = publicKey;
80
+ cert.serialNumber = "01";
81
+ cert.validity.notBefore = new Date();
82
+ cert.validity.notAfter = new Date();
83
+ cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
84
+
85
+ cert.setSubject(CERT_ATTRS);
86
+ cert.setIssuer(CERT_ATTRS);
87
+
88
+ // the actual certificate signing
89
+ cert.sign(privateKey);
90
+
91
+ // now convert the Forge certificate to PEM format
92
+ return pki.certificateToPem(cert);
93
+ };
94
+
95
+ const writeCertFiles = async (opts: {
96
+ cert: string;
97
+ privateKey: string;
98
+ }): Promise<void> => {
99
+ const { cert, privateKey } = opts;
100
+
101
+ await fs.mkdir(SSL_CERT_DIR, { recursive: true });
102
+ await Promise.all([
103
+ fs.writeFile(CERT_FILE, cert, { encoding: "utf8" }),
104
+ fs.writeFile(KEY_FILE, privateKey, { encoding: "utf8" }),
105
+ ]);
106
+ };
107
+
108
+ const cerfFilesExist = async (): Promise<boolean> => {
109
+ try {
110
+ await Promise.all([
111
+ fs.access(CERT_FILE, fs.constants.R_OK | fs.constants.W_OK),
112
+ fs.access(KEY_FILE, fs.constants.R_OK | fs.constants.W_OK),
113
+ ]);
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ };
119
+
120
+ export const createOrRetrieveCertificate = async (): Promise<Certificate> => {
121
+ if (!(await cerfFilesExist())) {
122
+ const keys = await generateRsaKeys();
123
+ const cert = generateCertificate(keys);
124
+ await writeCertFiles({ cert, privateKey: keys.privateKey });
125
+ }
126
+
127
+ return {
128
+ certFile: CERT_FILE,
129
+ keyFile: KEY_FILE,
130
+ };
131
+ };
@@ -0,0 +1,223 @@
1
+ /* eslint-disable no-console */
2
+ import { generatePreviewUrl } from "@canva/cli";
3
+ import ngrok from "@ngrok/ngrok";
4
+ import chalk from "chalk";
5
+ import Table from "cli-table3";
6
+ import nodemon from "nodemon";
7
+ import open from "open";
8
+ import os from "os";
9
+ import webpack from "webpack";
10
+ import WebpackDevServer from "webpack-dev-server";
11
+ import { buildConfig } from "../../webpack.config";
12
+ import type { Certificate } from "../ssl/ssl";
13
+ import { createOrRetrieveCertificate } from "../ssl/ssl";
14
+ import type { Context } from "./context";
15
+
16
+ export const infoChalk = chalk.blue.bold;
17
+ export const warnChalk = chalk.bgYellow.bold;
18
+ export const errorChalk = chalk.bgRed.bold;
19
+ export const highlightChalk = chalk.greenBright.bold;
20
+ export const linkChalk = chalk.cyan;
21
+
22
+ /**
23
+ * Returns the appropriate modifier key text based on the user's operating system.
24
+ * @returns "cmd" for macOS, "ctrl" for Windows and Linux
25
+ */
26
+ export function getModifierKey(): string {
27
+ const platform = os.platform();
28
+ switch (platform) {
29
+ case "darwin": // macOS
30
+ return "cmd";
31
+ case "win32": // Windows
32
+ return "ctrl";
33
+ default: // Linux and others
34
+ return "ctrl";
35
+ }
36
+ }
37
+
38
+ export class AppRunner {
39
+ async run(ctx: Context) {
40
+ console.log(
41
+ infoChalk("Info:"),
42
+ `Starting development server for ${highlightChalk(ctx.entryDir)}\n`,
43
+ );
44
+
45
+ if (!ctx.hmrEnabled) {
46
+ console.log(
47
+ `${infoChalk(
48
+ "Note:",
49
+ )} Hot Module Replacement (HMR) not enabled. To enable it, please refer to the instructions in the ${highlightChalk(
50
+ "README.md",
51
+ )}\n`,
52
+ );
53
+ }
54
+
55
+ let cert: Certificate | undefined;
56
+ if (ctx.httpsEnabled) {
57
+ try {
58
+ cert = await createOrRetrieveCertificate();
59
+ } catch (err) {
60
+ console.log(
61
+ errorChalk("Error:"),
62
+ "Unable to generate SSL certificate.",
63
+ );
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ const table = new Table({
69
+ colWidths: [30, 80],
70
+ wordWrap: true,
71
+ wrapOnWordBoundary: true,
72
+ });
73
+
74
+ const server = await this.runWebpackDevServer(ctx, table, cert);
75
+
76
+ await this.maybeRunBackendServer(ctx, table, cert, server);
77
+
78
+ await this.generateAndOpenPreviewUrl(ctx.openPreview, table);
79
+
80
+ console.log(table.toString(), "\n");
81
+
82
+ console.log(
83
+ `${infoChalk(
84
+ "Note:",
85
+ )} For instructions on how to set up the app via the Developer Portal, see the ${highlightChalk(
86
+ "README.md",
87
+ )}.\n`,
88
+ );
89
+ }
90
+
91
+ private readonly maybeRunBackendServer = async (
92
+ ctx: Context,
93
+ table: Table.Table,
94
+ cert: Certificate | undefined,
95
+ webpackDevServer: WebpackDevServer,
96
+ ) => {
97
+ if (!ctx.developerBackendEntryPath) {
98
+ return;
99
+ }
100
+
101
+ // App ID must be set when running a backend example
102
+ if (!ctx.appId) {
103
+ console.log(
104
+ errorChalk("Error:"),
105
+ `'CANVA_APP_ID' environment variable is undefined. Refer to the instructions in the ${highlightChalk(
106
+ "README.md",
107
+ )} on starting a backend example.`,
108
+ );
109
+ throw new Error("'CANVA_APP_ID' env variable not set.");
110
+ }
111
+
112
+ await new Promise((resolve) => {
113
+ const nodemonServer = nodemon({
114
+ script: ctx.developerBackendEntryPath,
115
+ ext: "ts",
116
+ env: {
117
+ SHOULD_ENABLE_HTTPS: ctx.httpsEnabled,
118
+ HTTPS_CERT_FILE: cert?.certFile || "",
119
+ HTTPS_KEY_FILE: cert?.keyFile || "",
120
+ },
121
+ });
122
+
123
+ nodemonServer.on("start", resolve);
124
+
125
+ nodemonServer.on("crash", async () => {
126
+ console.log(errorChalk("Shutting down local server.\n"));
127
+
128
+ await webpackDevServer.stop();
129
+ process.exit(1);
130
+ });
131
+ });
132
+
133
+ if (ctx.ngrokEnabled) {
134
+ console.log(
135
+ warnChalk("Warning:"),
136
+ `ngrok exposes a local port via a public URL. Be mindful of what's exposed and shut down the server when it's not in use.\n`,
137
+ );
138
+ }
139
+
140
+ let url = ctx.backendUrl;
141
+ if (ctx.ngrokEnabled) {
142
+ try {
143
+ const ngrokListener = await ngrok.forward({
144
+ addr: ctx.backendPort,
145
+ // requires an `NGROK_AUTHTOKEN` env var to be set
146
+ authtoken_from_env: true,
147
+ });
148
+ url = ngrokListener.url() ?? url;
149
+ } catch (err) {
150
+ console.log(
151
+ errorChalk("Error:"),
152
+ `Unable to start ngrok server: ${err}`,
153
+ );
154
+ }
155
+ }
156
+
157
+ table.push(["Base URL (Backend)", linkChalk(url)]);
158
+ };
159
+
160
+ private readonly runWebpackDevServer = async (
161
+ ctx: Context,
162
+ table: Table.Table,
163
+ cert: Certificate | undefined,
164
+ ): Promise<WebpackDevServer> => {
165
+ const runtimeWebpackConfig = buildConfig({
166
+ appEntry: ctx.frontendEntryPath,
167
+ backendHost: ctx.backendHost,
168
+ devConfig: {
169
+ port: ctx.frontendPort,
170
+ enableHmr: ctx.hmrEnabled,
171
+ appId: ctx.appId,
172
+ appOrigin: ctx.appOrigin,
173
+ enableHttps: ctx.httpsEnabled,
174
+ ...cert,
175
+ },
176
+ });
177
+
178
+ const compiler = webpack(runtimeWebpackConfig);
179
+ const server = new WebpackDevServer(
180
+ runtimeWebpackConfig.devServer,
181
+ compiler,
182
+ );
183
+ await server.start();
184
+
185
+ table.push(["Development URL (Frontend)", linkChalk(ctx.frontendUrl)]);
186
+
187
+ return server;
188
+ };
189
+
190
+ /**
191
+ * Calls the Canva CLI to generate a preview URL for the app
192
+ */
193
+ private readonly generateAndOpenPreviewUrl = async (
194
+ openPreview: boolean,
195
+ table: Table.Table,
196
+ ) => {
197
+ const previewCellHeader = { content: "Preview your app in Canva" };
198
+
199
+ const generatePreviewResult = await generatePreviewUrl();
200
+
201
+ if (!generatePreviewResult.success) {
202
+ table.push([
203
+ previewCellHeader,
204
+ { content: warnChalk(generatePreviewResult.message) },
205
+ ]);
206
+ return;
207
+ }
208
+
209
+ const modifierKey = getModifierKey();
210
+
211
+ table.push([
212
+ previewCellHeader,
213
+ {
214
+ content: `Preview URL (${modifierKey} + click)`,
215
+ href: generatePreviewResult.data,
216
+ },
217
+ ]);
218
+
219
+ if (openPreview) {
220
+ open(generatePreviewResult.data);
221
+ }
222
+ };
223
+ }