@equinor/roma-nx-plugin 1.0.0-BETA.0 → 1.1.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 (114) hide show
  1. package/.eslintrc.json +37 -0
  2. package/CHANGELOG.md +42 -0
  3. package/executors.json +5 -0
  4. package/generators.json +5 -0
  5. package/jest.config.ts +13 -0
  6. package/manifest-schema.json +80 -0
  7. package/package.json +12 -11
  8. package/project.json +65 -0
  9. package/src/executors/build/build.ts +100 -0
  10. package/src/executors/build/executor.spec.ts +13 -0
  11. package/src/executors/build/executor.ts +10 -0
  12. package/src/executors/build/minify.ts +20 -0
  13. package/src/executors/component-test/executor.spec.ts +18 -0
  14. package/src/executors/component-test/executor.ts +57 -0
  15. package/src/executors/component-test/schema.d.ts +5 -0
  16. package/src/executors/component-test/schema.json +25 -0
  17. package/src/executors/create-vite-config.ts +133 -0
  18. package/src/executors/executor-context.ts +102 -0
  19. package/src/executors/publish/executor.ts +29 -0
  20. package/src/executors/publish/manifest-model.ts +33 -0
  21. package/src/executors/publish/publish-script.spec.ts +118 -0
  22. package/src/executors/publish/publish-script.ts +210 -0
  23. package/src/executors/serve/executor.ts +19 -0
  24. package/src/executors/serve/get-manifest.ts +20 -0
  25. package/src/executors/serve/schema.d.ts +2 -0
  26. package/src/executors/serve/schema.json +7 -0
  27. package/src/executors/serve/server.ts +250 -0
  28. package/src/executors/utils/get-vite-config.ts +9 -0
  29. package/src/executors/utils/logger.ts +90 -0
  30. package/src/generators/app/data/modules.ts +19 -0
  31. package/src/generators/app/generator.spec.ts +86 -0
  32. package/src/generators/app/generator.ts +141 -0
  33. package/src/generators/component-test/files/cypress/fixtures/example.json +5 -0
  34. package/src/generators/component-test/files/cypress/screenshots/.gitkeep +0 -0
  35. package/src/generators/component-test/files/cypress/support/commands.ts +37 -0
  36. package/src/generators/component-test/files/cypress/support/component-index.html +12 -0
  37. package/src/generators/component-test/files/cypress/support/component.ts +39 -0
  38. package/src/generators/component-test/files/cypress/videos/.gitkeep +0 -0
  39. package/src/generators/component-test/files/cypress.config.ts.template +43 -0
  40. package/src/generators/component-test/generator.spec.ts +79 -0
  41. package/src/generators/component-test/generator.ts +67 -0
  42. package/src/generators/component-test/schema.d.ts +3 -0
  43. package/src/generators/component-test/schema.json +17 -0
  44. package/src/generators/preset/generator.spec.ts +38 -0
  45. package/src/generators/preset/generator.ts +18 -0
  46. package/src/index.ts +1 -0
  47. package/src/migrations/add-publish-target/add-publish-target.spec.ts +60 -0
  48. package/src/migrations/add-publish-target/add-publish-target.ts +28 -0
  49. package/src/migrations/move-fusion-manifest/move-fusion-manifest.ts +35 -0
  50. package/src/migrations/remove-fusion-cli/remove-fusion-cli.ts +70 -0
  51. package/tsconfig.json +17 -0
  52. package/tsconfig.lib.json +20 -0
  53. package/tsconfig.spec.json +26 -0
  54. package/vite.config.ts +31 -0
  55. package/src/executors/build/build.d.ts +0 -4
  56. package/src/executors/build/build.js +0 -76
  57. package/src/executors/build/build.js.map +0 -1
  58. package/src/executors/build/executor.d.ts +0 -5
  59. package/src/executors/build/executor.js +0 -8
  60. package/src/executors/build/executor.js.map +0 -1
  61. package/src/executors/build/minify.d.ts +0 -2
  62. package/src/executors/build/minify.js +0 -22
  63. package/src/executors/build/minify.js.map +0 -1
  64. package/src/executors/create-vite-config.d.ts +0 -3
  65. package/src/executors/create-vite-config.js +0 -73
  66. package/src/executors/create-vite-config.js.map +0 -1
  67. package/src/executors/executor-context.d.ts +0 -2
  68. package/src/executors/executor-context.js +0 -101
  69. package/src/executors/executor-context.js.map +0 -1
  70. package/src/executors/publish/executor.d.ts +0 -5
  71. package/src/executors/publish/executor.js +0 -24
  72. package/src/executors/publish/executor.js.map +0 -1
  73. package/src/executors/publish/manifest-model.d.ts +0 -30
  74. package/src/executors/publish/manifest-model.js +0 -3
  75. package/src/executors/publish/manifest-model.js.map +0 -1
  76. package/src/executors/publish/publish-script.d.ts +0 -9
  77. package/src/executors/publish/publish-script.js +0 -185
  78. package/src/executors/publish/publish-script.js.map +0 -1
  79. package/src/executors/serve/executor.d.ts +0 -3
  80. package/src/executors/serve/executor.js +0 -8
  81. package/src/executors/serve/executor.js.map +0 -1
  82. package/src/executors/serve/get-manifest.d.ts +0 -2
  83. package/src/executors/serve/get-manifest.js +0 -20
  84. package/src/executors/serve/get-manifest.js.map +0 -1
  85. package/src/executors/serve/server.d.ts +0 -3
  86. package/src/executors/serve/server.js +0 -166
  87. package/src/executors/serve/server.js.map +0 -1
  88. package/src/executors/utils/get-vite-config.d.ts +0 -1
  89. package/src/executors/utils/get-vite-config.js +0 -13
  90. package/src/executors/utils/get-vite-config.js.map +0 -1
  91. package/src/executors/utils/logger.d.ts +0 -24
  92. package/src/executors/utils/logger.js +0 -68
  93. package/src/executors/utils/logger.js.map +0 -1
  94. package/src/generators/app/data/modules.d.ts +0 -19
  95. package/src/generators/app/data/modules.js +0 -23
  96. package/src/generators/app/data/modules.js.map +0 -1
  97. package/src/generators/app/generator.d.ts +0 -5
  98. package/src/generators/app/generator.js +0 -101
  99. package/src/generators/app/generator.js.map +0 -1
  100. package/src/generators/preset/generator.d.ts +0 -4
  101. package/src/generators/preset/generator.js +0 -13
  102. package/src/generators/preset/generator.js.map +0 -1
  103. package/src/index.js +0 -1
  104. package/src/index.js.map +0 -1
  105. package/src/migrations/add-publish-target/add-publish-target.d.ts +0 -2
  106. package/src/migrations/add-publish-target/add-publish-target.js +0 -32
  107. package/src/migrations/add-publish-target/add-publish-target.js.map +0 -1
  108. package/src/migrations/move-fusion-manifest/move-fusion-manifest.d.ts +0 -2
  109. package/src/migrations/move-fusion-manifest/move-fusion-manifest.js +0 -30
  110. package/src/migrations/move-fusion-manifest/move-fusion-manifest.js.map +0 -1
  111. package/src/migrations/remove-fusion-cli/remove-fusion-cli.d.ts +0 -2
  112. package/src/migrations/remove-fusion-cli/remove-fusion-cli.js +0 -48
  113. package/src/migrations/remove-fusion-cli/remove-fusion-cli.js.map +0 -1
  114. /package/src/{index.d.ts → generators/component-test/files/cypress/downloads/.gitkeep} +0 -0
