@canva/cli 0.0.1-beta.1 → 0.0.1-beta.10

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 (79) hide show
  1. package/README.md +184 -108
  2. package/cli.js +446 -359
  3. package/lib/cjs/index.cjs +392 -0
  4. package/lib/esm/index.esm +392 -0
  5. package/package.json +11 -2
  6. package/templates/base/backend/routers/oauth.ts +393 -0
  7. package/templates/base/eslint.config.mjs +5 -277
  8. package/templates/base/package.json +26 -23
  9. package/templates/base/scripts/copy-env.ts +10 -0
  10. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  11. package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
  12. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  13. package/templates/base/utils/use_add_element.ts +48 -0
  14. package/templates/base/utils/use_feature_support.ts +28 -0
  15. package/templates/base/webpack.config.cjs +3 -1
  16. package/templates/common/.gitignore.template +5 -6
  17. package/templates/common/.nvmrc +1 -0
  18. package/templates/common/.prettierrc +21 -0
  19. package/templates/common/.vscode/extensions.json +6 -0
  20. package/templates/common/README.md +4 -74
  21. package/templates/common/conf/eslint-general.mjs +303 -0
  22. package/templates/common/conf/eslint-i18n.mjs +41 -0
  23. package/templates/common/conf/eslint-local-i18n-rules/index.mjs +181 -0
  24. package/templates/common/jest.config.mjs +29 -2
  25. package/templates/common/jest.setup.ts +19 -0
  26. package/templates/common/utils/backend/base_backend/create.ts +104 -0
  27. package/templates/common/utils/table_wrapper.ts +477 -0
  28. package/templates/common/utils/tests/table_wrapper.tests.ts +252 -0
  29. package/templates/common/utils/use_add_element.ts +48 -0
  30. package/templates/common/utils/use_feature_support.ts +28 -0
  31. package/templates/common/utils/use_overlay_hook.ts +74 -0
  32. package/templates/common/utils/use_selection_hook.ts +37 -0
  33. package/templates/dam/backend/server.ts +0 -7
  34. package/templates/dam/eslint.config.mjs +6 -275
  35. package/templates/dam/package.json +43 -35
  36. package/templates/dam/scripts/copy-env.ts +10 -0
  37. package/templates/dam/src/app.tsx +2 -135
  38. package/templates/dam/webpack.config.cjs +3 -1
  39. package/templates/gen_ai/README.md +1 -1
  40. package/templates/gen_ai/backend/routers/image.ts +3 -3
  41. package/templates/gen_ai/backend/server.ts +0 -7
  42. package/templates/gen_ai/eslint.config.mjs +5 -277
  43. package/templates/gen_ai/package.json +46 -38
  44. package/templates/gen_ai/scripts/copy-env.ts +10 -0
  45. package/templates/gen_ai/src/api/api.ts +1 -39
  46. package/templates/gen_ai/src/app.tsx +16 -10
  47. package/templates/gen_ai/src/components/footer.messages.ts +0 -5
  48. package/templates/gen_ai/src/components/footer.tsx +2 -16
  49. package/templates/gen_ai/src/components/image_grid.tsx +9 -7
  50. package/templates/gen_ai/src/components/index.ts +0 -1
  51. package/templates/gen_ai/src/components/prompt_input.tsx +2 -0
  52. package/templates/gen_ai/src/components/tests/remaining_credit.tests.tsx +43 -0
  53. package/templates/gen_ai/src/context/app_context.tsx +4 -26
  54. package/templates/gen_ai/src/context/context.messages.ts +1 -12
  55. package/templates/gen_ai/src/home.tsx +13 -0
  56. package/templates/gen_ai/src/index.tsx +2 -18
  57. package/templates/gen_ai/src/routes/routes.tsx +2 -2
  58. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  59. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
  60. package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  61. package/templates/gen_ai/webpack.config.cjs +3 -1
  62. package/templates/hello_world/eslint.config.mjs +5 -277
  63. package/templates/hello_world/package.json +46 -28
  64. package/templates/hello_world/scripts/copy-env.ts +10 -0
  65. package/templates/hello_world/src/app.tsx +25 -3
  66. package/templates/hello_world/src/tests/__snapshots__/app.tests.tsx.snap +45 -0
  67. package/templates/hello_world/src/tests/app.tests.tsx +86 -0
  68. package/templates/hello_world/utils/use_add_element.ts +48 -0
  69. package/templates/hello_world/utils/use_feature_support.ts +28 -0
  70. package/templates/hello_world/webpack.config.cjs +3 -1
  71. package/templates/dam/backend/database/database.ts +0 -42
  72. package/templates/dam/backend/routers/auth.ts +0 -285
  73. package/templates/gen_ai/backend/routers/auth.ts +0 -285
  74. package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
  75. package/templates/gen_ai/src/services/auth.tsx +0 -31
  76. package/templates/gen_ai/src/services/index.ts +0 -1
  77. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/index.ts +0 -0
  78. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/jwt_middleware.ts +0 -0
  79. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -0
