-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdeploy.ts
More file actions
347 lines (313 loc) · 11 KB
/
deploy.ts
File metadata and controls
347 lines (313 loc) · 11 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
* Copyright (c) 2025, Salesforce, Inc.
* SPDX-License-Identifier: Apache-2
* For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0
*/
import {Args, Flags} from '@oclif/core';
import {MrtCommand} from '@salesforce/b2c-tooling-sdk/cli';
import {
pushBundle,
createDeployment,
waitForEnv,
DEFAULT_SSR_PARAMETERS,
type PushResult,
type CreateDeploymentResult,
type MrtEnvironment,
} from '@salesforce/b2c-tooling-sdk/operations/mrt';
import {t, withDocs} from '../../../i18n/index.js';
/**
* Parses a glob pattern string into an array of patterns.
* Accepts either a JSON array (e.g. '["server/**\/*", "ssr.{js,mjs}"]')
* or a comma-separated string (e.g. 'server/**\/*,ssr.js').
* JSON array format supports brace expansion in individual patterns.
*/
function parseGlobPatterns(value: string): string[] {
const trimmed = value.trim();
if (trimmed.startsWith('[')) {
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed) || !parsed.every((item) => typeof item === 'string')) {
throw new Error(`Invalid glob pattern array: expected an array of strings`);
}
return parsed.map((s: string) => s.trim()).filter(Boolean);
}
return trimmed
.split(',')
.map((s) => s.trim())
.filter(Boolean);
}
/**
* Parses SSR parameter flags into a key-value object.
* Accepts format: key=value
*/
function parseSsrParams(params: string[]): Record<string, string> {
const result: Record<string, string> = {};
for (const param of params) {
const eqIndex = param.indexOf('=');
if (eqIndex === -1) {
throw new Error(`Invalid SSR parameter format: "${param}". Expected key=value format.`);
}
const key = param.slice(0, eqIndex);
const value = param.slice(eqIndex + 1);
result[key] = value;
}
return result;
}
type DeployResult = CreateDeploymentResult | MrtEnvironment | PushResult;
/**
* Deploy a bundle to Managed Runtime.
*
* Without bundleId: Creates a bundle from the local build directory and uploads it.
* Optionally deploys to a target environment if --environment is specified.
*
* With bundleId: Deploys an existing bundle to the specified environment.
*/
export default class MrtBundleDeploy extends MrtCommand<typeof MrtBundleDeploy> {
static args = {
bundleId: Args.integer({
description: 'Bundle ID to deploy (omit to push local build)',
required: false,
}),
};
static description = withDocs(
t('commands.mrt.bundle.deploy.description', 'Push a local build or deploy an existing bundle to Managed Runtime'),
'/cli/mrt.html#b2c-mrt-bundle-deploy',
);
static enableJsonFlag = true;
static examples = [
'<%= config.bin %> <%= command.id %> --project my-storefront',
'<%= config.bin %> <%= command.id %> --project my-storefront --environment staging',
'<%= config.bin %> <%= command.id %> --project my-storefront --environment production --message "Release v1.0.0"',
'<%= config.bin %> <%= command.id %> --project my-storefront --build-dir ./dist',
'<%= config.bin %> <%= command.id %> --project my-storefront --node-version 20.x',
'<%= config.bin %> <%= command.id %> --project my-storefront --ssr-param SSRProxyPath=/api',
'<%= config.bin %> <%= command.id %> 12345 --project my-storefront --environment staging',
'<%= config.bin %> <%= command.id %> 12345 --project my-storefront --environment staging --wait',
];
static flags = {
...MrtCommand.baseFlags,
message: Flags.string({
char: 'm',
description: 'Bundle message/description (only for local builds)',
}),
'build-dir': Flags.string({
char: 'b',
description: 'Path to the build directory (only for local builds)',
default: 'build',
}),
'ssr-only': Flags.string({
description: 'Glob patterns for server-only files (comma-separated or JSON array, only for local builds)',
default: 'ssr.js,ssr.mjs,server/**/*',
}),
'ssr-shared': Flags.string({
description: 'Glob patterns for shared files (comma-separated or JSON array, only for local builds)',
default: 'static/**/*,client/**/*',
}),
'node-version': Flags.string({
char: 'n',
description: `Node.js version for SSR runtime (default: ${DEFAULT_SSR_PARAMETERS.SSRFunctionNodeVersion}, only for local builds)`,
}),
'ssr-param': Flags.string({
description: 'SSR parameter in key=value format (can be specified multiple times, only for local builds)',
multiple: true,
default: [],
}),
wait: Flags.boolean({
char: 'w',
description: 'Wait for the deployment to complete before returning',
default: false,
}),
'poll-interval': Flags.integer({
description: 'Polling interval in seconds when using --wait',
default: 30,
dependsOn: ['wait'],
}),
timeout: Flags.integer({
description: 'Maximum time to wait in seconds when using --wait (0 for no timeout)',
default: 600,
dependsOn: ['wait'],
}),
};
protected operations = {
pushBundle,
createDeployment,
waitForEnv,
};
async run(): Promise<DeployResult> {
this.requireMrtCredentials();
const {bundleId} = this.args;
if (bundleId !== undefined) {
return this.deployExistingBundle(bundleId);
}
return this.pushLocalBuild();
}
/**
* Deploy an existing bundle to an environment.
*/
private async deployExistingBundle(bundleId: number): Promise<CreateDeploymentResult | MrtEnvironment> {
const {mrtProject: project, mrtEnvironment: environment} = this.resolvedConfig.values;
if (!project) {
this.error('MRT project is required. Provide --project flag, set MRT_PROJECT, or set mrtProject in dw.json.');
}
if (!environment) {
this.error(
'MRT environment is required when deploying an existing bundle. Provide --environment flag, set MRT_ENVIRONMENT, or set mrtEnvironment in dw.json.',
);
}
this.log(
t('commands.mrt.bundle.deploy.deploying', 'Deploying bundle {{bundleId}} to {{project}}/{{environment}}...', {
bundleId,
project,
environment,
}),
);
try {
const result = await this.operations.createDeployment(
{
projectSlug: project,
targetSlug: environment,
bundleId,
origin: this.resolvedConfig.values.mrtOrigin,
},
this.getMrtAuth(),
);
if (!this.jsonEnabled()) {
this.log(
t(
'commands.mrt.bundle.deploy.deploySuccess',
'Deployment started. Bundle {{bundleId}} is being deployed to {{environment}}.',
{
bundleId,
environment,
},
),
);
if (!this.flags.wait) {
this.log(
t(
'commands.mrt.bundle.deploy.note',
'Note: Deployments are asynchronous. Use "b2c mrt env get" or the Runtime Admin dashboard to check status.',
),
);
}
}
if (this.flags.wait) {
return this.waitForDeployment(project, environment);
}
return result;
} catch (error) {
if (error instanceof Error) {
this.error(
t('commands.mrt.bundle.deploy.deployFailed', 'Failed to create deployment: {{message}}', {
message: error.message,
}),
);
}
throw error;
}
}
/**
* Push a local build to create a new bundle.
*/
private async pushLocalBuild(): Promise<MrtEnvironment | PushResult> {
const {mrtProject: project, mrtEnvironment: target} = this.resolvedConfig.values;
const {message} = this.flags;
if (!project) {
this.error('MRT project is required. Provide --project flag, set MRT_PROJECT, or set mrtProject in dw.json.');
}
const buildDir = this.flags['build-dir'];
const ssrOnly = parseGlobPatterns(this.flags['ssr-only']);
const ssrShared = parseGlobPatterns(this.flags['ssr-shared']);
// Build SSR parameters from flags
const ssrParameters: Record<string, unknown> = parseSsrParams(this.flags['ssr-param']);
// --node-version is a convenience flag for SSRFunctionNodeVersion
if (this.flags['node-version']) {
ssrParameters.SSRFunctionNodeVersion = this.flags['node-version'];
}
this.log(t('commands.mrt.bundle.deploy.pushing', 'Pushing bundle to {{project}}...', {project}));
if (target) {
this.log(
t('commands.mrt.bundle.deploy.willDeploy', 'Bundle will be deployed to {{environment}}', {environment: target}),
);
}
try {
const result = await this.operations.pushBundle(
{
projectSlug: project,
target,
message,
buildDirectory: buildDir,
ssrOnly,
ssrShared,
ssrParameters,
origin: this.resolvedConfig.values.mrtOrigin,
},
this.getMrtAuth(),
);
// Consolidated success output
const deployedMsg = result.deployed && result.target ? ` and deployed to ${result.target}` : '';
this.log(
t(
'commands.mrt.bundle.deploy.pushSuccess',
'Bundle #{{bundleId}} pushed to {{project}}{{deployed}} ({{message}})',
{
bundleId: String(result.bundleId),
project: result.projectSlug,
deployed: deployedMsg,
message: result.message,
},
),
);
if (this.flags.wait) {
if (!target) {
this.warn('--wait was specified but no environment target was provided. Skipping wait.');
return result;
}
return this.waitForDeployment(project, target);
}
return result;
} catch (error) {
if (error instanceof Error) {
this.error(t('commands.mrt.bundle.deploy.pushFailed', 'Push failed: {{message}}', {message: error.message}));
}
throw error;
}
}
/**
* Wait for a deployment to complete by polling the environment state.
*/
private async waitForDeployment(project: string, environment: string): Promise<MrtEnvironment> {
this.log(
t('commands.mrt.bundle.deploy.waiting', 'Waiting for deployment to complete on {{environment}}...', {
environment,
}),
);
const envResult = await this.operations.waitForEnv(
{
projectSlug: project,
slug: environment,
origin: this.resolvedConfig.values.mrtOrigin,
pollIntervalSeconds: this.flags['poll-interval'],
timeoutSeconds: this.flags.timeout,
onPoll: (info) => {
if (!this.jsonEnabled()) {
this.log(
t('commands.mrt.bundle.deploy.state', '[{{elapsed}}s] State: {{state}}', {
elapsed: String(info.elapsedSeconds),
state: info.state,
}),
);
}
},
},
this.getMrtAuth(),
);
if (!this.jsonEnabled()) {
this.log(
t('commands.mrt.bundle.deploy.deployComplete', 'Deployment complete. Environment is {{state}}.', {
state: envResult.state ?? 'unknown',
}),
);
}
return envResult;
}
}