-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathreact.ts
More file actions
275 lines (259 loc) · 8.08 KB
/
react.ts
File metadata and controls
275 lines (259 loc) · 8.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import {
addDependenciesToPackageJson,
generateFiles,
joinPathFragments,
OverwriteStrategy,
ProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nx/devkit';
import { kebabCase, toClassName } from '../../names';
import { sortObjectKeys } from '../../object';
import { updateGitIgnore } from '../../git';
import runtimeConfigGenerator from '../../../ts/react-website/runtime-config/generator';
import { addSingleImport, applyGritQL } from '../../ast';
import { addTargetToServeLocal } from '../../../connection/serve-local';
import { withVersions } from '../../versions';
export interface AddOpenApiReactClientOptions {
/**
* The react project to add the openapi client and build targets to
*/
frontendProjectConfig: ProjectConfiguration;
/**
* The backend project which serves the api
*/
backendProjectConfig: ProjectConfiguration;
/**
* The project which builds/generates the openapi spec
*/
specBuildProject: ProjectConfiguration;
/**
* Name of the api
*/
apiName: string;
/**
* Path to the openapi spec from the workspace root
*/
specPath: string;
/**
* Fully qualified target name for the target that builds/generates the openapi spec
*/
specBuildTargetName: string;
/**
* Authentication method
*/
auth: 'IAM' | 'Cognito' | 'None';
/**
* Port on which the backend project's local server listens
*/
port: number;
/**
* When true, the generated provider reads from runtimeConfig.agentRuntimes
* and converts Bedrock AgentCore Runtime ARNs to HTTP URLs.
* When false (default), reads from runtimeConfig.apis directly.
*/
isAgentRuntime?: boolean;
/**
* When true, skips the serve-local setup. Use this when the caller
* handles serve-local configuration separately (e.g. agent connections
* that use a component-specific serve-local target instead of 'serve').
*/
skipServeLocal?: boolean;
}
/**
* Adds an OpenAPI React client to the frontend project along with supporting build targets
*/
export const addOpenApiReactClient = async (
tree: Tree,
{
apiName,
frontendProjectConfig,
backendProjectConfig,
specBuildProject,
specPath,
specBuildTargetName,
auth,
port,
isAgentRuntime = false,
skipServeLocal = false,
}: AddOpenApiReactClientOptions,
) => {
const clientGenTarget = `generate:${kebabCase(apiName)}-client`;
const clientGenWatchTarget = `watch-${clientGenTarget}`;
const generatedClientDir = joinPathFragments('generated', kebabCase(apiName));
const generatedClientDirFromRoot = joinPathFragments(
frontendProjectConfig.sourceRoot,
generatedClientDir,
);
// Add TypeScript client generation to Frontend project.json
updateProjectConfiguration(tree, frontendProjectConfig.name, {
...frontendProjectConfig,
targets: sortObjectKeys({
...frontendProjectConfig.targets,
// Generate should run before compile and bundle as the client is created as part of the website src
...Object.fromEntries(
['compile', 'bundle'].map((target) => [
target,
{
...frontendProjectConfig.targets?.[target],
dependsOn: [
...(
frontendProjectConfig.targets?.[target]?.dependsOn ?? []
).filter((t) => t !== clientGenTarget),
clientGenTarget,
],
},
]),
),
[clientGenTarget]: {
cache: true,
executor: 'nx:run-commands',
inputs: [
{
dependentTasksOutputFiles: '**/*.json',
},
],
outputs: [
joinPathFragments('{workspaceRoot}', generatedClientDirFromRoot),
],
options: {
commands: [
`nx g @aws/nx-plugin:open-api#ts-hooks --openApiSpecPath="${specPath}" --outputPath="${generatedClientDirFromRoot}" --no-interactive`,
],
},
dependsOn: [specBuildTargetName],
},
// Watch target for regenerating the client
[clientGenWatchTarget]: {
executor: 'nx:run-commands',
options: {
commands: [
`nx watch --projects=${specBuildProject.name} --includeDependentProjects -- nx run ${frontendProjectConfig.name}:"${clientGenTarget}"`,
],
},
continuous: true,
},
}),
});
const relativeSrcDir = frontendProjectConfig.sourceRoot.slice(
frontendProjectConfig.root.length + 1,
);
// Ignore the generated client by default
// Users can safely remove the entry from the .gitignore if they prefer to check it in
updateGitIgnore(tree, frontendProjectConfig.root, (patterns) => [
...patterns,
joinPathFragments(relativeSrcDir, generatedClientDir),
]);
// Ensure that the frontend has runtime config as we'll use the url for creating the client
await runtimeConfigGenerator(tree, {
project: frontendProjectConfig.name,
});
// Add sigv4 fetch
if (auth === 'IAM') {
generateFiles(
tree,
joinPathFragments(__dirname, '../../files/website/hooks/sigv4'),
joinPathFragments(frontendProjectConfig.sourceRoot, 'hooks'),
{},
{
overwriteStrategy: OverwriteStrategy.KeepExisting,
},
);
}
// Generate the tanstack query provider if it does not exist already
generateFiles(
tree,
joinPathFragments(
__dirname,
'../../files/website/components/tanstack-query',
),
joinPathFragments(frontendProjectConfig.sourceRoot, 'components'),
{},
{
overwriteStrategy: OverwriteStrategy.KeepExisting,
},
);
const apiNameClassName = toClassName(apiName);
// Add a hook to instantiate the client
generateFiles(
tree,
joinPathFragments(__dirname, 'files'),
frontendProjectConfig.sourceRoot,
{
auth,
apiName,
apiNameClassName,
generatedClientDir,
isAgentRuntime,
},
);
// Update main.tsx to add required providers
const mainTsxPath = joinPathFragments(
frontendProjectConfig.sourceRoot,
'main.tsx',
);
// Add the query client provider if it doesn't exist already
await addSingleImport(
tree,
mainTsxPath,
'QueryClientProvider',
'./components/QueryClientProvider',
);
await applyGritQL(
tree,
mainTsxPath,
'`<App />` => `<QueryClientProvider><App /></QueryClientProvider>` where { $program <: not contains `<QueryClientProvider>$_</QueryClientProvider>` }',
);
// Add the api provider if it does not exist
const providerName = `${apiNameClassName}Provider`;
await addSingleImport(
tree,
mainTsxPath,
providerName,
`./components/${providerName}`,
);
await applyGritQL(
tree,
mainTsxPath,
`\`<App />\` => \`<${providerName}><App /></${providerName}>\` where { $program <: not contains \`<${providerName}>$_</${providerName}>\` }`,
);
// Update serve-local on the website to use our local server.
// Callers that handle serve-local separately (e.g. agent connections) set skipServeLocal.
if (!skipServeLocal) {
await addTargetToServeLocal(
tree,
frontendProjectConfig.name,
backendProjectConfig.name,
{
url: `http://localhost:${port}/`,
apiName,
// Additionally add a dependency on the generate watch command to ensure that local
// API changes that affect the client are also reloaded.
// We include a dependency on the generate target as watch ONLY triggers on a change,
// and we need to ensure the client is generated the first time if not already present.
additionalDependencyTargets: [clientGenTarget, clientGenWatchTarget],
},
);
}
addDependenciesToPackageJson(
tree,
withVersions([
...((auth === 'IAM'
? [
'oidc-client-ts',
'react-oidc-context',
'@aws-sdk/credential-providers',
'aws4fetch',
]
: []) as any),
...((auth === 'Cognito' ? ['react-oidc-context'] : []) as any),
'@tanstack/react-query',
'@tanstack/react-query-devtools',
]),
withVersions(['@smithy/types']),
);
};