finan-code-push 1.0.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.
@@ -0,0 +1,445 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation.
3
+ // Licensed under the MIT License.
4
+ const fs = require("fs");
5
+ const os = require("os");
6
+ const path = require("path");
7
+ const Q = require("q");
8
+ const superagent = require("superagent");
9
+ const recursiveFs = require("recursive-fs");
10
+ const yazl = require("yazl");
11
+ const slash = require("slash");
12
+ var Promise = Q.Promise;
13
+ const hashUtils = require("./hash-utils");
14
+ const packageJson = require("../../package.json");
15
+ // A template string tag function that URL encodes the substituted values
16
+ function urlEncode(strings, ...values) {
17
+ let result = "";
18
+ for (let i = 0; i < strings.length; i++) {
19
+ result += strings[i];
20
+ if (i < values.length) {
21
+ result += encodeURIComponent(values[i]);
22
+ }
23
+ }
24
+ return result;
25
+ }
26
+ class AccountManager {
27
+ static AppPermission = {
28
+ OWNER: "Owner",
29
+ COLLABORATOR: "Collaborator",
30
+ };
31
+ static SERVER_URL = "http://localhost:3000";
32
+ static API_VERSION = 2;
33
+ static ERROR_GATEWAY_TIMEOUT = 504; // Used if there is a network error
34
+ static ERROR_INTERNAL_SERVER = 500;
35
+ static ERROR_NOT_FOUND = 404;
36
+ static ERROR_CONFLICT = 409; // Used if the resource already exists
37
+ static ERROR_UNAUTHORIZED = 401;
38
+ _accessKey;
39
+ _serverUrl;
40
+ _customHeaders;
41
+ constructor(accessKey, customHeaders, serverUrl) {
42
+ if (!accessKey)
43
+ throw new Error("An access key must be specified.");
44
+ this._accessKey = accessKey;
45
+ this._customHeaders = customHeaders;
46
+ this._serverUrl = serverUrl || AccountManager.SERVER_URL;
47
+ }
48
+ get accessKey() {
49
+ return this._accessKey;
50
+ }
51
+ isAuthenticated(throwIfUnauthorized) {
52
+ return Promise((resolve, reject, notify) => {
53
+ const request = superagent.get(`${this._serverUrl}${urlEncode(["/authenticated"])}`);
54
+ this.attachCredentials(request);
55
+ request.end((err, res) => {
56
+ const status = this.getErrorStatus(err, res);
57
+ if (err && status !== AccountManager.ERROR_UNAUTHORIZED) {
58
+ reject(this.getCodePushError(err, res));
59
+ return;
60
+ }
61
+ const authenticated = status === 200;
62
+ if (!authenticated && throwIfUnauthorized) {
63
+ reject(this.getCodePushError(err, res));
64
+ return;
65
+ }
66
+ resolve(authenticated);
67
+ });
68
+ });
69
+ }
70
+ addAccessKey(friendlyName, ttl) {
71
+ if (!friendlyName) {
72
+ throw new Error("A name must be specified when adding an access key.");
73
+ }
74
+ const accessKeyRequest = {
75
+ createdBy: os.hostname(),
76
+ friendlyName,
77
+ ttl,
78
+ };
79
+ return this.post(urlEncode(["/accessKeys/"]), JSON.stringify(accessKeyRequest), /*expectResponseBody=*/ true).then((response) => {
80
+ return {
81
+ createdTime: response.body.accessKey.createdTime,
82
+ expires: response.body.accessKey.expires,
83
+ key: response.body.accessKey.name,
84
+ name: response.body.accessKey.friendlyName,
85
+ };
86
+ });
87
+ }
88
+ getAccessKey(accessKeyName) {
89
+ return this.get(urlEncode([`/accessKeys/${accessKeyName}`])).then((res) => {
90
+ return {
91
+ createdTime: res.body.accessKey.createdTime,
92
+ expires: res.body.accessKey.expires,
93
+ name: res.body.accessKey.friendlyName,
94
+ };
95
+ });
96
+ }
97
+ getAccessKeys() {
98
+ return this.get(urlEncode(["/accessKeys"])).then((res) => {
99
+ const accessKeys = [];
100
+ res.body.accessKeys.forEach((serverAccessKey) => {
101
+ !serverAccessKey.isSession &&
102
+ accessKeys.push({
103
+ createdTime: serverAccessKey.createdTime,
104
+ expires: serverAccessKey.expires,
105
+ name: serverAccessKey.friendlyName,
106
+ });
107
+ });
108
+ return accessKeys;
109
+ });
110
+ }
111
+ getSessions() {
112
+ return this.get(urlEncode(["/accessKeys"])).then((res) => {
113
+ // A machine name might be associated with multiple session keys,
114
+ // but we should only return one per machine name.
115
+ const sessionMap = {};
116
+ const now = new Date().getTime();
117
+ res.body.accessKeys.forEach((serverAccessKey) => {
118
+ if (serverAccessKey.isSession && serverAccessKey.expires > now) {
119
+ sessionMap[serverAccessKey.createdBy] = {
120
+ loggedInTime: serverAccessKey.createdTime,
121
+ machineName: serverAccessKey.createdBy,
122
+ };
123
+ }
124
+ });
125
+ const sessions = Object.keys(sessionMap).map((machineName) => sessionMap[machineName]);
126
+ return sessions;
127
+ });
128
+ }
129
+ patchAccessKey(oldName, newName, ttl) {
130
+ const accessKeyRequest = {
131
+ friendlyName: newName,
132
+ ttl,
133
+ };
134
+ return this.patch(urlEncode([`/accessKeys/${oldName}`]), JSON.stringify(accessKeyRequest)).then((res) => {
135
+ return {
136
+ createdTime: res.body.accessKey.createdTime,
137
+ expires: res.body.accessKey.expires,
138
+ name: res.body.accessKey.friendlyName,
139
+ };
140
+ });
141
+ }
142
+ removeAccessKey(name) {
143
+ return this.del(urlEncode([`/accessKeys/${name}`])).then(() => null);
144
+ }
145
+ removeSession(machineName) {
146
+ return this.del(urlEncode([`/sessions/${machineName}`])).then(() => null);
147
+ }
148
+ // Account
149
+ getAccountInfo() {
150
+ return this.get(urlEncode(["/account"])).then((res) => res.body.account);
151
+ }
152
+ // Apps
153
+ getApps() {
154
+ return this.get(urlEncode(["/apps"])).then((res) => res.body.apps);
155
+ }
156
+ getApp(appName) {
157
+ return this.get(urlEncode([`/apps/${appName}`])).then((res) => res.body.app);
158
+ }
159
+ addApp(appName) {
160
+ const app = { name: appName };
161
+ return this.post(urlEncode(["/apps/"]), JSON.stringify(app), /*expectResponseBody=*/ false).then(() => app);
162
+ }
163
+ removeApp(appName) {
164
+ return this.del(urlEncode([`/apps/${appName}`])).then(() => null);
165
+ }
166
+ renameApp(oldAppName, newAppName) {
167
+ return this.patch(urlEncode([`/apps/${oldAppName}`]), JSON.stringify({ name: newAppName })).then(() => null);
168
+ }
169
+ transferApp(appName, email) {
170
+ return this.post(urlEncode([`/apps/${appName}/transfer/${email}`]), /*requestBody=*/ null, /*expectResponseBody=*/ false).then(() => null);
171
+ }
172
+ // Collaborators
173
+ getCollaborators(appName) {
174
+ return this.get(urlEncode([`/apps/${appName}/collaborators`])).then((res) => res.body.collaborators);
175
+ }
176
+ addCollaborator(appName, email) {
177
+ return this.post(urlEncode([`/apps/${appName}/collaborators/${email}`]),
178
+ /*requestBody=*/ null,
179
+ /*expectResponseBody=*/ false).then(() => null);
180
+ }
181
+ removeCollaborator(appName, email) {
182
+ return this.del(urlEncode([`/apps/${appName}/collaborators/${email}`])).then(() => null);
183
+ }
184
+ // Deployments
185
+ addDeployment(appName, deploymentName, deploymentKey) {
186
+ const deployment = { name: deploymentName, key: deploymentKey };
187
+ return this.post(urlEncode([`/apps/${appName}/deployments/`]), JSON.stringify(deployment), /*expectResponseBody=*/ true).then((res) => res.body.deployment);
188
+ }
189
+ clearDeploymentHistory(appName, deploymentName) {
190
+ return this.del(urlEncode([`/apps/${appName}/deployments/${deploymentName}/history`])).then(() => null);
191
+ }
192
+ getDeployments(appName) {
193
+ return this.get(urlEncode([`/apps/${appName}/deployments/`])).then((res) => res.body.deployments);
194
+ }
195
+ getDeployment(appName, deploymentName) {
196
+ return this.get(urlEncode([`/apps/${appName}/deployments/${deploymentName}`])).then((res) => res.body.deployment);
197
+ }
198
+ renameDeployment(appName, oldDeploymentName, newDeploymentName) {
199
+ return this.patch(urlEncode([`/apps/${appName}/deployments/${oldDeploymentName}`]), JSON.stringify({ name: newDeploymentName })).then(() => null);
200
+ }
201
+ removeDeployment(appName, deploymentName) {
202
+ return this.del(urlEncode([`/apps/${appName}/deployments/${deploymentName}`])).then(() => null);
203
+ }
204
+ getDeploymentMetrics(appName, deploymentName) {
205
+ return this.get(urlEncode([`/apps/${appName}/deployments/${deploymentName}/metrics`])).then((res) => res.body.metrics);
206
+ }
207
+ getDeploymentHistory(appName, deploymentName) {
208
+ return this.get(urlEncode([`/apps/${appName}/deployments/${deploymentName}/history`])).then((res) => res.body.history);
209
+ }
210
+ release(appName, deploymentName, filePath, targetBinaryVersion, updateMetadata, uploadProgressCallback) {
211
+ return Promise((resolve, reject, notify) => {
212
+ updateMetadata.appVersion = targetBinaryVersion;
213
+ this.packageFileFromPath(filePath)
214
+ .then((packageFile) => {
215
+ // Compute package hash from the zip file
216
+ hashUtils.generatePackageManifestFromZip(packageFile.path)
217
+ .then((manifest) => {
218
+ let hashPromise;
219
+ if (manifest) {
220
+ hashPromise = manifest.computePackageHash();
221
+ }
222
+ else {
223
+ // If not a valid zip, hash the file directly
224
+ hashPromise = hashUtils.hashFile(packageFile.path);
225
+ }
226
+ return hashPromise.then((packageHash) => {
227
+ // Step 1: Get pre-signed upload URL from server
228
+ const uploadUrlEndpoint = urlEncode([`/apps/${appName}/deployments/${deploymentName}/upload-url`]);
229
+ return this.post(uploadUrlEndpoint, JSON.stringify({ packageInfo: updateMetadata }), true)
230
+ .then((response) => {
231
+ const { uploadUrl, blobId } = response.body;
232
+ // Step 2: Upload directly to S3 using pre-signed URL
233
+ const fileBuffer = fs.readFileSync(packageFile.path);
234
+ const fileSize = fileBuffer.length;
235
+ const uploadRequest = superagent
236
+ .put(uploadUrl)
237
+ .set("Content-Type", "application/octet-stream")
238
+ .set("Content-Length", fileSize.toString())
239
+ .send(fileBuffer);
240
+ uploadRequest.on("progress", (event) => {
241
+ if (uploadProgressCallback && event && event.total > 0) {
242
+ const currentProgress = (event.loaded / event.total) * 100;
243
+ uploadProgressCallback(currentProgress);
244
+ }
245
+ });
246
+ uploadRequest.end((err, res) => {
247
+ if (packageFile.isTemporary) {
248
+ fs.unlinkSync(packageFile.path);
249
+ }
250
+ if (err) {
251
+ reject({
252
+ message: `Failed to upload to S3: ${err.message}`,
253
+ statusCode: err.status || AccountManager.ERROR_GATEWAY_TIMEOUT,
254
+ });
255
+ return;
256
+ }
257
+ // Step 3: Finalize release on server with computed hash
258
+ const finalizeEndpoint = urlEncode([`/apps/${appName}/deployments/${deploymentName}/finalize-release`]);
259
+ const finalizeBody = JSON.stringify({
260
+ blobId,
261
+ packageInfo: updateMetadata,
262
+ packageSize: fileSize,
263
+ packageHash: packageHash,
264
+ });
265
+ this.post(finalizeEndpoint, finalizeBody, false)
266
+ .then(() => {
267
+ resolve(null);
268
+ })
269
+ .catch((finalizeErr) => {
270
+ reject(finalizeErr);
271
+ });
272
+ });
273
+ });
274
+ });
275
+ })
276
+ .catch((hashErr) => {
277
+ if (packageFile.isTemporary) {
278
+ fs.unlinkSync(packageFile.path);
279
+ }
280
+ reject({
281
+ message: `Failed to compute package hash: ${hashErr.message}`,
282
+ statusCode: AccountManager.ERROR_INTERNAL_SERVER,
283
+ });
284
+ });
285
+ })
286
+ .catch((err) => {
287
+ reject({
288
+ message: err.message,
289
+ statusCode: AccountManager.ERROR_INTERNAL_SERVER,
290
+ });
291
+ });
292
+ });
293
+ }
294
+ patchRelease(appName, deploymentName, label, updateMetadata) {
295
+ updateMetadata.label = label;
296
+ const requestBody = JSON.stringify({ packageInfo: updateMetadata });
297
+ return this.patch(urlEncode([`/apps/${appName}/deployments/${deploymentName}/release`]), requestBody,
298
+ /*expectResponseBody=*/ false).then(() => null);
299
+ }
300
+ promote(appName, sourceDeploymentName, destinationDeploymentName, updateMetadata) {
301
+ const requestBody = JSON.stringify({ packageInfo: updateMetadata });
302
+ return this.post(urlEncode([`/apps/${appName}/deployments/${sourceDeploymentName}/promote/${destinationDeploymentName}`]), requestBody,
303
+ /*expectResponseBody=*/ false).then(() => null);
304
+ }
305
+ rollback(appName, deploymentName, targetRelease) {
306
+ return this.post(urlEncode([`/apps/${appName}/deployments/${deploymentName}/rollback/${targetRelease || ``}`]),
307
+ /*requestBody=*/ null,
308
+ /*expectResponseBody=*/ false).then(() => null);
309
+ }
310
+ packageFileFromPath(filePath) {
311
+ let getPackageFilePromise;
312
+ if (fs.lstatSync(filePath).isDirectory()) {
313
+ getPackageFilePromise = Promise((resolve, reject) => {
314
+ const directoryPath = filePath;
315
+ recursiveFs.readdirr(directoryPath, (error, directories, files) => {
316
+ if (error) {
317
+ reject(error);
318
+ return;
319
+ }
320
+ const baseDirectoryPath = path.dirname(directoryPath);
321
+ const fileName = this.generateRandomFilename(15) + ".zip";
322
+ const zipFile = new yazl.ZipFile();
323
+ const writeStream = fs.createWriteStream(fileName);
324
+ zipFile.outputStream
325
+ .pipe(writeStream)
326
+ .on("error", (error) => {
327
+ reject(error);
328
+ })
329
+ .on("close", () => {
330
+ filePath = path.join(process.cwd(), fileName);
331
+ resolve({ isTemporary: true, path: filePath });
332
+ });
333
+ for (let i = 0; i < files.length; ++i) {
334
+ const file = files[i];
335
+ // yazl does not like backslash (\) in the metadata path.
336
+ const relativePath = slash(path.relative(baseDirectoryPath, file));
337
+ zipFile.addFile(file, relativePath);
338
+ }
339
+ zipFile.end();
340
+ });
341
+ });
342
+ }
343
+ else {
344
+ getPackageFilePromise = Q({ isTemporary: false, path: filePath });
345
+ }
346
+ return getPackageFilePromise;
347
+ }
348
+ generateRandomFilename(length) {
349
+ let filename = "";
350
+ const validChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
351
+ for (let i = 0; i < length; i++) {
352
+ filename += validChar.charAt(Math.floor(Math.random() * validChar.length));
353
+ }
354
+ return filename;
355
+ }
356
+ get(endpoint, expectResponseBody = true) {
357
+ return this.makeApiRequest("get", endpoint, /*requestBody=*/ null, expectResponseBody, /*contentType=*/ null);
358
+ }
359
+ post(endpoint, requestBody, expectResponseBody, contentType = "application/json;charset=UTF-8") {
360
+ return this.makeApiRequest("post", endpoint, requestBody, expectResponseBody, contentType);
361
+ }
362
+ patch(endpoint, requestBody, expectResponseBody = false, contentType = "application/json;charset=UTF-8") {
363
+ return this.makeApiRequest("patch", endpoint, requestBody, expectResponseBody, contentType);
364
+ }
365
+ del(endpoint, expectResponseBody = false) {
366
+ return this.makeApiRequest("del", endpoint, /*requestBody=*/ null, expectResponseBody, /*contentType=*/ null);
367
+ }
368
+ makeApiRequest(method, endpoint, requestBody, expectResponseBody, contentType) {
369
+ return Promise((resolve, reject, notify) => {
370
+ let request = superagent[method](this._serverUrl + endpoint);
371
+ this.attachCredentials(request);
372
+ if (requestBody) {
373
+ if (contentType) {
374
+ request = request.set("Content-Type", contentType);
375
+ }
376
+ request = request.send(requestBody);
377
+ }
378
+ request.end((err, res) => {
379
+ if (err) {
380
+ reject(this.getCodePushError(err, res));
381
+ return;
382
+ }
383
+ let body;
384
+ try {
385
+ body = JSON.parse(res.text);
386
+ }
387
+ catch (err) { }
388
+ if (res.ok) {
389
+ if (expectResponseBody && !body) {
390
+ reject({
391
+ message: `Could not parse response: ${res.text}`,
392
+ statusCode: AccountManager.ERROR_INTERNAL_SERVER,
393
+ });
394
+ }
395
+ else {
396
+ resolve({
397
+ headers: res.header,
398
+ body: body,
399
+ });
400
+ }
401
+ }
402
+ else {
403
+ if (body) {
404
+ reject({
405
+ message: body.message,
406
+ statusCode: this.getErrorStatus(err, res),
407
+ });
408
+ }
409
+ else {
410
+ reject({
411
+ message: res.text,
412
+ statusCode: this.getErrorStatus(err, res),
413
+ });
414
+ }
415
+ }
416
+ });
417
+ });
418
+ }
419
+ getCodePushError(error, response) {
420
+ if (error.syscall === "getaddrinfo") {
421
+ error.message = `Unable to connect to the CodePush server. Are you offline, or behind a firewall or proxy?\n(${error.message})`;
422
+ }
423
+ return {
424
+ message: this.getErrorMessage(error, response),
425
+ statusCode: this.getErrorStatus(error, response),
426
+ };
427
+ }
428
+ getErrorStatus(error, response) {
429
+ return (error && error.status) || (response && response.status) || AccountManager.ERROR_GATEWAY_TIMEOUT;
430
+ }
431
+ getErrorMessage(error, response) {
432
+ return response && response.text ? response.text : error.message;
433
+ }
434
+ attachCredentials(request) {
435
+ if (this._customHeaders) {
436
+ for (const headerName in this._customHeaders) {
437
+ request.set(headerName, this._customHeaders[headerName]);
438
+ }
439
+ }
440
+ request.set("Accept", `application/vnd.code-push.v${AccountManager.API_VERSION}+json`);
441
+ request.set("Authorization", `Bearer ${this._accessKey}`);
442
+ request.set("X-CodePush-SDK-Version", packageJson.version);
443
+ }
444
+ }
445
+ module.exports = AccountManager;