@@ -0,0 +1,133 @@
1
+ import { defineConfig, UserConfig, mergeConfig, LibraryOptions } from 'vite';
2
+ import ViteRestart from 'vite-plugin-restart';
3
+ import viteEnv from 'vite-plugin-environment';
4
+ import { resolve, join } from 'path';
5
+ import react from '@vitejs/plugin-react';
6
+ import { Logger } from './utils/logger';
7
+ import type { ExecutorContext } from '@nx/devkit';
8
+ import { TargetConfiguration } from 'nx/src/config/workspace-json-project-json';
9
+ import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
10
+ import { minifyEs } from './build/minify';
11
+ import { ServeExecutorSchema } from './serve/schema';
12
+
13
+ type BuildConfiguration = TargetConfiguration & {
14
+ outputPath?: string;
15
+ };
16
+
17
+ export const createRomaViteConfig = (
18
+ config: UserConfig,
19
+ context: ExecutorContext,
20
+ watch = false,
21
+ hmrPort = 42000
22
+ ) => {
23
+ const isServe = context.targetName === 'serve';
24
+ const projectName = context.projectName;
25
+ const project = context.workspace.projects[projectName];
26
+ const workspaceRoot = context.root;
27
+ const serveConfig = project.targets.serve;
28
+ const options = serveConfig.options as ServeExecutorSchema;
29
+ let base: string;
30
+ let entry: string | Record<string, string>;
31
+ let viteConfigPath: string;
32
+ let projectRoot = project.root;
33
+ let appDir = '';
34
+ if (isServe) {
35
+ const [appDirectory, ...rest] = projectRoot.split('/');
36
+ projectRoot = rest.join('/');
37
+ appDir = appDirectory;
38
+ base = resolve(context.root, appDirectory);
39
+ entry = {
40
+ self: join(projectRoot, 'src/index.ts'),
41
+ };
42
+ viteConfigPath = resolve(base, projectRoot, 'vite.config.ts');
43
+ } else {
44
+ base = resolve(context.root, projectRoot);
45
+ entry = '/src/index.ts';
46
+ viteConfigPath = resolve(base, 'vite.config.ts');
47
+ }
48
+ if (
49
+ isServe &&
50
+ options.additionalProjects &&
51
+ options.additionalProjects.length > 0
52
+ ) {
53
+ options.additionalProjects.forEach((project) => {
54
+ const projectConfig = context.workspace.projects[project];
55
+ const path = join(
56
+ projectConfig.root.replace(appDir + '/', ''),
57
+ 'src',
58
+ 'index.ts'
59
+ );
60
+ console.log('Adding project', path, 'to server-list');
61
+ entry[`${project}`] = path;
62
+ });
63
+ }
64
+ const buildConfig = project.targets.build as BuildConfiguration;
65
+ const outputPath = buildConfig.outputPath ?? `dist/apps/${projectName}`;
66
+
67
+ const devPortalPath = resolve(
68
+ process.cwd(),
69
+ 'node_modules/@equinor/roma-framework/dev-portal'
70
+ );
71
+
72
+ if (!config.build) {
73
+ config.build = {
74
+ lib: {
75
+ entry: 'src/index.ts',
76
+ fileName: 'app-bundle',
77
+ formats: ['es'],
78
+ },
79
+ };
80
+ }
81
+ (config.build.lib as LibraryOptions).entry = entry;
82
+
83
+ const minifyPlugin = [];
84
+
85
+ if (config.build.minify) {
86
+ minifyPlugin.push(minifyEs());
87
+ }
88
+
89
+ const build = context.targetName === 'build';
90
+ const romaConfig = {
91
+ customLogger: new Logger(),
92
+ cacheDir: resolve(
93
+ context.root,
94
+ 'node_modules',
95
+ '.vite',
96
+ context.projectName
97
+ ),
98
+ assetsInclude: [`${devPortalPath}/roma-framework.umd.js`],
99
+ root: base,
100
+ server: {
101
+ middlewareMode: true,
102
+ hmr: {
103
+ port: hmrPort,
104
+ },
105
+ },
106
+ appType: 'custom',
107
+ define: {
108
+ 'process.env': {},
109
+ },
110
+ build: {
111
+ outDir: resolve(workspaceRoot, outputPath),
112
+ watch: watch
113
+ ? {
114
+ clearScreen: true,
115
+ }
116
+ : undefined,
117
+ },
118
+ plugins: [
119
+ react(),
120
+ nxViteTsPaths(),
121
+ viteEnv({
122
+ NODE_ENV: build ? 'production' : 'development',
123
+ }),
124
+ ViteRestart({
125
+ restart: ['package.json', viteConfigPath].filter(
126
+ (x): x is string => !!x
127
+ ),
128
+ }),
129
+ ...minifyPlugin,
130
+ ],
131
+ } as UserConfig;
132
+ return defineConfig(mergeConfig(config, romaConfig));
133
+ };
@@ -0,0 +1,102 @@
1
+ import { ExecutorContext } from '@nx/devkit';
2
+
3
+ const projects = {
4
+ administration: {
5
+ name: 'administration',
6
+ root: 'apps/applications/administration',
7
+ $schema: '../../../node_modules/nx/schemas/project-schema.json',
8
+ sourceRoot: 'apps/applications/administration/src',
9
+ projectType: 'application',
10
+ targets: {
11
+ build: {
12
+ dependsOn: ['^build'],
13
+ inputs: ['production', '^production'],
14
+ executor: '@equinor/roma-nx-plugin:build',
15
+ options: {},
16
+ configurations: {},
17
+ },
18
+ serve: {
19
+ executor: '@equinor/roma-nx-plugin:serve',
20
+ options: {
21
+ port: 3001,
22
+ portal: 'http://localhost:3000',
23
+ devPortal: 'dist/libs/roma-framework/dev-portal',
24
+ },
25
+ configurations: {},
26
+ },
27
+ portal: {
28
+ executor: '@equinor/roma-nx-plugin:portal',
29
+ options: {
30
+ additionalProxyTargets: {
31
+ '/tradeadministration': {
32
+ target:
33
+ 'https://api-dev.gateway.equinor.com/tradeadministration/v1',
34
+ headers: {
35
+ 'Ocp-Apim-Subscription-Key': 'RATSCORE_SUB_KEY',
36
+ },
37
+ },
38
+ },
39
+ },
40
+ configurations: {},
41
+ },
42
+ test: {
43
+ inputs: [
44
+ 'default',
45
+ '^production',
46
+ '{workspaceRoot}/jest.preset.js',
47
+ '{workspaceRoot}/jest.preset.js',
48
+ ],
49
+ executor: '@nx/vite:test',
50
+ outputs: ['{options.reportsDirectory}'],
51
+ options: {
52
+ passWithNoTests: true,
53
+ reportsDirectory:
54
+ '../../../coverage/apps/applications/administration',
55
+ },
56
+ configurations: {},
57
+ },
58
+ lint: {
59
+ inputs: [
60
+ 'default',
61
+ '{workspaceRoot}/.eslintrc.json',
62
+ '{workspaceRoot}/.eslintignore',
63
+ '{workspaceRoot}/eslint.config.js',
64
+ ],
65
+ executor: '@nx/eslint:eslint',
66
+ outputs: ['{options.outputFile}'],
67
+ options: {
68
+ lintFilePatterns: [
69
+ 'apps/applications/administration/**/*.{ts,tsx,js,jsx}',
70
+ ],
71
+ },
72
+ configurations: {},
73
+ },
74
+ },
75
+ tags: ['roma-application'],
76
+ implicitDependencies: [],
77
+ },
78
+ };
79
+
80
+ export const executorContext = {
81
+ root: '/Users/RHENRI/dev/tops-roma/roma-workbench',
82
+ target: {
83
+ dependsOn: ['^build'],
84
+ inputs: ['production', '^production'],
85
+ executor: '@equinor/roma-nx-plugin:build',
86
+ options: {},
87
+ configurations: {},
88
+ },
89
+ projectsConfigurations: {
90
+ projects,
91
+ version: 2,
92
+ },
93
+ workspace: {
94
+ projects,
95
+ version: 2,
96
+ $schema: './node_modules/nx/schemas/nx-schema.json',
97
+ },
98
+ projectName: 'administration',
99
+ targetName: 'build',
100
+ cwd: '/Users/RHENRI/dev/tops-roma/roma-workbench',
101
+ isVerbose: false,
102
+ } as ExecutorContext;
@@ -0,0 +1,29 @@
1
+ import { ExecutorContext } from '@nx/devkit';
2
+ import { ProjectConfiguration } from 'nx/src/config/workspace-json-project-json';
3
+ import { publishApplication } from './publish-script';
4
+ import { PublishExecutorSchema } from './schema';
5
+
6
+ type BuildConfiguration = ProjectConfiguration & {
7
+ outputPath?: string;
8
+ };
9
+
10
+ export default async function runExecutor(
11
+ options: PublishExecutorSchema,
12
+ context: ExecutorContext
13
+ ) {
14
+ const projectName = context.projectName;
15
+ const project = context.workspace.projects[projectName] as BuildConfiguration;
16
+ const buildConfig = project.targets.build as BuildConfiguration;
17
+ const outputPath = buildConfig.outputPath ?? `dist/apps/${projectName}`;
18
+ let success = true;
19
+ try {
20
+ await publishApplication(outputPath, options);
21
+ } catch (ex) {
22
+ console.error(`Error when publishing ${projectName}`);
23
+ console.error(ex);
24
+ success = false;
25
+ }
26
+ return {
27
+ success,
28
+ };
29
+ }
@@ -0,0 +1,33 @@
1
+ export type Manifest = {
2
+ key: string;
3
+ version: Version;
4
+ shortName: string;
5
+ name: string;
6
+ description: string;
7
+ tags: Array<string>;
8
+ hide: boolean;
9
+ order: number;
10
+ type: string;
11
+ accentColor: string;
12
+ icon: string;
13
+ categoryId: string;
14
+ category: Category;
15
+ entry?: string;
16
+ };
17
+
18
+ export type ManifestFile = Omit<Manifest, 'version'> & {
19
+ version: string;
20
+ };
21
+
22
+ export type Version = {
23
+ major: number;
24
+ minor: number;
25
+ patch: number;
26
+ };
27
+
28
+ export type Category = {
29
+ id: string;
30
+ name: string;
31
+ color: string;
32
+ defaultIcon: string;
33
+ };
@@ -0,0 +1,118 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { publishApplication } from './publish-script';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { AppManifest } from '@equinor/fusion-framework-module-app';
5
+
6
+ // Mock external dependencies
7
+ vi.mock('@azure/identity', () => ({
8
+ DefaultAzureCredential: vi.fn().mockImplementation(() => ({
9
+ getToken: vi.fn().mockResolvedValue({ token: 'mock-token' }),
10
+ })),
11
+ }));
12
+
13
+ vi.mock('node:zlib', () => ({
14
+ brotliCompress: vi.fn((input, callback) =>
15
+ callback(null, Buffer.from('mock-brotli'))
16
+ ),
17
+ }));
18
+
19
+ const readFileMocks = vi.hoisted(() => {
20
+ return {
21
+ readFile: vi.fn(),
22
+ };
23
+ });
24
+ vi.mock('node:fs/promises', () => ({
25
+ readFile: readFileMocks.readFile,
26
+ }));
27
+
28
+ // Override fetch
29
+ // @ts-expect-error Only needs a partial implementation
30
+ global.fetch = vi.fn((url: string, req) => {
31
+ if (url.includes('/api/apps/categories')) {
32
+ return Promise.resolve({
33
+ status: 200,
34
+ json: () => Promise.resolve([{ id: 'category1', name: 'Category 1' }]),
35
+ });
36
+ }
37
+
38
+ // Mock response for the publish manifest URL
39
+ if (url.includes('/api/apps') && req?.method === 'POST') {
40
+ return Promise.resolve({
41
+ status: 200,
42
+ json: () => Promise.resolve({ success: true }),
43
+ });
44
+ }
45
+
46
+ // Mock response for the upload bundle URL
47
+ if (url.includes('/api/apps/key/')) {
48
+ return Promise.resolve({
49
+ status: 200,
50
+ json: () => Promise.resolve({ success: true }),
51
+ });
52
+ }
53
+
54
+ // Default to a network error if the URL is not recognized
55
+ return Promise.reject(new Error('Network error'));
56
+ });
57
+
58
+ describe('publishApplication', () => {
59
+ let manifest: string;
60
+ beforeEach(() => {
61
+ vi.clearAllMocks();
62
+ manifest = JSON.stringify({
63
+ categoryId: 'category1',
64
+ key: 'test',
65
+ name: 'Test',
66
+ description: 'Test',
67
+ entry:
68
+ 'https://romadev.equinor.com/cdn/applications/bundle/test/app-bundle.js?version=1.0.0',
69
+ version: {
70
+ major: 1,
71
+ minor: 0,
72
+ patch: 0,
73
+ },
74
+ } as unknown as AppManifest);
75
+ });
76
+
77
+ it('should publish application successfully', async () => {
78
+ // Define your input parameters
79
+ readFileMocks.readFile.mockResolvedValue(Buffer.from(manifest));
80
+ const pathToOutput = '/path/to/output';
81
+ const options = { environment: 'dev', randomVersion: false } as const;
82
+
83
+ // Call the function to test
84
+ await expect(
85
+ publishApplication(pathToOutput, options)
86
+ ).resolves.not.toThrow();
87
+
88
+ // Check if readFile was called with the correct path
89
+ expect(readFile).toHaveBeenCalledWith('/path/to/output/app-bundle.js');
90
+ // Check if fetch was called with the correct parameters
91
+ expect(fetch).toHaveBeenCalledWith(
92
+ expect.stringContaining('api/apps/categories'),
93
+ expect.anything()
94
+ );
95
+ expect(fetch).toHaveBeenCalledWith(
96
+ expect.stringMatching(/api\/apps$/),
97
+ expect.objectContaining({
98
+ body: manifest,
99
+ })
100
+ );
101
+ });
102
+
103
+ it('should throw if manifest is missing', async () => {
104
+ readFileMocks.readFile.mockResolvedValue(Buffer.from(''));
105
+ // Define your input parameters
106
+ const pathToOutput = '/path/to/output';
107
+ const options = { environment: 'dev', randomVersion: true } as const;
108
+
109
+ // Call the function to test
110
+ await expect(publishApplication(pathToOutput, options)).rejects.toThrow();
111
+
112
+ // Check if readFile was called with the correct path
113
+ expect(readFile).toHaveBeenCalledWith('/path/to/output/app-bundle.js');
114
+ expect(readFile).toHaveBeenCalledWith('/path/to/output/manifest.json');
115
+ });
116
+
117
+ // Add more test cases as needed
118
+ });
@@ -0,0 +1,210 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { DefaultAzureCredential } from '@azure/identity';
4
+ import { Manifest } from './manifest-model';
5
+ import type { PublishExecutorSchema } from './schema';
6
+ import { brotliCompress } from 'node:zlib';
7
+ import { promisify } from 'node:util';
8
+
9
+ const brotli = promisify(brotliCompress);
10
+
11
+ /**
12
+ * An enum representing the status of the publish operation.
13
+ * @enum {number}
14
+ */
15
+ enum Status {
16
+ SUCCESS,
17
+ ERROR,
18
+ }
19
+
20
+ /**
21
+ * An object representing the configuration for the publish script.
22
+ *
23
+ * @property apiScopes - An array of API scopes.
24
+ * @property romaUri - The URI of the API.
25
+ * @property randomVersion - Whether we should generate a random version number.
26
+ */
27
+ type Config = {
28
+ romaUri: string;
29
+ apiScopes: Array<string>;
30
+ randomVersion: boolean;
31
+ };
32
+
33
+ /**
34
+ * A map of environment names to their respective configurations.
35
+ */
36
+ const configMap: Record<string, Config> = {
37
+ dev: {
38
+ romaUri: 'https://romadev.equinor.com',
39
+ randomVersion: true,
40
+ apiScopes: ['api://RomaWorkbenchApiNonProd/.default'],
41
+ },
42
+ qa: {
43
+ romaUri: 'https://romaqa.equinor.com',
44
+ randomVersion: true,
45
+ apiScopes: ['api://RomaWorkbenchApiNonProd/.default'],
46
+ },
47
+ production: {
48
+ romaUri: 'https://roma.equinor.com',
49
+ randomVersion: false,
50
+ apiScopes: ['api://RomaWorkbenchApi/.default'],
51
+ },
52
+ };
53
+
54
+ /**
55
+ * Auth token to publish the application
56
+ */
57
+ let token: string;
58
+
59
+ /**
60
+ * Publishes the application to the specified environment.
61
+ *
62
+ * @param pathToOutput - The path to the output directory.
63
+ * @param options - The options for the publish operation.
64
+ * @param version - The version of the application.
65
+ */
66
+ export const publishApplication = async (
67
+ pathToOutput: string,
68
+ options: PublishExecutorSchema
69
+ ) => {
70
+ let env = options.environment;
71
+ // @ts-expect-error Need to rewrite this as nx expects production, not prod.
72
+ if (env === 'prod') env = 'production';
73
+ const config = configMap[env];
74
+ config.randomVersion = options.randomVersion ?? config.randomVersion;
75
+ const bundle = await readFile(join(pathToOutput, 'app-bundle.js'));
76
+ const manifest = await readFile(join(pathToOutput, 'manifest.json'));
77
+ const manifestJsonString = manifest.toString('utf-8');
78
+ const parsedManifest = JSON.parse(manifestJsonString) as Manifest;
79
+ const appName = parsedManifest.key;
80
+ const categories = await getCategories(config);
81
+ const categoryIds = categories.map((c) => c.id);
82
+ if (!categoryIds.includes(parsedManifest.categoryId)) {
83
+ console.log(
84
+ `Manifest validation failed: categoryId ${parsedManifest.categoryId} is not in list of categories`
85
+ );
86
+ console.log(`Valid categories:`);
87
+ console.table(categories, ['id', 'name']);
88
+ console.log(`Publish will now exit.`);
89
+ throw new Error(`ManifestValidationError`);
90
+ }
91
+ console.log(`Reading & uploading bundle for ${appName}`);
92
+ const bundleResult = await uploadBundle(appName, bundle, config);
93
+ if (bundleResult === Status.ERROR) {
94
+ throw new Error('Failed to upload application');
95
+ }
96
+ console.log(`Reading & uploading application manifest to ${config.romaUri}`);
97
+
98
+ const status = await publishManifest(parsedManifest, config);
99
+ if (status === Status.ERROR) {
100
+ throw new Error(`Failed to publish application ${appName}`);
101
+ } else {
102
+ console.log(`Successfully published application ${appName}`);
103
+ }
104
+ };
105
+
106
+ /**
107
+ * Authenticates the user and returns the authentication token.
108
+ *
109
+ * @returns The authentication token.
110
+ */
111
+ async function authenticate(config: Config) {
112
+ if (token) return token;
113
+ const auth = new DefaultAzureCredential();
114
+ const tokenHolder = await auth.getToken(config.apiScopes);
115
+ token = tokenHolder.token;
116
+
117
+ return token;
118
+ }
119
+
120
+ /**
121
+ * Gets a list of valid roma categories
122
+ *
123
+ * @param config - The configuration for the environment.
124
+ * @returns The categories for roma.
125
+ */
126
+ async function getCategories(
127
+ config: Config
128
+ ): Promise<Array<{ id: string; name: string }>> {
129
+ const token = await authenticate(config);
130
+ const req = await fetch(`${config.romaUri}/api/apps/categories`, {
131
+ headers: {
132
+ Authorization: `Bearer ${token}`,
133
+ 'Content-Type': 'application/json',
134
+ },
135
+ });
136
+ if (req.status >= 400) {
137
+ console.error('Failure', req.status);
138
+ return [];
139
+ } else {
140
+ return await req.json();
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Publishes the manifest for the application.
146
+ *
147
+ * @param manifest - The manifest for the application.
148
+ * @param config - The configuration for the application.
149
+ * @returns The status of the publish operation.
150
+ */
151
+ async function publishManifest(manifest: Manifest, config: Config) {
152
+ manifest.description = manifest.description || manifest.name;
153
+ const { major, minor, patch } = manifest.version;
154
+ const version = config.randomVersion
155
+ ? Date.now()
156
+ : `${major}.${minor}.${patch}`;
157
+ manifest.entry = `${config.romaUri}/cdn/applications/bundle/${manifest.key}/app-bundle.js?version=${version}`;
158
+ const token = await authenticate(config);
159
+ const req = await fetch(`${config.romaUri}/api/apps`, {
160
+ method: 'POST',
161
+ headers: {
162
+ Authorization: `Bearer ${token}`,
163
+ 'Content-Type': 'application/json',
164
+ },
165
+ body: JSON.stringify(manifest),
166
+ });
167
+ if (req.status < 400) {
168
+ return Status.SUCCESS;
169
+ } else {
170
+ console.error(
171
+ `Encountered a problem when publishing application: Received statuscode ${req.status}`
172
+ );
173
+ const err = await req.json();
174
+ console.error(err);
175
+ return Status.ERROR;
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Uploads the bundle for the application to Azure Blob Storage.
181
+ *
182
+ * @param appName - The name of the application.
183
+ * @param bundle - The bundle for the application.
184
+ * @param config - The active config
185
+ */
186
+ async function uploadBundle(appName: string, bundle: Buffer, config: Config) {
187
+ const fd = new FormData();
188
+ const br = await brotli(bundle);
189
+ fd.set('bundleFile', new Blob([br.buffer]));
190
+
191
+ const token = await authenticate(config);
192
+ const req = await fetch(`${config.romaUri}/api/apps/key/${appName}/bundle`, {
193
+ method: 'PUT',
194
+ headers: {
195
+ Authorization: `Bearer ${token}`,
196
+ },
197
+ body: fd,
198
+ });
199
+ if (req.status < 400) {
200
+ console.log(`Successfully uploaded bundle to ${appName}/app-bundle.js`);
201
+ return Status.SUCCESS;
202
+ } else {
203
+ console.error(
204
+ `Encountered a problem when publishing application: Received statuscode ${req.status}`
205
+ );
206
+ const err = await req.json();
207
+ console.error(err);
208
+ return Status.ERROR;
209
+ }
210
+ }
@@ -0,0 +1,19 @@
1
+ import { ServeExecutorSchema } from './schema';
2
+ import { ExecutorContext } from '@nx/devkit';
3
+ import { createServer } from './server';
4
+
5
+ export default async function runExecutor(
6
+ options: ServeExecutorSchema,
7
+ context: ExecutorContext
8
+ ) {
9
+ const configs = [];
10
+ if (options.additionalProjects) {
11
+ options.additionalProjects.forEach((project) => {
12
+ const config = context.workspace.projects[project].targets.serve
13
+ .options as ServeExecutorSchema;
14
+ config.name = project;
15
+ configs.push(config);
16
+ });
17
+ }
18
+ return createServer(options, context, configs);
19
+ }
@@ -0,0 +1,20 @@
1
+ import { join } from 'path';
2
+ import { AppManifest } from '@equinor/fusion-framework-module-app';
3
+ import { readJsonFile } from '@nx/devkit';
4
+
5
+ export function getManifest(root: string) {
6
+ let manifest: AppManifest;
7
+ try {
8
+ const packageJson = readJsonFile(join(root, 'package.json'));
9
+ const pkgManifest = packageJson.roma;
10
+ if (pkgManifest) {
11
+ manifest = {
12
+ ...pkgManifest,
13
+ version: packageJson.version,
14
+ };
15
+ }
16
+ } catch {
17
+ manifest = readJsonFile(join(root, 'fusion-manifest.json')) as AppManifest;
18
+ }
19
+ return manifest;
20
+ }
@@ -3,4 +3,6 @@ export type ServeExecutorSchema = {
3
3
  portal?: string;
4
4
  devPortal?: string;
5
5
  open?: boolean;
6
+ additionalProjects?: Array<string>;
7
+ name?: string;
6
8
  };
@@ -22,6 +22,13 @@
22
22
  "type": "boolean",
23
23
  "description": "Whether to open the application in your default browser. Default false",
24
24
  "default": false
25
+ },
26
+ "additionalProjects": {
27
+ "type": "array",
28
+ "description": "Additional projects to serve",
29
+ "items": {
30
+ "type": "string"
31
+ }
25
32
  }
26
33
  },
27
34
  "required": []