@friggframework/devtools 2.0.0--canary.517.35ee143.0 → 2.0.0--canary.524.06156322a.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 (147) hide show
  1. package/infrastructure/domains/shared/types/app-definition.js +0 -21
  2. package/infrastructure/domains/shared/utilities/base-definition-factory.js +15 -1
  3. package/infrastructure/infrastructure-composer.js +0 -2
  4. package/package.json +15 -7
  5. package/.eslintrc.json +0 -3
  6. package/CHANGELOG.md +0 -132
  7. package/infrastructure/domains/admin-scripts/admin-script-builder.js +0 -200
  8. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +0 -499
  9. package/infrastructure/domains/admin-scripts/index.js +0 -5
  10. package/layers/prisma/.build-complete +0 -3
  11. package/layers/prisma/nodejs/package.json +0 -8
  12. package/management-ui/.eslintrc.js +0 -22
  13. package/management-ui/components.json +0 -21
  14. package/management-ui/docs/phase2-integration-guide.md +0 -320
  15. package/management-ui/index.html +0 -13
  16. package/management-ui/package.json +0 -76
  17. package/management-ui/packages/devtools/frigg-cli/ui-command/index.js +0 -302
  18. package/management-ui/postcss.config.js +0 -6
  19. package/management-ui/server/api/backend.js +0 -256
  20. package/management-ui/server/api/cli.js +0 -315
  21. package/management-ui/server/api/codegen.js +0 -663
  22. package/management-ui/server/api/connections.js +0 -857
  23. package/management-ui/server/api/discovery.js +0 -185
  24. package/management-ui/server/api/environment/index.js +0 -1
  25. package/management-ui/server/api/environment/router.js +0 -378
  26. package/management-ui/server/api/environment.js +0 -328
  27. package/management-ui/server/api/integrations.js +0 -876
  28. package/management-ui/server/api/logs.js +0 -248
  29. package/management-ui/server/api/monitoring.js +0 -282
  30. package/management-ui/server/api/open-ide.js +0 -31
  31. package/management-ui/server/api/project.js +0 -1029
  32. package/management-ui/server/api/users/sessions.js +0 -371
  33. package/management-ui/server/api/users/simulation.js +0 -254
  34. package/management-ui/server/api/users.js +0 -362
  35. package/management-ui/server/api-contract.md +0 -275
  36. package/management-ui/server/index.js +0 -873
  37. package/management-ui/server/middleware/errorHandler.js +0 -93
  38. package/management-ui/server/middleware/security.js +0 -32
  39. package/management-ui/server/processManager.js +0 -296
  40. package/management-ui/server/server.js +0 -346
  41. package/management-ui/server/services/aws-monitor.js +0 -413
  42. package/management-ui/server/services/npm-registry.js +0 -347
  43. package/management-ui/server/services/template-engine.js +0 -538
  44. package/management-ui/server/utils/cliIntegration.js +0 -220
  45. package/management-ui/server/utils/environment/auditLogger.js +0 -471
  46. package/management-ui/server/utils/environment/awsParameterStore.js +0 -275
  47. package/management-ui/server/utils/environment/encryption.js +0 -278
  48. package/management-ui/server/utils/environment/envFileManager.js +0 -286
  49. package/management-ui/server/utils/import-commonjs.js +0 -28
  50. package/management-ui/server/utils/response.js +0 -83
  51. package/management-ui/server/websocket/handler.js +0 -325
  52. package/management-ui/src/App.jsx +0 -25
  53. package/management-ui/src/assets/FriggLogo.svg +0 -1
  54. package/management-ui/src/components/AppRouter.jsx +0 -65
  55. package/management-ui/src/components/Button.jsx +0 -70
  56. package/management-ui/src/components/Card.jsx +0 -97
  57. package/management-ui/src/components/EnvironmentCompare.jsx +0 -400
  58. package/management-ui/src/components/EnvironmentEditor.jsx +0 -372
  59. package/management-ui/src/components/EnvironmentImportExport.jsx +0 -469
  60. package/management-ui/src/components/EnvironmentSchema.jsx +0 -491
  61. package/management-ui/src/components/EnvironmentSecurity.jsx +0 -463
  62. package/management-ui/src/components/ErrorBoundary.jsx +0 -73
  63. package/management-ui/src/components/IntegrationCard.jsx +0 -481
  64. package/management-ui/src/components/IntegrationCardEnhanced.jsx +0 -770
  65. package/management-ui/src/components/IntegrationExplorer.jsx +0 -379
  66. package/management-ui/src/components/IntegrationStatus.jsx +0 -336
  67. package/management-ui/src/components/Layout.jsx +0 -716
  68. package/management-ui/src/components/LoadingSpinner.jsx +0 -113
  69. package/management-ui/src/components/RepositoryPicker.jsx +0 -248
  70. package/management-ui/src/components/SessionMonitor.jsx +0 -350
  71. package/management-ui/src/components/StatusBadge.jsx +0 -208
  72. package/management-ui/src/components/UserContextSwitcher.jsx +0 -212
  73. package/management-ui/src/components/UserSimulation.jsx +0 -327
  74. package/management-ui/src/components/Welcome.jsx +0 -434
  75. package/management-ui/src/components/codegen/APIEndpointGenerator.jsx +0 -637
  76. package/management-ui/src/components/codegen/APIModuleSelector.jsx +0 -227
  77. package/management-ui/src/components/codegen/CodeGenerationWizard.jsx +0 -247
  78. package/management-ui/src/components/codegen/CodePreviewEditor.jsx +0 -316
  79. package/management-ui/src/components/codegen/DynamicModuleForm.jsx +0 -271
  80. package/management-ui/src/components/codegen/FormBuilder.jsx +0 -737
  81. package/management-ui/src/components/codegen/IntegrationGenerator.jsx +0 -855
  82. package/management-ui/src/components/codegen/ProjectScaffoldWizard.jsx +0 -797
  83. package/management-ui/src/components/codegen/SchemaBuilder.jsx +0 -303
  84. package/management-ui/src/components/codegen/TemplateSelector.jsx +0 -586
  85. package/management-ui/src/components/codegen/index.js +0 -10
  86. package/management-ui/src/components/connections/ConnectionConfigForm.jsx +0 -362
  87. package/management-ui/src/components/connections/ConnectionHealthMonitor.jsx +0 -182
  88. package/management-ui/src/components/connections/ConnectionTester.jsx +0 -200
  89. package/management-ui/src/components/connections/EntityRelationshipMapper.jsx +0 -292
  90. package/management-ui/src/components/connections/OAuthFlow.jsx +0 -204
  91. package/management-ui/src/components/connections/index.js +0 -5
  92. package/management-ui/src/components/index.js +0 -21
  93. package/management-ui/src/components/monitoring/APIGatewayMetrics.jsx +0 -222
  94. package/management-ui/src/components/monitoring/LambdaMetrics.jsx +0 -169
  95. package/management-ui/src/components/monitoring/MetricsChart.jsx +0 -197
  96. package/management-ui/src/components/monitoring/MonitoringDashboard.jsx +0 -393
  97. package/management-ui/src/components/monitoring/SQSMetrics.jsx +0 -246
  98. package/management-ui/src/components/monitoring/index.js +0 -6
  99. package/management-ui/src/components/monitoring/monitoring.css +0 -218
  100. package/management-ui/src/components/theme-provider.jsx +0 -52
  101. package/management-ui/src/components/theme-toggle.jsx +0 -39
  102. package/management-ui/src/components/ui/badge.tsx +0 -36
  103. package/management-ui/src/components/ui/button.test.jsx +0 -56
  104. package/management-ui/src/components/ui/button.tsx +0 -57
  105. package/management-ui/src/components/ui/card.tsx +0 -76
  106. package/management-ui/src/components/ui/dropdown-menu.tsx +0 -199
  107. package/management-ui/src/components/ui/select.tsx +0 -157
  108. package/management-ui/src/components/ui/skeleton.jsx +0 -15
  109. package/management-ui/src/hooks/useFrigg.jsx +0 -387
  110. package/management-ui/src/hooks/useSocket.jsx +0 -58
  111. package/management-ui/src/index.css +0 -193
  112. package/management-ui/src/lib/utils.ts +0 -6
  113. package/management-ui/src/main.jsx +0 -10
  114. package/management-ui/src/pages/CodeGeneration.jsx +0 -14
  115. package/management-ui/src/pages/Connections.jsx +0 -252
  116. package/management-ui/src/pages/ConnectionsEnhanced.jsx +0 -633
  117. package/management-ui/src/pages/Dashboard.jsx +0 -311
  118. package/management-ui/src/pages/Environment.jsx +0 -314
  119. package/management-ui/src/pages/IntegrationConfigure.jsx +0 -669
  120. package/management-ui/src/pages/IntegrationDiscovery.jsx +0 -567
  121. package/management-ui/src/pages/IntegrationTest.jsx +0 -742
  122. package/management-ui/src/pages/Integrations.jsx +0 -253
  123. package/management-ui/src/pages/Monitoring.jsx +0 -17
  124. package/management-ui/src/pages/Simulation.jsx +0 -155
  125. package/management-ui/src/pages/Users.jsx +0 -492
  126. package/management-ui/src/services/api.js +0 -41
  127. package/management-ui/src/services/apiModuleService.js +0 -193
  128. package/management-ui/src/services/websocket-handlers.js +0 -120
  129. package/management-ui/src/test/api/project.test.js +0 -273
  130. package/management-ui/src/test/components/Welcome.test.jsx +0 -378
  131. package/management-ui/src/test/mocks/server.js +0 -178
  132. package/management-ui/src/test/setup.js +0 -61
  133. package/management-ui/src/test/utils/test-utils.jsx +0 -134
  134. package/management-ui/src/utils/repository.js +0 -98
  135. package/management-ui/src/utils/repository.test.js +0 -118
  136. package/management-ui/src/workflows/phase2-integration-workflows.js +0 -884
  137. package/management-ui/tailwind.config.js +0 -63
  138. package/management-ui/tsconfig.json +0 -37
  139. package/management-ui/tsconfig.node.json +0 -10
  140. package/management-ui/vite.config.js +0 -26
  141. package/management-ui/vitest.config.js +0 -38
  142. package/test/auther-definition-method-tester.js +0 -45
  143. package/test/index.js +0 -9
  144. package/test/integration-validator.js +0 -2
  145. package/test/mock-api-readme.md +0 -102
  146. package/test/mock-api.js +0 -284
  147. package/test/mock-integration.js +0 -78
