@canva/cli 0.0.1-beta.2 → 0.0.1-beta.21

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 (97) hide show
  1. package/README.md +203 -106
  2. package/cli.js +467 -394
  3. package/lib/cjs/index.cjs +388 -0
  4. package/lib/esm/index.mjs +388 -0
  5. package/package.json +12 -3
  6. package/templates/base/backend/routers/oauth.ts +393 -0
  7. package/templates/base/eslint.config.mjs +2 -4
  8. package/templates/base/package.json +31 -25
  9. package/templates/base/scripts/copy_env.ts +10 -0
  10. package/templates/base/scripts/start/app_runner.ts +39 -2
  11. package/templates/base/scripts/start/context.ts +12 -6
  12. package/templates/base/scripts/start/start.ts +11 -0
  13. package/templates/base/scripts/start/tests/start.tests.ts +61 -0
  14. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  15. package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
  16. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  17. package/templates/base/utils/use_add_element.ts +48 -0
  18. package/templates/base/utils/use_feature_support.ts +28 -0
  19. package/templates/base/{webpack.config.cjs → webpack.config.ts} +34 -42
  20. package/templates/common/.gitignore.template +5 -6
  21. package/templates/common/.nvmrc +1 -0
  22. package/templates/common/.prettierrc +21 -0
  23. package/templates/common/.vscode/extensions.json +6 -0
  24. package/templates/common/README.md +4 -74
  25. package/templates/common/conf/eslint-local-i18n-rules/index.mjs +181 -0
  26. package/templates/common/conf/{eslint-general.mjs → eslint_general.mjs} +40 -0
  27. package/templates/common/conf/eslint_i18n.mjs +41 -0
  28. package/templates/common/jest.config.mjs +29 -2
  29. package/templates/common/jest.setup.ts +20 -0
  30. package/templates/common/utils/backend/base_backend/create.ts +104 -0
  31. package/templates/common/utils/table_wrapper.ts +477 -0
  32. package/templates/common/utils/tests/table_wrapper.tests.ts +252 -0
  33. package/templates/common/utils/use_add_element.ts +48 -0
  34. package/templates/common/utils/use_feature_support.ts +28 -0
  35. package/templates/common/utils/use_overlay_hook.ts +74 -0
  36. package/templates/common/utils/use_selection_hook.ts +37 -0
  37. package/templates/dam/backend/routers/dam.ts +17 -12
  38. package/templates/dam/backend/server.ts +0 -7
  39. package/templates/dam/eslint.config.mjs +2 -2
  40. package/templates/dam/package.json +51 -39
  41. package/templates/dam/scripts/copy_env.ts +10 -0
  42. package/templates/dam/scripts/start/app_runner.ts +39 -2
  43. package/templates/dam/scripts/start/context.ts +12 -6
  44. package/templates/dam/scripts/start/start.ts +11 -0
  45. package/templates/dam/scripts/start/tests/start.tests.ts +61 -0
  46. package/templates/dam/src/app.tsx +26 -138
  47. package/templates/dam/src/config.ts +209 -87
  48. package/templates/{hello_world/webpack.config.cjs → dam/webpack.config.ts} +34 -42
  49. package/templates/gen_ai/README.md +1 -1
  50. package/templates/gen_ai/backend/routers/image.ts +3 -3
  51. package/templates/gen_ai/backend/server.ts +0 -7
  52. package/templates/gen_ai/eslint.config.mjs +2 -4
  53. package/templates/gen_ai/package.json +56 -42
  54. package/templates/gen_ai/scripts/copy_env.ts +10 -0
  55. package/templates/gen_ai/scripts/start/app_runner.ts +39 -2
  56. package/templates/gen_ai/scripts/start/context.ts +12 -6
  57. package/templates/gen_ai/scripts/start/start.ts +11 -0
  58. package/templates/gen_ai/scripts/start/tests/start.tests.ts +61 -0
  59. package/templates/gen_ai/src/api/api.ts +1 -39
  60. package/templates/gen_ai/src/app.tsx +16 -10
  61. package/templates/gen_ai/src/components/footer.messages.ts +0 -5
  62. package/templates/gen_ai/src/components/footer.tsx +2 -16
  63. package/templates/gen_ai/src/components/image_grid.tsx +8 -6
  64. package/templates/gen_ai/src/components/index.ts +0 -1
  65. package/templates/gen_ai/src/components/tests/remaining_credit.tests.tsx +43 -0
  66. package/templates/gen_ai/src/context/app_context.tsx +4 -26
  67. package/templates/gen_ai/src/context/context.messages.ts +1 -12
  68. package/templates/gen_ai/src/home.tsx +13 -0
  69. package/templates/gen_ai/src/index.tsx +2 -18
  70. package/templates/gen_ai/src/routes/routes.tsx +2 -2
  71. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  72. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
  73. package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  74. package/templates/gen_ai/{webpack.config.cjs → webpack.config.ts} +34 -42
  75. package/templates/hello_world/eslint.config.mjs +2 -4
  76. package/templates/hello_world/package.json +55 -33
  77. package/templates/hello_world/scripts/copy_env.ts +10 -0
  78. package/templates/hello_world/scripts/start/app_runner.ts +39 -2
  79. package/templates/hello_world/scripts/start/context.ts +12 -6
  80. package/templates/hello_world/scripts/start/start.ts +11 -0
  81. package/templates/hello_world/scripts/start/tests/start.tests.ts +61 -0
  82. package/templates/hello_world/src/app.tsx +24 -2
  83. package/templates/hello_world/src/tests/__snapshots__/app.tests.tsx.snap +45 -0
  84. package/templates/hello_world/src/tests/app.tests.tsx +86 -0
  85. package/templates/hello_world/utils/use_add_element.ts +48 -0
  86. package/templates/hello_world/utils/use_feature_support.ts +28 -0
  87. package/templates/{dam/webpack.config.cjs → hello_world/webpack.config.ts} +34 -42
  88. package/templates/common/conf/eslint-i18n.mjs +0 -23
  89. package/templates/dam/backend/database/database.ts +0 -42
  90. package/templates/dam/backend/routers/auth.ts +0 -285
  91. package/templates/gen_ai/backend/routers/auth.ts +0 -285
  92. package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
  93. package/templates/gen_ai/src/services/auth.tsx +0 -31
  94. package/templates/gen_ai/src/services/index.ts +0 -1
  95. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/index.ts +0 -0
  96. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/jwt_middleware.ts +0 -0
  97. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -0