@@ -0,0 +1,303 @@
1
+ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
+ import jest from "eslint-plugin-jest";
3
+ import react from "eslint-plugin-react";
4
+ import globals from "globals";
5
+
6
+ export default [
7
+ {
8
+ plugins: {
9
+ "@typescript-eslint": typescriptEslint,
10
+ jest,
11
+ react,
12
+ },
13
+ languageOptions: {
14
+ globals: {
15
+ ...globals.serviceworker,
16
+ ...globals.browser,
17
+ },
18
+ },
19
+ settings: {
20
+ react: {
21
+ version: "detect",
22
+ },
23
+ },
24
+ rules: {
25
+ "@typescript-eslint/no-non-null-assertion": "warn",
26
+ "@typescript-eslint/no-empty-function": "off",
27
+ "@typescript-eslint/consistent-type-imports": "error",
28
+ "@typescript-eslint/no-explicit-any": "warn",
29
+ "@typescript-eslint/no-empty-interface": "warn",
30
+ "@typescript-eslint/consistent-type-definitions": "off",
31
+ "@typescript-eslint/explicit-member-accessibility": [
32
+ "error",
33
+ {
34
+ accessibility: "no-public",
35
+ overrides: {
36
+ parameterProperties: "off",
37
+ },
38
+ },
39
+ ],
40
+ "@typescript-eslint/naming-convention": [
41
+ "error",
42
+ {
43
+ selector: "typeLike",
44
+ format: ["PascalCase"],
45
+ leadingUnderscore: "allow",
46
+ },
47
+ ],
48
+ "no-invalid-this": "off",
49
+ "@typescript-eslint/no-invalid-this": "error",
50
+ "@typescript-eslint/no-unused-expressions": [
51
+ "error",
52
+ {
53
+ allowShortCircuit: true,
54
+ allowTernary: true,
55
+ },
56
+ ],
57
+ "no-unused-vars": "off",
58
+ "@typescript-eslint/no-unused-vars": [
59
+ "error",
60
+ {
61
+ vars: "all",
62
+ varsIgnorePattern: "^_",
63
+ args: "none",
64
+ ignoreRestSiblings: true,
65
+ },
66
+ ],
67
+ "@typescript-eslint/no-require-imports": "error",
68
+ "jest/no-restricted-matchers": [
69
+ "error",
70
+ {
71
+ toContainElement:
72
+ "toContainElement is not recommended as it encourages testing the internals of the components",
73
+ toContainHTML:
74
+ "toContainHTML is not recommended as it encourages testing the internals of the components",
75
+ toHaveAttribute:
76
+ "toHaveAttribute is not recommended as it encourages testing the internals of the components",
77
+ toHaveClass:
78
+ "toHaveClass is not recommended as it encourages testing the internals of the components",
79
+ toHaveStyle:
80
+ "toHaveStyle is not recommended as it encourages testing the internals of the components",
81
+ },
82
+ ],
83
+ "react/jsx-curly-brace-presence": [
84
+ "error",
85
+ {
86
+ props: "never",
87
+ children: "never",
88
+ },
89
+ ],
90
+ "react/jsx-tag-spacing": [
91
+ "error",
92
+ {
93
+ closingSlash: "never",
94
+ beforeSelfClosing: "allow",
95
+ afterOpening: "never",
96
+ beforeClosing: "allow",
97
+ },
98
+ ],
99
+ "react/self-closing-comp": "error",
100
+ "react/no-unescaped-entities": "off",
101
+ "react/jsx-uses-react": "off",
102
+ "react/react-in-jsx-scope": "off",
103
+ "default-case": "error",
104
+ eqeqeq: [
105
+ "error",
106
+ "always",
107
+ {
108
+ null: "never",
109
+ },
110
+ ],
111
+ "no-caller": "error",
112
+ "no-console": "error",
113
+ "no-eval": "error",
114
+ "no-inner-declarations": "error",
115
+ "no-new-wrappers": "error",
116
+ "no-restricted-globals": [
117
+ "error",
118
+ {
119
+ name: "fit",
120
+ message: "Don't focus tests",
121
+ },
122
+ {
123
+ name: "fdescribe",
124
+ message: "Don't focus tests",
125
+ },
126
+ {
127
+ name: "length",
128
+ message:
129
+ "Undefined length - Did you mean to use window.length instead?",
130
+ },
131
+ {
132
+ name: "name",
133
+ message: "Undefined name - Did you mean to use window.name instead?",
134
+ },
135
+ {
136
+ name: "status",
137
+ message:
138
+ "Undefined status - Did you mean to use window.status instead?",
139
+ },
140
+ {
141
+ name: "spyOn",
142
+ message: "Don't use spyOn directly, use jest.spyOn",
143
+ },
144
+ ],
145
+ "no-restricted-properties": [
146
+ "error",
147
+ {
148
+ property: "bind",
149
+ message: "Don't o.f.bind(o, ...), use () => o.f(...)",
150
+ },
151
+ {
152
+ object: "ReactDOM",
153
+ property: "findDOMNode",
154
+ message: "Don't use ReactDOM.findDOMNode() as it is deprecated",
155
+ },
156
+ ],
157
+ "no-restricted-syntax": [
158
+ "error",
159
+ {
160
+ selector: "AccessorProperty, TSAbstractAccessorProperty",
161
+ message:
162
+ "Accessor property syntax is not allowed, use getter and setters.",
163
+ },
164
+ {
165
+ selector: "PrivateIdentifier",
166
+ message:
167
+ "Private identifiers are not allowed, use TypeScript private fields.",
168
+ },
169
+ {
170
+ selector:
171
+ "JSXOpeningElement[name.name = /^[A-Z]/] > JSXAttribute[name.name = /-/]",
172
+ message:
173
+ "Passing hyphenated props to custom components is not type-safe. Prefer a camelCased equivalent if available. (See https://github.com/microsoft/TypeScript/issues/55182)",
174
+ },
175
+ {
176
+ selector:
177
+ "CallExpression[callee.object.name='window'][callee.property.name='open']",
178
+ message:
179
+ "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
+ },
181
+ ],
182
+ "no-restricted-imports": [
183
+ "warn",
184
+ {
185
+ // Warn when importing static assets that increase bundle size
186
+ patterns: [
187
+ // Images
188
+ {
189
+ group: ["*.png", "*.jpg", "*.jpeg", "*.gif"],
190
+ message:
191
+ "Inline images increase app bundle size and degrade app performance. Wherever possible, please use a CDN or external hosting service to dynamically load assets.",
192
+ },
193
+ // Videos
194
+ {
195
+ group: ["*.mp4", "*.webm", "*.ogg"],
196
+ message:
197
+ "Inline videos increase app bundle size and degrade app performance. Wherever possible, please use a CDN or external hosting service to dynamically load assets.",
198
+ },
199
+ // Audio
200
+ {
201
+ group: ["*.mp3", "*.wav", "*.ogg"],
202
+ message:
203
+ "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.",
204
+ },
205
+ ],
206
+ },
207
+ ],
208
+ "no-return-await": "error",
209
+ "no-throw-literal": "error",
210
+ "no-undef-init": "error",
211
+ "no-var": "error",
212
+ "object-shorthand": "error",
213
+ "prefer-const": [
214
+ "error",
215
+ {
216
+ destructuring: "all",
217
+ },
218
+ ],
219
+ "prefer-object-spread": "error",
220
+ "prefer-rest-params": "error",
221
+ "prefer-spread": "error",
222
+ radix: "error",
223
+ },
224
+ },
225
+ {
226
+ files: ["**/*.tsx"],
227
+ rules: {
228
+ "react/no-deprecated": "error",
229
+ "react/forbid-elements": [
230
+ "error",
231
+ {
232
+ forbid: [
233
+ {
234
+ element: "video",
235
+ message:
236
+ "Don't use HTML video directly. Instead, use the App UI Kit <VideoCard /> as this respects users' auto-playing preferences",
237
+ },
238
+ {
239
+ element: "em",
240
+ message:
241
+ "Don't use <em> to italicize text. Canva's UI fonts don't support italic font style.",
242
+ },
243
+ {
244
+ element: "i",
245
+ message:
246
+ "Don't use <i> to italicize text. Canva's UI fonts don't support italic font style.",
247
+ },
248
+ {
249
+ element: "iframe",
250
+ message:
251
+ "Canva Apps aren't allowed to contain iframes. You should either recreate the UI you want to show in the iframe in the app directly, or link to your page via a `<Link>` tag. For more info see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
252
+ },
253
+ {
254
+ element: "script",
255
+ message:
256
+ "Script tags are not allowed in Canva SDK Apps. You should import JavaScript modules instead. For more info see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
257
+ },
258
+ {
259
+ element: "a",
260
+ message:
261
+ "Don't use <a> tags. Instead, use the <Link> component from the App UI Kit, and remember to open the url via the requestOpenExternalUrl method from @canva/platform.",
262
+ },
263
+ {
264
+ element: "img",
265
+ message:
266
+ "Have you considered using <ImageCard /> from the App UI Kit instead?",
267
+ },
268
+ {
269
+ element: "embed",
270
+ message:
271
+ "Have you considered using <EmbedCard /> from the App UI Kit instead?",
272
+ },
273
+ {
274
+ element: "audio",
275
+ message:
276
+ "Have you considered using <AudioCard /> from the App UI Kit instead?",
277
+ },
278
+ {
279
+ element: "button",
280
+ message:
281
+ "Rather than using the native HTML <button> element, use the <Button> component from the App UI Kit for consistency and accessibility.",
282
+ },
283
+ {
284
+ element: "input",
285
+ message:
286
+ "Wherever possible, prefer using the form inputs from the App UI Kit for consistency and accessibility (TextInput, Checkbox, FileInput, etc).",
287
+ },
288
+ {
289
+ element: "base",
290
+ message:
291
+ "The <base> tag is not supported in Canva Apps. We recommend using hash-based routing. For more on what is and isn't allowed in Canva Apps see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
292
+ },
293
+ {
294
+ element: "link",
295
+ message:
296
+ "If you're trying to include a css stylesheet, we recommend importing css using React, or using embedded stylesheets. For more on what is and isn't allowed in Canva Apps see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
297
+ },
298
+ ],
299
+ },
300
+ ],
301
+ },
302
+ },
303
+ ];
@@ -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
+ ];
@@ -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
+ };
@@ -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,19 @@
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");
@@ -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
+ }