@@ -1,63 +0,0 @@
1
- /** @type {import('tailwindcss').Config} */
2
- export default {
3
- darkMode: ["class"],
4
- content: [
5
- "./index.html",
6
- "./src/**/*.{js,ts,jsx,tsx}",
7
- ],
8
- theme: {
9
- extend: {
10
- colors: {
11
- 'frigg-blue': '#0066CC',
12
- 'frigg-dark': '#1A1A1A',
13
- 'frigg-gray': '#F5F5F5',
14
- background: 'hsl(var(--background))',
15
- foreground: 'hsl(var(--foreground))',
16
- card: {
17
- DEFAULT: 'hsl(var(--card))',
18
- foreground: 'hsl(var(--card-foreground))'
19
- },
20
- popover: {
21
- DEFAULT: 'hsl(var(--popover))',
22
- foreground: 'hsl(var(--popover-foreground))'
23
- },
24
- primary: {
25
- DEFAULT: 'hsl(var(--primary))',
26
- foreground: 'hsl(var(--primary-foreground))'
27
- },
28
- secondary: {
29
- DEFAULT: 'hsl(var(--secondary))',
30
- foreground: 'hsl(var(--secondary-foreground))'
31
- },
32
- muted: {
33
- DEFAULT: 'hsl(var(--muted))',
34
- foreground: 'hsl(var(--muted-foreground))'
35
- },
36
- accent: {
37
- DEFAULT: 'hsl(var(--accent))',
38
- foreground: 'hsl(var(--accent-foreground))'
39
- },
40
- destructive: {
41
- DEFAULT: 'hsl(var(--destructive))',
42
- foreground: 'hsl(var(--destructive-foreground))'
43
- },
44
- border: 'hsl(var(--border))',
45
- input: 'hsl(var(--input))',
46
- ring: 'hsl(var(--ring))',
47
- chart: {
48
- '1': 'hsl(var(--chart-1))',
49
- '2': 'hsl(var(--chart-2))',
50
- '3': 'hsl(var(--chart-3))',
51
- '4': 'hsl(var(--chart-4))',
52
- '5': 'hsl(var(--chart-5))'
53
- }
54
- },
55
- borderRadius: {
56
- lg: 'var(--radius)',
57
- md: 'calc(var(--radius) - 2px)',
58
- sm: 'calc(var(--radius) - 4px)'
59
- }
60
- }
61
- },
62
- plugins: [require("tailwindcss-animate")],
63
- }
@@ -1,37 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "useDefineForClassFields": true,
5
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
- "module": "ESNext",
7
- "skipLibCheck": true,
8
- "allowJs": true,
9
- "checkJs": false,
10
-
11
- /* Bundler mode */
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "resolveJsonModule": true,
15
- "isolatedModules": true,
16
- "noEmit": true,
17
- "jsx": "react-jsx",
18
-
19
- /* Linting */
20
- "strict": true,
21
- "noUnusedLocals": false,
22
- "noUnusedParameters": false,
23
- "noFallthroughCasesInSwitch": true,
24
-
25
- /* Path mapping */
26
- "baseUrl": ".",
27
- "paths": {
28
- "@/*": ["./src/*"],
29
- "@/components/*": ["./src/components/*"],
30
- "@/hooks/*": ["./src/hooks/*"],
31
- "@/utils/*": ["./src/utils/*"],
32
- "@/services/*": ["./src/services/*"]
33
- }
34
- },
35
- "include": ["src"],
36
- "references": [{ "path": "./tsconfig.node.json" }]
37
- }
@@ -1,10 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "composite": true,
4
- "skipLibCheck": true,
5
- "module": "ESNext",
6
- "moduleResolution": "bundler",
7
- "allowSyntheticDefaultImports": true
8
- },
9
- "include": ["vite.config.js"]
10
- }
@@ -1,26 +0,0 @@
1
- import { defineConfig } from 'vite'
2
- import react from '@vitejs/plugin-react'
3
- import path from 'path'
4
-
5
- // https://vitejs.dev/config/
6
- export default defineConfig({
7
- plugins: [react()],
8
- resolve: {
9
- alias: {
10
- '@': path.resolve(__dirname, './src'),
11
- },
12
- },
13
- server: {
14
- port: 5173,
15
- proxy: {
16
- '/api': {
17
- target: 'http://localhost:3001',
18
- changeOrigin: true,
19
- },
20
- '/socket.io': {
21
- target: 'http://localhost:3001',
22
- ws: true,
23
- }
24
- }
25
- }
26
- })
@@ -1,38 +0,0 @@
1
- import { defineConfig } from 'vitest/config'
2
- import react from '@vitejs/plugin-react'
3
- import path from 'path'
4
-
5
- export default defineConfig({
6
- plugins: [react()],
7
- test: {
8
- globals: true,
9
- environment: 'jsdom',
10
- setupFiles: ['./src/test/setup.js'],
11
- coverage: {
12
- provider: 'v8',
13
- reporter: ['text', 'json', 'html'],
14
- exclude: [
15
- 'node_modules/',
16
- 'dist/',
17
- 'server/',
18
- '**/*.config.js',
19
- '**/*.config.ts',
20
- '**/test/**',
21
- '**/__tests__/**',
22
- '**/*.test.{js,ts,jsx,tsx}',
23
- '**/*.spec.{js,ts,jsx,tsx}'
24
- ],
25
- thresholds: {
26
- statements: 70,
27
- branches: 70,
28
- functions: 70,
29
- lines: 70
30
- }
31
- }
32
- },
33
- resolve: {
34
- alias: {
35
- '@': path.resolve(__dirname, './src'),
36
- },
37
- },
38
- })
@@ -1,45 +0,0 @@
1
- const {flushDebugLog} = require('@friggframework/core');
2
-
3
- async function testDefinitionRequiredAuthMethods(api, definition, authCallbackParams, tokenResponse, userId) {
4
-
5
- // const response = await definition.getToken(api, authCallbackParams);
6
- // expect(api.setTokens).toHaveBeenCalled();
7
- // if (tokenResponse) {
8
- // expect(response).toMatchObject(tokenResponse);
9
- // }
10
-
11
- const entityDetails = await definition.requiredAuthMethods.getEntityDetails(api, authCallbackParams, tokenResponse, userId);
12
- expect(entityDetails).toHaveProperty('identifiers');
13
- expect(Object.values(entityDetails.identifiers).length).toBeGreaterThan(0);
14
- for (const key of Object.keys(entityDetails.identifiers)){
15
- expect(key).toBeDefined();
16
- expect(entityDetails.identifiers[key]).toBeDefined();
17
- }
18
-
19
-
20
- const credentialDetails = await definition.requiredAuthMethods.getCredentialDetails(api);
21
- expect(credentialDetails).toHaveProperty('identifiers');
22
- expect(Object.values(entityDetails.identifiers).length).toBeGreaterThan(0);
23
- for (const key of Object.keys(entityDetails.identifiers)){
24
- expect(key).toBeDefined();
25
- expect(entityDetails.identifiers[key]).toBeDefined();
26
- }
27
-
28
- const successResponse = await definition.requiredAuthMethods.testAuthRequest(api);
29
- expect(successResponse).toBeTruthy();
30
- const savedKeys = {};
31
- for (const key of definition.requiredAuthMethods.apiPropertiesToPersist.credential){
32
- savedKeys[key] = api[key];
33
- delete api[key];
34
- }
35
- let validAuth = false;
36
- try {
37
- if (await definition.requiredAuthMethods.testAuthRequest(api)) validAuth = true;
38
- } catch (e) {
39
- flushDebugLog(e);
40
- }
41
- expect(validAuth).not.toBeTruthy();
42
- Object.assign(api, savedKeys);
43
- }
44
-
45
- module.exports = { testDefinitionRequiredAuthMethods }
package/test/index.js DELETED
@@ -1,9 +0,0 @@
1
- const { testDefinitionRequiredAuthMethods } = require('./auther-definition-method-tester');
2
- const { createMockIntegration, createMockApiObject } = require('./mock-integration');
3
-
4
-
5
- module.exports = {
6
- createMockIntegration,
7
- createMockApiObject,
8
- testDefinitionRequiredAuthMethods,
9
- };
@@ -1,2 +0,0 @@
1
- // TODO input for poll worker (etc), run as if in staging, set up env just right, enable debugging with debugger,
2
- // TODO write up or help automate (?) knowing where to update tests/mocks when a problem is found
@@ -1,102 +0,0 @@
1
- # Mocked Requests Set Up for Your API Module
2
-
3
- ## Add Tooling to the Test File
4
-
5
- Example code:
6
-
7
- ```js
8
- const Api = require('./Api');
9
- const { mockApi } = require('../../../../test/utils/mockApi');
10
-
11
- const MockedApi = mockApi(Api, {
12
- authenticationMode: 'browser',
13
- });
14
-
15
- describe('DemoNock API', async () => {
16
- before(async function () {
17
- await MockedApi.initialize({ test: this.test });
18
- });
19
-
20
- after(async function () {
21
- await MockedApi.clean({ test: this.test });
22
- });
23
-
24
- it('tests a nice thing', async () => {
25
- const api = await MockedApi.mock();
26
- const users = await api.getUsers();
27
- expect(users).to.have.length(2);
28
- });
29
- });
30
- ```
31
-
32
- Api - the LH API class that is being tested/mocked
33
-
34
- mockApi - tool to record/playback requests and automate login to API
35
-
36
- MockedApi - Api class with wrapper around it to record/playback requests and automate login to API. `authenticationMode` sets how to handle authentication when recording requests. Browser means it will require a manual step in the browser (uses Authenticator). Client credentials mode gets a token automcaitcally with machine-to-machine token. Manual means the developer will handle authentication manually, like setting an API key. By default mockApi will use the class name of the mocked API to name the output file. This can be overidden by passing in `displayName`.
37
- test/recorded-requests - the directory where recorded API requests are saved
38
-
39
- before - make sure to use the `async function` form here, so we can access mocha's `this` object. The call to `initialize` sets up the tooling for recording/playback
40
-
41
- after - same here need to use the `async function` form and pass in `this.test` to `clean`. This stops recording/playback and removes all hooks and other tooling from Node's HTTP code.
42
-
43
- test - instead of using `new Api` in your tests, use `await MockedApi.mock`. Any parameters you would normally pass into `new Api` will be passed through with the call to `mock`. The instance of the Api class that is returned will already be authenticated (unless using manual mode).
44
-
45
- ## Creating new API tests
46
-
47
- When running your tests while creating them, use `npm --record-apis=demonock test`.
48
-
49
- This tells the tooling to record the requests made while running the tests for the DemoNockApi class.
50
-
51
- ## Finalizing API tests
52
-
53
- When satisified with your tests, run `npm test` without adding the `--record-apis` flag to make sure the recorded requests worked. The tests should pass without needing you to perform a login step in the browser.
54
-
55
- ## Tests that fail...
56
-
57
- Sometimes a "finished" test that was previously working starts to fail. Or, a test passes when it should fail (false negative). There are a few reasons this might happen.
58
-
59
- ### Test fails after code updates
60
-
61
- If you made updates to the code, this may cause a test to fail. In this case the developer doesn't need to update mocks. To make the test pass, the updated code should be fixed, or the test should be updated to reflect the new data shape.
62
-
63
- One way to test for this scenario is running `npm test` in the main branch, seeing that all tests pass, and then confirming tests fail in your feature branch. This would show that the test is almost certainly failing due to a change in your branch.
64
-
65
- ### Test should fail but passes
66
-
67
- If a test is passing, but in the "real world" the code is failing, the API response may have changed. Re-record mocks by running tests with `--record-apis=nockdemo`. Hopefully, one or more tests will now fail. These tests and related code should be updated to work with the new API response data shape.
68
-
69
- When creating the PR for this update, flag that the mocks were re-recorded so the updated mocks will be sure to be reviewed by another team member as part of code review.
70
-
71
- ### Mocks in error state
72
-
73
- If the recorded files get messed up when updating (sometimes unavoidable under certain error conditions) just `git restore test/recorded-requests` or delete the file(s) in that directory and re-record.
74
-
75
- ## Miscellaneous Notes
76
-
77
- More than one API can be set to record mode at a time: `npm --record-apis=activecampaign,hubspot test`
78
-
79
- You can use .only when --record-apis is passed, but only for the root level test suite. Otherwise an error will be thrown to prevent partial recording of the mocks. .skip is fine to use to skip tests that should not be recorded.
80
-
81
- CAN UPDATE RECORDED REQUESTS:
82
-
83
- ```js
84
- describe('Nock Demo API', () => {
85
- it('does x');
86
- it.skip('does y');
87
- });
88
- ```
89
-
90
- CANNOT UPDATE RECORDED REQUESTS:
91
-
92
- ```js
93
- describe('Nock Demo API', () => {
94
- it('does x');
95
- it('does y');
96
- });
97
- ```
98
-
99
- ## Caveats
100
-
101
- - Client credential mode may only work with Crossbeam currently
102
- - Puppet mode (browser automation) for login is not yet implemented
package/test/mock-api.js DELETED
@@ -1,284 +0,0 @@
1
- const nock = require('nock');
2
- const { Authenticator } = require('@friggframework/test');
3
- const { join: joinPath } = require('path');
4
- const { parse: parseUrl } = require('url');
5
- const { mkdir, readFile, rename, rm, writeFile } = require('fs/promises');
6
-
7
- // TODO store in DB?
8
- const tokenDirectory = joinPath(process.cwd(), 'test', '.token-cache');
9
- const fixtureDirectory = joinPath(process.cwd(), 'test', 'recorded-requests');
10
- nock.back.fixtures = fixtureDirectory;
11
-
12
- // Try to rename but fail silently if the file does not exist.
13
- const tryRename = async (a, b) => {
14
- try {
15
- await rename(a, b);
16
- } catch (error) {
17
- if (error.code === 'ENOENT') {
18
- return;
19
- }
20
- throw error;
21
- }
22
- };
23
- const getJestGlobalState = () => {
24
- const globalSymbols = Object.getOwnPropertySymbols(global);
25
- let jestState;
26
- globalSymbols.forEach((sym) => {
27
- if (sym.toString() === 'Symbol(JEST_STATE_SYMBOL)') {
28
- jestState = global[sym];
29
- }
30
- });
31
-
32
- return jestState;
33
- };
34
-
35
- const checkForOnlies = () => {
36
- let didFindOnly = false;
37
- const findOnly = (child) => {
38
- if (child.mode === 'only') {
39
- didFindOnly = true;
40
- }
41
- if (child.children) {
42
- child.children.forEach((nestedChild) => {
43
- findOnly(nestedChild);
44
- });
45
- }
46
- };
47
- const jestState = getJestGlobalState();
48
- const rootDescribe = jestState.rootDescribeBlock;
49
-
50
- for (const child of rootDescribe.children) {
51
- findOnly(child);
52
- }
53
-
54
- return didFindOnly;
55
- };
56
-
57
- const mockApi = (Api, classOptionByName = {}) => {
58
- const {
59
- authenticationMode,
60
- displayName = Api.name,
61
- filteringScope,
62
- } = classOptionByName;
63
- // The tag is the lower case display name, with any trailing 'Api' in the string removed.
64
- const tag = displayName.replace(/Api$/i, '').toLowerCase();
65
- const tokenFile = `${displayName}.json`;
66
- const tokenFileFullPath = joinPath(tokenDirectory, tokenFile);
67
-
68
- return class MockedApi extends Api {
69
- static name = `Mocked${displayName}`;
70
- static tokenResponse = null;
71
- static excludedRecordingPaths = [];
72
- static #context = {};
73
-
74
- static async initialize() {
75
- this.#context = {};
76
-
77
- const didFindOnlies = checkForOnlies();
78
-
79
- if (didFindOnlies) {
80
- throw new Error(
81
- 'Cancelled recording API mocks because some tests were marked `.only`. Please remove any `.only`s from any `describe` blocks deeper than the root level, and all `it` blocks.'
82
- );
83
- }
84
-
85
- this.#context.originalNockMode = nock.back.currentMode;
86
-
87
- const { npm_config_record_apis: apisToRecordText = '' } =
88
- process.env;
89
- const apisToRecord = apisToRecordText
90
- .split(',')
91
- .map((name) => name.trim().toLowerCase());
92
-
93
- if (apisToRecord.includes(tag)) {
94
- this.#context.nockMode = 'update';
95
- } else {
96
- this.#context.nockMode = 'lockdown';
97
- }
98
-
99
- nock.back.setMode(this.#context.nockMode);
100
-
101
- const fixtureFile = `${displayName}.json`;
102
-
103
- if (this.#context.nockMode === 'update') {
104
- const fixtureFileFullPath = joinPath(
105
- fixtureDirectory,
106
- fixtureFile
107
- );
108
- const fixtureFileBackupFullPath = joinPath(
109
- fixtureDirectory,
110
- `.${displayName}.json.backup`
111
- );
112
-
113
- await tryRename(fixtureFileFullPath, fixtureFileBackupFullPath);
114
-
115
- this.#context.restoreFixture = async () =>
116
- await tryRename(
117
- fixtureFileBackupFullPath,
118
- fixtureFileFullPath
119
- );
120
- this.#context.deleteFixtureBackup = async () =>
121
- await rm(fixtureFileBackupFullPath, { force: true });
122
- }
123
-
124
- const nockBack = await nock.back(fixtureFile, {
125
- before: (scope) => {
126
- if (filteringScope) {
127
- scope.options.filteringScope = filteringScope;
128
- }
129
- },
130
- // Filter out token URLs
131
- afterRecord: (recordings) =>
132
- recordings.filter(
133
- ({ path }) =>
134
- !this.excludedRecordingPaths.includes(path)
135
- ),
136
- recorder: {
137
- output_objects: true,
138
- enable_reqheaders_recording: false,
139
- },
140
- });
141
-
142
- this.#context.assertAllRequests = () =>
143
- nockBack.context.assertScopesFinished();
144
- this.#context.done = () => nockBack.nockDone();
145
- }
146
-
147
- static async clean() {
148
- const {
149
- assertAllRequests,
150
- done,
151
- nockMode,
152
- originalNockMode,
153
- restoreFixture,
154
- deleteFixtureBackup,
155
- } = this.#context;
156
-
157
- const { didAllTestsPass } = global.mockApiResults;
158
-
159
- if (done) {
160
- done();
161
- }
162
- if (originalNockMode) {
163
- nock.back.setMode(originalNockMode);
164
- }
165
- if (assertAllRequests && nockMode !== 'update') {
166
- assertAllRequests();
167
- }
168
-
169
- nock.cleanAll();
170
- nock.restore();
171
-
172
- if (nockMode === 'update') {
173
- if (!didAllTestsPass) {
174
- try {
175
- await restoreFixture();
176
- } finally {
177
- throw new Error(
178
- 'Cancelled recording API mocks because some tests failed. Please fix the failing tests and try to record again.'
179
- );
180
- }
181
- } else {
182
- await deleteFixtureBackup();
183
- }
184
- }
185
- }
186
-
187
- static async saveCachedTokenResponse() {
188
- if (!this.tokenResponse) {
189
- return;
190
- }
191
-
192
- await mkdir(tokenDirectory, { recursive: true });
193
- await writeFile(
194
- tokenFileFullPath,
195
- JSON.stringify(this.tokenResponse)
196
- );
197
- }
198
-
199
- static async loadCachedTokenResponse() {
200
- try {
201
- const tokenResponseText = await readFile(tokenFileFullPath);
202
- this.tokenResponse = JSON.parse(tokenResponseText);
203
- } catch (error) {
204
- if (error.code === 'ENOENT') {
205
- this.tokenResponse = null;
206
- return;
207
- }
208
- throw error;
209
- }
210
- }
211
-
212
- static async mock(...constructorParameters) {
213
- const api = new this(...constructorParameters);
214
-
215
- if (nock.back.currentMode !== 'lockdown') {
216
- await this.loadCachedTokenResponse();
217
- }
218
-
219
- // TODO read authentication mode from module package
220
- if (authenticationMode === 'client_credentials') {
221
- // TODO make generic (tied to crossbeam api)
222
- api.grantType = 'client_credentials';
223
- api.refreshAccessToken = api.getTokenFromClientCredentials;
224
-
225
- if (process.env.CROSSBEAM_API_BASE_URL)
226
- api.baseUrl = process.env.CROSSBEAM_API_BASE_URL;
227
- if (process.env.CROSSBEAM_API_AUTH_URL)
228
- api.tokenUri = `${process.env.CROSSBEAM_API_AUTH_URL}/oauth/token`;
229
- if (process.env.CROSSBEAM_API_AUDIENCE)
230
- api.audience = process.env.CROSSBEAM_API_AUDIENCE;
231
-
232
- api.client_secret = process.env.CROSSBEAM_TEST_CLIENT_SECRET;
233
- api.client_id = process.env.CROSSBEAM_TEST_CLIENT_ID;
234
- api.refreshAccessToken = api.getTokenFromClientCredentials;
235
-
236
- this.tokenResponse = await api.getTokenFromClientCredentials();
237
- } else if (authenticationMode === 'puppet') {
238
- throw new Error('Not yet implemented');
239
- } else if (authenticationMode === 'browser') {
240
- if (nock.back.currentMode !== 'lockdown') {
241
- const { path: tokenPath } = parseUrl(api.tokenUri);
242
- this.excludedRecordingPaths.push(tokenPath);
243
-
244
- if (this.tokenResponse) {
245
- await api.setTokens(this.tokenResponse);
246
-
247
- try {
248
- await api.testAuth();
249
- } catch {
250
- this.tokenResponse = null;
251
- nock.cleanAll();
252
- await rm(tokenFileFullPath, {
253
- force: true,
254
- });
255
- }
256
- }
257
-
258
- if (!this.tokenResponse) {
259
- const url = api.authorizationUri;
260
- const { data } = await Authenticator.oauth2(url);
261
- const { code } = data;
262
- this.tokenResponse = await api.getTokenFromCode(code);
263
- await api.setTokens(this.tokenResponse);
264
- nock.cleanAll();
265
- }
266
- }
267
- } else if (authenticationMode === 'manual') {
268
- // NOOP. This space intentionally left blank. No action should be performed in this mode, and the developer writing the test will handle authentication externally to this module.
269
- } else {
270
- throw new Error(
271
- 'Unrecognized authentication mode for mocked API.'
272
- );
273
- }
274
-
275
- if (nock.back.currentMode !== 'lockdown') {
276
- await this.saveCachedTokenResponse();
277
- }
278
-
279
- return api;
280
- }
281
- };
282
- };
283
-
284
- module.exports = { mockApi };