@@ -63,18 +63,15 @@ To preview apps in Safari:
63
63
  1. Start the development server with HTTPS enabled:
64
64
 
65
65
  ```bash
66
- # Run the main app
67
66
  npm start --use-https
68
-
69
- # Run an example
70
- npm start <example-name> --use-https
71
67
  ```
72
68
 
73
69
  2. Navigate to <https://localhost:8080>.
74
70
  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>.
71
+ 1. Click **Show details**.
72
+ 2. Click **Visit website**.
73
+ 4. In the Developer Portal, set the app's **Development URL** to <https://localhost:8080>.
74
+ 5. Click preview (or refresh your app if it's already open).
78
75
 
79
76
  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
77
 
@@ -181,70 +178,3 @@ To use ngrok, you'll need to do the following:
181
178
  ```
182
179
 
183
180
  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,181 @@
1
+ /**
2
+ * ESLint rule that identifies and flags untranslated user-facing strings in object properties.
3
+ *
4
+ * This rule helps maintain internationalization consistency by detecting untranslated
5
+ * strings in specific object properties (default: 'label'). It suggests using
6
+ * intl.formatMessage for proper translation.
7
+ *
8
+ * Note: The rule is currently implemented as a local rule, with plans to publish as
9
+ * an npm package to make it available to the broader development community.
10
+ *
11
+ * @example
12
+ * // ❌ Incorrect - Untranslated strings
13
+ * const options = [
14
+ * { value: "inbox", label: "Inbox" },
15
+ * { value: "starred", label: "Starred messages" },
16
+ * { value: "spam", label: "Spam folder" }
17
+ * ];
18
+ *
19
+ * // ✅ Correct - Using intl.formatMessage with descriptions
20
+ * const options = [
21
+ * {
22
+ * value: "inbox",
23
+ * label: intl.formatMessage({
24
+ * defaultMessage: "Inbox",
25
+ * description: "Label for main message inbox folder option"
26
+ * })
27
+ * },
28
+ * {
29
+ * value: "starred",
30
+ * label: intl.formatMessage({
31
+ * defaultMessage: "Starred messages",
32
+ * description: "Label for folder containing messages marked as important"
33
+ * })
34
+ * },
35
+ * {
36
+ * value: "spam",
37
+ * label: intl.formatMessage({
38
+ * defaultMessage: "Spam folder",
39
+ * description: "Label for folder containing filtered spam messages"
40
+ * })
41
+ * }
42
+ * ];
43
+ *
44
+ * @see https://www.canva.dev/docs/apps/localization/
45
+ */
46
+ export default {
47
+ rules: {
48
+ "enforce-object-property-translation": {
49
+ meta: {
50
+ type: "problem",
51
+ docs: {
52
+ description:
53
+ "Enforce translation of specific properties using intl.formatMessage",
54
+ category: "Possible Errors",
55
+ recommended: true,
56
+ },
57
+ fixable: "code",
58
+ schema: [
59
+ {
60
+ type: "object",
61
+ properties: {
62
+ properties: {
63
+ type: "array",
64
+ items: { type: "string" },
65
+ default: ["label"],
66
+ },
67
+ intlObjectName: {
68
+ type: "string",
69
+ default: "intl",
70
+ },
71
+ },
72
+ additionalProperties: false,
73
+ },
74
+ ],
75
+ messages: {
76
+ untranslatedProperty: `If "{{ originalMessage }}" is a user-facing string, you should translate it using "intl.formatMessage". See https://www.canva.dev/docs/apps/localization/.`,
77
+ },
78
+ },
79
+ create(context) {
80
+ const config = context.options[0] || {};
81
+ const propertiesToCheck = config.properties || ["label"];
82
+ const intlObjectName = config.intlObjectName || "intl";
83
+
84
+ function getTemplateLiteralString(node) {
85
+ const src = context.getSourceCode();
86
+ return src.getText(node);
87
+ }
88
+
89
+ // Extract string content from different node types
90
+ function extractStringContent(node) {
91
+ if (!node) return [];
92
+
93
+ switch (node.type) {
94
+ // label: "Foo"
95
+ case "Literal":
96
+ return typeof node.value === "string"
97
+ ? [{ node, value: node.value }]
98
+ : [];
99
+
100
+ // label: `Foo ${bar}`
101
+ case "TemplateLiteral":
102
+ return [{ node, value: getTemplateLiteralString(node) }];
103
+ // label: foo || "Bar"
104
+ case "LogicalExpression": {
105
+ if (node.operator === "||") {
106
+ return [
107
+ ...extractStringContent(node.left),
108
+ ...extractStringContent(node.right),
109
+ ];
110
+ }
111
+ return [];
112
+ }
113
+ // label: "Foo" + "Bar" + "Baz"
114
+ case "BinaryExpression":
115
+ if (node.operator === "+") {
116
+ return [
117
+ ...extractStringContent(node.left),
118
+ ...extractStringContent(node.right),
119
+ ];
120
+ }
121
+ return [];
122
+ // label: foo ? "Foo" : "Bar"
123
+ case "ConditionalExpression":
124
+ return [
125
+ ...extractStringContent(node.consequent),
126
+ ...extractStringContent(node.alternate),
127
+ ];
128
+
129
+ default:
130
+ return [];
131
+ }
132
+ }
133
+
134
+ function isTranslated(node) {
135
+ return (
136
+ node.parent.type === "CallExpression" &&
137
+ node.parent.callee.type === "MemberExpression" &&
138
+ node.parent.callee.object.name === intlObjectName &&
139
+ node.parent.callee.property.name === "formatMessage"
140
+ );
141
+ }
142
+
143
+ return {
144
+ Property(node) {
145
+ const keyName = node.key.name || node.key.value;
146
+ if (propertiesToCheck.includes(keyName)) {
147
+ const results = extractStringContent(node.value);
148
+ if (!results) return;
149
+ results.forEach((result) => {
150
+ const { node: stringNode, value: stringValue } = result;
151
+
152
+ if (!isTranslated(stringNode)) {
153
+ context.report({
154
+ node: stringNode,
155
+ messageId: "untranslatedProperty",
156
+ data: {
157
+ property: keyName,
158
+ originalMessage:
159
+ stringValue.length > 40
160
+ ? stringValue.split(" ").slice(0, 4).join(" ") + "..."
161
+ : stringValue,
162
+ intlObjectName,
163
+ },
164
+ fix(fixer) {
165
+ const newText = `${intlObjectName}.formatMessage({
166
+ defaultMessage: ${JSON.stringify(stringValue)},
167
+ // TODO: Provide a meaningful description for translators
168
+ description: ""
169
+ })`;
170
+ return fixer.replaceText(stringNode, newText);
171
+ },
172
+ });
173
+ }
174
+ });
175
+ }
176
+ },
177
+ };
178
+ },
179
+ },
180
+ },
181
+ };
@@ -2,6 +2,7 @@ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
2
  import jest from "eslint-plugin-jest";
