-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy-api.js
More file actions
370 lines (328 loc) · 12.3 KB
/
deploy-api.js
File metadata and controls
370 lines (328 loc) · 12.3 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
try {
require('dotenv').config();
} catch (e) {}
const fs = require('fs');
const path = require('path');
const https = require('https');
const FormData = require('form-data');
const CLIENT_ID = process.env.CONTENTSTACK_CLIENT_ID?.trim();
const CLIENT_SECRET = process.env.CONTENTSTACK_CLIENT_SECRET?.trim();
const PROJECT_UID = process.env.PROJECT_UID?.trim();
const ENVIRONMENT_UID = process.env.ENVIRONMENT_UID?.trim();
const REGION_URLS = {
AWS_NA: { auth: 'app.contentstack.com', launch: 'launch-api.contentstack.com' },
AWS_EU: { auth: 'eu-app.contentstack.com', launch: 'eu-launch-api.contentstack.com' },
AWS_AU: { auth: 'au-app.contentstack.com', launch: 'au-launch-api.contentstack.com' },
AZURE_NA: { auth: 'azure-na-app.contentstack.com', launch: 'azure-na-launch-api.contentstack.com' },
AZURE_EU: { auth: 'azure-eu-app.contentstack.com', launch: 'azure-eu-launch-api.contentstack.com' },
GCP_NA: { auth: 'gcp-na-app.contentstack.com', launch: 'gcp-na-launch-api.contentstack.com' },
GCP_EU: { auth: 'gcp-eu-app.contentstack.com', launch: 'gcp-eu-launch-api.contentstack.com' },
STAGE: { auth: 'dev11-app.csnonprod.com', launch: 'dev-launch-api.csnonprod.com' }
};
const CONTENTSTACK_REGION = (process.env.CONTENTSTACK_REGION || '').trim().toUpperCase();
const regionConfig = CONTENTSTACK_REGION ? REGION_URLS[CONTENTSTACK_REGION] : null;
async function getM2MAccessToken() {
return new Promise((resolve, reject) => {
const body = `scopes=${encodeURIComponent('launch:manage')}&grant_type=${encodeURIComponent('client_credentials')}&client_id=${encodeURIComponent(CLIENT_ID)}&client_secret=${encodeURIComponent(CLIENT_SECRET)}`;
const req = https.request({
hostname: regionConfig.auth,
path: '/apps-api/apps/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body)
}
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const parsed = JSON.parse(data);
if (res.statusCode >= 200 && res.statusCode < 300 && parsed.access_token) {
resolve({
token: parsed.access_token,
organizationUid: parsed.organization_uid || null
});
return;
}
if (res.statusCode === 401) {
console.error('Unauthorized - check credentials');
}
if (data && res.statusCode === 400) {
try {
const err = typeof data === 'string' ? JSON.parse(data) : data;
const msg = err.error_description || err.error || err.message || data;
console.error('Token API response:', msg);
} catch (_) {
console.error('Token API response body:', data);
}
}
reject(new Error(`Token request failed: ${res.statusCode}`));
} catch (e) {
reject(new Error(`Parse error: ${e.message}`));
}
});
});
req.on('error', reject);
req.write(body);
req.end();
});
}
function launchApiRequest(apiPath, method, body, accessToken, organizationUid) {
return new Promise((resolve, reject) => {
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'x-cs-api-version': '1.0',
'Accept': 'application/json'
};
if (organizationUid) {
headers['organization_uid'] = organizationUid;
}
const req = https.request({
hostname: regionConfig.launch,
path: apiPath,
method,
headers
}, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const parsed = data ? JSON.parse(data) : {};
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(parsed);
return;
}
if (res.statusCode === 401) {
console.error('Launch API authentication failed');
}
reject(new Error(`API Error ${res.statusCode}`));
} catch (e) {
if (data.includes('<?xml') || data.includes('<Error>')) {
console.error('Invalid API endpoint - check CONTENTSTACK_REGION');
}
reject(new Error(`Parse error: ${e.message}`));
}
});
});
req.on('error', reject);
if (body) {
req.write(JSON.stringify(body));
}
req.end();
});
}
async function getSignedUploadUrl(tokenData) {
const accessToken = typeof tokenData === 'string' ? tokenData : tokenData.token;
const orgUid = typeof tokenData === 'object' ? tokenData.organizationUid : null;
return await launchApiRequest('/projects/upload/signed_url', 'GET', null, accessToken, orgUid);
}
async function uploadZipToSignedUrl(signedUrlData, zipPath) {
return new Promise((resolve, reject) => {
const uploadUrl = signedUrlData.uploadUrl;
if (!uploadUrl) {
reject(new Error('No uploadUrl in signed URL response'));
return;
}
const method = signedUrlData.method;
let responseHeaders = {};
const headersRaw = signedUrlData.headers;
if (Array.isArray(headersRaw)) {
for (const header of headersRaw) {
const k = header.key != null ? String(header.key).trim() : '';
const v = header.value != null ? String(header.value).trim() : '';
if (k && v) {
responseHeaders[header.key] = header.value;
}
}
} else if (headersRaw && typeof headersRaw === 'object') {
responseHeaders = headersRaw;
}
let formFields = {};
const formFieldsRaw = signedUrlData.fields;
if (Array.isArray(formFieldsRaw)) {
for (const field of formFieldsRaw) {
if (field.formFieldKey !== undefined && field.formFieldValue !== undefined) {
formFields[field.formFieldKey] = field.formFieldValue;
} else if (field.key !== undefined && field.value !== undefined) {
formFields[field.key] = field.value;
}
}
} else if (formFieldsRaw && typeof formFieldsRaw === 'object') {
formFields = formFieldsRaw;
}
const url = new URL(uploadUrl);
const fileSize = fs.statSync(zipPath).size;
const hasFormFields = Object.keys(formFields).length > 0;
if (hasFormFields) {
const form = new FormData();
for (const [key, value] of Object.entries(formFields)) {
form.append(key, value);
}
form.append('file', fs.createReadStream(zipPath), {
filename: 'deployment.zip',
contentType: 'application/zip'
});
const formHeaders = form.getHeaders();
form.getLength((err, length) => {
if (err) {
reject(new Error(`Failed to calculate form-data length: ${err.message}`));
return;
}
const headers = { ...responseHeaders, ...formHeaders, 'Content-Length': length };
const req = https.request({
hostname: url.hostname,
path: url.pathname + url.search,
method,
headers
}, (res) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve();
} else {
let errorData = '';
res.on('data', chunk => errorData += chunk);
res.on('end', () => {
const errorMsg = `Upload failed: ${res.statusCode}`;
if (errorData) {
reject(new Error(`${errorMsg} - ${errorData}`));
} else {
reject(new Error(errorMsg));
}
});
}
});
req.on('error', reject);
form.pipe(req);
});
} else {
const headers = { ...responseHeaders };
if (headers['Content-Length'] === undefined) {
headers['Content-Length'] = fileSize;
}
if (headers['Content-Type'] === undefined) {
headers['Content-Type'] = 'application/zip';
}
const req = https.request({
hostname: url.hostname,
path: url.pathname + url.search,
method,
headers
}, (res) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve();
} else {
let errorData = '';
res.on('data', chunk => errorData += chunk);
res.on('end', () => {
const errorMsg = `Upload failed: ${res.statusCode}`;
if (errorData) {
reject(new Error(`${errorMsg} - ${errorData}`));
} else {
reject(new Error(errorMsg));
}
});
}
});
req.on('error', reject);
fs.createReadStream(zipPath).pipe(req);
}
});
}
async function createDeployment(uploadUid, tokenData) {
const apiPath = `/projects/${encodeURIComponent(PROJECT_UID)}/environments/${encodeURIComponent(ENVIRONMENT_UID)}/deployments`;
const body = { uploadUid };
const accessToken = typeof tokenData === 'string' ? tokenData : tokenData.token;
const orgUid = typeof tokenData === 'object' ? tokenData.organizationUid : null;
return await launchApiRequest(apiPath, 'POST', body, accessToken, orgUid);
}
function addDirectoryToArchive(archive, dirPath, basePath, fileCount) {
const files = fs.readdirSync(dirPath);
for (const file of files) {
if (file === 'node_modules') continue;
const fullPath = path.join(dirPath, file);
const relativePath = path.join(basePath, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
addDirectoryToArchive(archive, fullPath, relativePath, fileCount);
} else {
archive.file(fullPath, { name: relativePath });
fileCount.count++;
}
}
return fileCount;
}
function createZipFile(outputPath) {
return new Promise((resolve, reject) => {
const archiver = require('archiver');
const output = fs.createWriteStream(outputPath);
const archive = archiver('zip', { zlib: { level: 9 } });
const fileCount = { count: 0 };
output.on('close', () => resolve());
archive.on('error', reject);
archive.pipe(output);
const rootDir = process.cwd();
const essentialFiles = ['package.json', 'package-lock.json', 'next.config.js', 'pages', 'public', 'app', 'functions'];
const excludedFromZip = ['deploy-api.js'];
for (const file of essentialFiles) {
if (excludedFromZip.includes(file)) continue;
const filePath = path.join(rootDir, file);
if (!fs.existsSync(filePath)) continue;
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
addDirectoryToArchive(archive, filePath, file, fileCount);
}
if (stat.isFile()) {
archive.file(filePath, { name: file });
fileCount.count++;
}
}
archive.finalize();
});
}
async function deploy() {
const missing = [];
if (!PROJECT_UID) missing.push('PROJECT_UID');
if (!ENVIRONMENT_UID) missing.push('ENVIRONMENT_UID');
if (!CONTENTSTACK_REGION) {
missing.push('CONTENTSTACK_REGION');
} else if (!regionConfig) {
console.error('Unknown CONTENTSTACK_REGION:', CONTENTSTACK_REGION);
console.error('Use one of:', Object.keys(REGION_URLS).join(', '));
process.exit(1);
}
if (missing.length > 0) {
console.error('Missing:', missing.join(', '));
process.exit(1);
}
const zipPath = path.join(process.cwd(), 'deployment.zip');
try {
const tokenData = await getM2MAccessToken();
await createZipFile(zipPath);
const signedUrlData = await getSignedUploadUrl(tokenData);
const uploadUrl = signedUrlData.uploadUrl;
const uploadUid = signedUrlData.uploadUid;
if (!uploadUrl || !uploadUid) {
throw new Error('Missing uploadUrl or uploadUid in response');
}
await uploadZipToSignedUrl(signedUrlData, zipPath);
await createDeployment(uploadUid, tokenData);
fs.unlinkSync(zipPath);
} catch (error) {
console.error(`\nDeployment failed: ${error.message}`);
if (error.message.includes('401') || error.message.includes('invalid')) {
console.error('Check M2M app has Launch API permissions');
}
if (error.message.includes('Missing')) {
console.error('Check environment variables');
}
if (error.message.includes('404') || error.message.includes('not found')) {
console.error('Verify PROJECT_UID and ENVIRONMENT_UID');
}
if (fs.existsSync(zipPath)) {
fs.unlinkSync(zipPath);
}
process.exit(1);
}
}
deploy();