3
3
  import react from "eslint-plugin-react";
4
4
  import globals from "globals";
5
+ import eslintPluginUnicorn from "eslint-plugin-unicorn";
5
6
 
6
7
  export default [
7
8
  {
@@ -9,6 +10,7 @@ export default [
9
10
  "@typescript-eslint": typescriptEslint,
10
11
  jest,
11
12
  react,
13
+ unicorn: eslintPluginUnicorn,
12
14
  },
13
15
  languageOptions: {
14
16
  globals: {
@@ -178,6 +180,38 @@ export default [
178
180
  message:
179
181
  "Apps are currently not allowed to open popups, or new tabs via browser APIs. Please use `requestOpenExternalUrl` from `@canva/platform` to link to external URLs. To learn more, see https://www.canva.dev/docs/apps/api/platform-request-open-external-url/",
180
182
  },
183
+ {
184
+ selector:
185
+ "MemberExpression[object.name='localStorage'], MemberExpression[object.name='sessionStorage']",
186
+ message:
187
+ "Using `localStorage` or `sessionStorage` may not be appropriate for certain types of data, such as sensitive information. If your use case is safe and does not involve storing sensitive data (e.g., access tokens or keys), you can ignore this warning with an eslint-disable comment. Otherwise, seek secure storage alternatives. For more details, refer to the Canva Security Guidelines (https://www.canva.dev/docs/apps/security-guidelines/#store-secrets-securely).",
188
+ },
189
+ ],
190
+ "no-restricted-imports": [
191
+ "warn",
192
+ {
193
+ // Warn when importing static assets that increase bundle size
194
+ patterns: [
195
+ // Images
196
+ {
197
+ group: ["*.png", "*.jpg", "*.jpeg", "*.gif"],
198
+ message:
199
+ "Inline images increase app bundle size and degrade app performance. Wherever possible, please use a CDN or external hosting service to dynamically load assets.",
200
+ },
201
+ // Videos
202
+ {
203
+ group: ["*.mp4", "*.webm", "*.ogg"],
204
+ message:
205
+ "Inline videos increase app bundle size and degrade app performance. Wherever possible, please use a CDN or external hosting service to dynamically load assets.",
206
+ },
207
+ // Audio
208
+ {
209
+ group: ["*.mp3", "*.wav", "*.ogg"],
210
+ message:
211
+ "Inline audio files increase app bundle size and degrade app performance. Wherever possible, please use a CDN or external hosting service to dynamically load assets.",
212
+ },
213
+ ],
214
+ },
181
215
  ],
182
216
  "no-return-await": "error",
183
217
  "no-throw-literal": "error",
@@ -194,6 +228,12 @@ export default [
194
228
  "prefer-rest-params": "error",
195
229
  "prefer-spread": "error",
196
230
  radix: "error",
231
+ "unicorn/filename-case": [
232
+ "error",
233
+ {
234
+ case: "snakeCase",
235
+ },
236
+ ],
197
237
  },
198
238
  },
199
239
  {
@@ -0,0 +1,41 @@
1
+ import formatjs from "eslint-plugin-formatjs";
2
+ import eslintLocalI18nRules from "./eslint-local-i18n-rules/index.mjs";
3
+
4
+ export default [
5
+ {
6
+ plugins: {
7
+ formatjs,
8
+ "local-i18n-rules": eslintLocalI18nRules,
9
+ },
10
+ rules: {
11
+ "formatjs/no-invalid-icu": "error",
12
+ "formatjs/no-literal-string-in-jsx": [
13
+ 2,
14
+ {
15
+ props: {
16
+ // These rules are for @canva/app-ui-kit components.
17
+ // For your own components, suppress any false positives using eslint ignore comments.
18
+ include: [
19
+ ["*", "(*Label|label|alt)"],
20
+ ["*", "(title|description|name|text)"],
21
+ ["*", "(placeholder|additionalPlaceholder|defaultValue)"],
22
+ ["FormField", "error"],
23
+ ],
24
+ exclude: [["FormattedMessage", "description"]],
25
+ },
26
+ },
27
+ ],
28
+ "formatjs/enforce-description": ["error", "literal"],
29
+ "formatjs/enforce-default-message": ["error", "literal"],
30
+ "formatjs/enforce-placeholders": "error",
31
+ "formatjs/no-id": "error",
32
+ "formatjs/no-emoji": "error",
33
+ "formatjs/no-useless-message": "error",
34
+ "formatjs/no-multiple-plurals": "error",
35
+ "formatjs/no-offset": "error",
36
+ "formatjs/blocklist-elements": [2, ["selectordinal"]],
37
+ "formatjs/no-complex-selectors": "error",
38
+ "local-i18n-rules/enforce-object-property-translation": ["warn"],
39
+ },
40
+ },
41
+ ];
@@ -1,8 +1,35 @@
1
+ import { pathsToModuleNameMapper } from "ts-jest";
2
+ import tsconfig from "./tsconfig.json" assert { type: "json" };
3
+
4
+ const { compilerOptions } = tsconfig;
5
+
1
6
  /** @type {import('ts-jest').JestConfigWithTsJest} */
2
7
 
3
8
  export default {
4
9
  preset: "ts-jest",
5
- testEnvironment: "node",
6
- testRegex: "(/tests/.*|(\\.|/)(tests))\\.ts?$",
10
+ testEnvironment: "jsdom",
11
+ testRegex: "(/tests/.*|(\\.|/)(tests))\\.tsx?$",
7
12
  modulePathIgnorePatterns: ["./internal/", "./node_modules/"],
13
+ modulePaths: [compilerOptions.baseUrl],
14
+ moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
15
+ transform: {
16
+ ".+\\.(css)$": "jest-css-modules-transform",
17
+ "^.+\\.tsx?$": [
18
+ "ts-jest",
19
+ {
20
+ astTransformers: {
21
+ before: [
22
+ {
23
+ path: "@formatjs/ts-transformer/ts-jest-integration",
24
+ options: {
25
+ overrideIdFn: "[sha512:contenthash:base64:6]",
26
+ ast: true,
27
+ },
28
+ },
29
+ ],
30
+ },
31
+ },
32
+ ],
33
+ },
34
+ setupFiles: ["<rootDir>/jest.setup.ts"],
8
35
  };
@@ -0,0 +1,20 @@
1
+ // Import testing sub-packages
2
+ import * as asset from "@canva/asset/test";
3
+ import * as design from "@canva/design/test";
4
+ import * as error from "@canva/error/test";
5
+ import * as platform from "@canva/platform/test";
6
+ import * as user from "@canva/user/test";
7
+
8
+ // Initialize the test environments
9
+ asset.initTestEnvironment();
10
+ design.initTestEnvironment();
11
+ error.initTestEnvironment();
12
+ platform.initTestEnvironment();
13
+ user.initTestEnvironment();
14
+
15
+ // Once they're initialized, mock the SDKs
16
+ jest.mock("@canva/asset");
17
+ jest.mock("@canva/design");
18
+ jest.mock("@canva/platform");
19
+ jest.mock("@canva/user");
20
+ // n.b. @canva/error should not be mocked - use it to simulate API error responses from other mocks by throwing CanvaError
@@ -0,0 +1,104 @@
1
+ /* eslint-disable no-console */
2
+ import * as express from "express";
3
+ import * as http from "http";
4
+ import * as https from "https";
5
+ import * as fs from "fs";
6
+ import type { Request, Response, NextFunction } from "express";
7
+ import debug from "debug";
8
+
9
+ const serverDebug = debug("server");
10
+
11
+ interface BaseServer {
12
+ app: express.Express;
13
+
14
+ /**
15
+ * Starts the server on the address or port provided
16
+ * @param address port number or string address or if left undefined express defaults to port 3000
17
+ */
18
+ start: (address: number | string | undefined) => void;
19
+ }
20
+
21
+ /**
22
+ * createBaseServer instantiates a customised express server with:
23
+ * - json body handling
24
+ * - health check endpoint
25
+ * - catchall endpoint
26
+ * - error handler catch route
27
+ * - process termination handling
28
+ * - debug logging - prefix starting your server with `DEBUG=server npm run XXX`
29
+ *
30
+ * @returns BaseServer object containing the express app and a start function
31
+ */
32
+ export function createBaseServer(router: express.Router): BaseServer {
33
+ const SHOULD_ENABLE_HTTPS = process.env?.SHOULD_ENABLE_HTTPS === "true";
34
+ const HTTPS_CERT_FILE = process.env?.HTTPS_CERT_FILE;
35
+ const HTTPS_KEY_FILE = process.env?.HTTPS_KEY_FILE;
36
+
37
+ const app = express();
38
+ app.use(express.json());
39
+
40
+ // It can help to provide an extra layer of obsecurity to reduce server fingerprinting.
41
+ app.disable("x-powered-by");
42
+
43
+ // Health check endpoint
44
+ app.get("/healthz", (req, res: Response) => {
45
+ res.sendStatus(200);
46
+ });
47
+
48
+ // logging middleware
49
+ app.use((req: Request, res: Response, next: NextFunction) => {
50
+ serverDebug(`${new Date().toISOString()}: ${req.method} ${req.url}`);
51
+ next();
52
+ });
53
+
54
+ // Custom routes router
55
+ app.use(router);
56
+
57
+ // catch all router
58
+ app.all("*", (req, res) => {
59
+ res.status(404).send({
60
+ error: `unhandled '${req.method}' on '${req.url}'`,
61
+ });
62
+ });
63
+
64
+ // default error handler
65
+ app.use((err, req, res, next) => {
66
+ console.error(err.stack);
67
+ res.status(500).send({
68
+ error: "something went wrong",
69
+ });
70
+ });
71
+
72
+ let server;
73
+ if (SHOULD_ENABLE_HTTPS) {
74
+ if (!HTTPS_CERT_FILE || !HTTPS_KEY_FILE) {
75
+ throw new Error(
76
+ "Looks like you're running the example with --use-https flag, but SSL certificates haven't been generated. Please remove the .ssl/ folder and re-run the command again.",
77
+ );
78
+ }
79
+
80
+ server = https.createServer(
81
+ {
82
+ key: fs.readFileSync(HTTPS_KEY_FILE),
83
+ cert: fs.readFileSync(HTTPS_CERT_FILE),
84
+ },
85
+ app,
86
+ );
87
+ } else {
88
+ server = http.createServer(app);
89
+ }
90
+
91
+ return {
92
+ app,
93
+ start: (address: number | string | undefined) => {
94
+ console.log(`Listening on '${address}'`);
95
+ server.listen(address);
96
+ process.on("SIGTERM", () => {
97
+ serverDebug("SIGTERM signal received: closing HTTP server");
98
+ server.close(() => {
99
+ serverDebug("HTTP server closed");
100
+ });
101
+ });
102
+ },
103
+ };
104
+ }