@novacraft-engineering/pulsar-code-push 1.5.1 → 1.5.3

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.
package/CodePush.js CHANGED
@@ -4,6 +4,7 @@ import requestFetchAdapter from "./request-fetch-adapter";
4
4
  import { AppState, Platform } from "react-native";
5
5
  import log from "./logging";
6
6
  import hoistStatics from 'hoist-non-react-statics';
7
+ import { setTargetingInfo } from "./targeting";
7
8
 
8
9
  let NativeCodePush = require("react-native").NativeModules.CodePush;
9
10
  const PackageMixins = require("./package-mixins")(NativeCodePush);
@@ -618,6 +619,7 @@ if (NativeCodePush) {
618
619
  notifyAppReady: notifyApplicationReady,
619
620
  notifyApplicationReady,
620
621
  restartApp,
622
+ setTargetingInfo,
621
623
  setUpTestDependencies,
622
624
  sync,
623
625
  disallowRestart: NativeCodePush.disallow,
@@ -69,9 +69,9 @@ gradle.projectsEvaluated {
69
69
 
70
70
  def nodeModulesPath;
71
71
  if (project.hasProperty('nodeModulesPath')) {
72
- nodeModulesPath = "${project.nodeModulesPath}/@revopush/react-native-code-push"
72
+ nodeModulesPath = "${project.nodeModulesPath}/@novacraft-engineering/pulsar-code-push"
73
73
  } else {
74
- nodeModulesPath = findNodeModulePath(projectDir, "@revopush/react-native-code-push")
74
+ nodeModulesPath = findNodeModulePath(projectDir, "@novacraft-engineering/pulsar-code-push")
75
75
  }
76
76
 
77
77
  def targetName = variant.name.capitalize()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@novacraft-engineering/pulsar-code-push",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
4
4
  "description": "Pulsar OTA client for React Native \u2014 over-the-air JavaScript updates. A CodePush-compatible client (RevoPush lineage) pointed at Pulsar.",
5
5
  "main": "CodePush.js",
6
6
  "typings": "typings/react-native-code-push.d.ts",
@@ -26,6 +26,7 @@
26
26
  "files": [
27
27
  "CodePush.js",
28
28
  "AlertAdapter.js",
29
+ "targeting.js",
29
30
  "logging.js",
30
31
  "package-mixins.js",
31
32
  "request-fetch-adapter.js",
@@ -33,6 +34,7 @@
33
34
  "CodePush.podspec",
34
35
  "android",
35
36
  "ios",
37
+ "scripts",
36
38
  "typings",
37
39
  "README.md",
38
40
  "LICENSE"
@@ -1,4 +1,5 @@
1
1
  const packageJson = require("./package.json");
2
+ const { getTargetingInfo } = require("./targeting");
2
3
 
3
4
  module.exports = {
4
5
  async request(verb, url, requestBody, callback) {
@@ -7,6 +8,16 @@ module.exports = {
7
8
  requestBody = null;
8
9
  }
9
10
 
11
+ // Scope the update-check to a specific device model / user id when the host app has set them.
12
+ // Only the GET update_check request is augmented; report_status is untouched.
13
+ if (verb === 0 && url.indexOf("update_check") !== -1) {
14
+ const { userId, deviceModel } = getTargetingInfo();
15
+ const extra = [];
16
+ if (deviceModel) extra.push("device_model=" + encodeURIComponent(deviceModel));
17
+ if (userId) extra.push("user_id=" + encodeURIComponent(userId));
18
+ if (extra.length) url += (url.indexOf("?") === -1 ? "?" : "&") + extra.join("&");
19
+ }
20
+
10
21
  const headers = {
11
22
  "Accept": "application/json",
12
23
  "Content-Type": "application/json",
@@ -0,0 +1,165 @@
1
+ /*
2
+ * This script generates a hash of all the React Native bundled assets and writes it into
3
+ * into the APK. The hash in "updateCheck" requests to prevent downloading an identical
4
+ * update to the one already present in the binary.
5
+ *
6
+ * It first creates a snapshot of the contents in the resource directory by creating
7
+ * a map with the modified time of all the files in the directory. It then compares this
8
+ * snapshot with the one saved earlier in "recordFilesBeforeBundleCommand.js" to figure
9
+ * out which files were generated by the "react-native bundle" command. It then computes
10
+ * the hash for each file to generate a manifest, and then computes a hash over the entire
11
+ * manifest to generate the final hash, which is saved to the APK's assets directory.
12
+ */
13
+
14
+ var crypto = require("crypto");
15
+ var fs = require("fs");
16
+ var path = require("path");
17
+
18
+ var getFilesInFolder = require("./getFilesInFolder");
19
+
20
+ const CODE_PUSH_FOLDER_PREFIX = "CodePush";
21
+ const CODE_PUSH_HASH_FILE_NAME = "CodePushHash";
22
+ const CODE_PUSH_METADATA_FILE_NAME = "CodePushMetadata";
23
+ const CODE_PUSH_PACKAGE_HASH = "packageHash"
24
+ const CODE_PUSH_BUNDLE_HASH = "bundleHash"
25
+ const CODE_PUSH_ASSET_HASH = "assetHash"
26
+ const MANIFEST = "manifest"
27
+ const CODE_PUSH_HASH_OLD_FILE_NAME = "CodePushHash.json";
28
+ const HASH_ALGORITHM = "sha256";
29
+
30
+ var resourcesDir = process.argv[2];
31
+ var jsBundleFilePath = process.argv[3];
32
+ var assetsDir = process.argv[4];
33
+ var tempFileName = process.argv[5];
34
+
35
+ var oldFileToModifiedTimeMap = {};
36
+ var tempFileLocalPath = null;
37
+ if (tempFileName) {
38
+ tempFileLocalPath = path.join(require("os").tmpdir(), tempFileName);
39
+ oldFileToModifiedTimeMap = require(tempFileLocalPath);
40
+ }
41
+ var resourceFiles = [];
42
+
43
+ getFilesInFolder(resourcesDir, resourceFiles);
44
+
45
+ function getBundleResourceEntries(resourcesDir, assetsDir) {
46
+ const resourceFiles = [];
47
+ const assetFiles = [];
48
+ getFilesInFolder(resourcesDir, resourceFiles);
49
+ getFilesInFolder(assetsDir, assetFiles);
50
+ let resourceFilesRelative = resourceFiles.map((it) => path.relative(resourcesDir, it.path));
51
+ let assetsFilesRelative = assetFiles.map((it) => path.relative(assetsDir, it.path));
52
+
53
+ const normalizePath = (it) => path.join(CODE_PUSH_FOLDER_PREFIX, it).replace(/\\/g, "/")
54
+ return {
55
+ resources: Object.fromEntries(resourceFilesRelative.map((it) => [normalizePath(it), path.parse(it).name])),
56
+ assets: Object.fromEntries(assetsFilesRelative.map((it) => [it.replace(/\\/g, "/"), normalizePath(it)]))
57
+ }
58
+ }
59
+
60
+ var newFileToModifiedTimeMap = {};
61
+
62
+ resourceFiles.forEach(function (resourceFile) {
63
+ newFileToModifiedTimeMap[resourceFile.path.substring(resourcesDir.length)] = resourceFile.mtime;
64
+ });
65
+
66
+ var bundleGeneratedAssetFiles = [];
67
+
68
+ for (var newFilePath in newFileToModifiedTimeMap) {
69
+ if (!oldFileToModifiedTimeMap[newFilePath] || oldFileToModifiedTimeMap[newFilePath] < newFileToModifiedTimeMap[newFilePath].getTime()) {
70
+ bundleGeneratedAssetFiles.push(newFilePath);
71
+ }
72
+ }
73
+
74
+ var manifest = [];
75
+
76
+ if (bundleGeneratedAssetFiles.length) {
77
+ bundleGeneratedAssetFiles.forEach(function (assetFile) {
78
+ // Generate hash for each asset file
79
+ addFileToManifest(resourcesDir, assetFile, manifest, function () {
80
+ if (manifest.length === bundleGeneratedAssetFiles.length) {
81
+ addJsBundleAndMetaToManifest();
82
+ }
83
+ });
84
+ });
85
+ } else {
86
+ addJsBundleAndMetaToManifest();
87
+ }
88
+
89
+ function addJsBundleAndMetaToManifest() {
90
+ addFileToManifest(path.dirname(jsBundleFilePath), path.basename(jsBundleFilePath), manifest, function (jsBundleFileHash) {
91
+ var jsBundleMetaFilePath = jsBundleFilePath + ".meta";
92
+ addFileToManifest(path.dirname(jsBundleMetaFilePath), path.basename(jsBundleMetaFilePath), manifest, function () {
93
+ manifest = manifest.sort();
94
+ const finalHash = crypto.createHash(HASH_ALGORITHM)
95
+ .update(JSON.stringify(manifest))
96
+ .digest("hex");
97
+
98
+ const bundleHashDada = path.join(CODE_PUSH_FOLDER_PREFIX, path.basename(jsBundleFilePath)).replace(/\\/g, "/") + ":" + jsBundleFileHash;
99
+ const bundleHash = crypto.createHash(HASH_ALGORITHM)
100
+ .update(JSON.stringify([bundleHashDada]))
101
+ .digest("hex");
102
+
103
+ const assetHash = crypto.createHash(HASH_ALGORITHM)
104
+ .update(JSON.stringify([...manifest].filter(it => it !== bundleHashDada).sort()))
105
+ .digest("hex");
106
+
107
+ const manifestMetadata = {
108
+ [CODE_PUSH_PACKAGE_HASH]: finalHash,
109
+ [CODE_PUSH_BUNDLE_HASH]: bundleHash,
110
+ [CODE_PUSH_ASSET_HASH]: assetHash,
111
+ ...(getBundleResourceEntries(resourcesDir, assetsDir)),
112
+ [MANIFEST]: manifest
113
+ }
114
+
115
+ console.log(finalHash);
116
+
117
+ fs.writeFileSync(path.join(assetsDir, CODE_PUSH_HASH_FILE_NAME), finalHash);
118
+ fs.writeFileSync(path.join(assetsDir, CODE_PUSH_METADATA_FILE_NAME), JSON.stringify(manifestMetadata));
119
+
120
+ // "CodePushHash.json" file name breaks flow type checking.
121
+ // To fix the issue we need to delete "CodePushHash.json" file and
122
+ // use "CodePushHash" file name instead to store the hash value.
123
+ // Relates to https://github.com/microsoft/react-native-code-push/issues/577
124
+ var oldSavedResourcesManifestPath = assetsDir + "/" + CODE_PUSH_HASH_OLD_FILE_NAME;
125
+ if (fs.existsSync(oldSavedResourcesManifestPath)) {
126
+ fs.unlinkSync(oldSavedResourcesManifestPath);
127
+ }
128
+ });
129
+ });
130
+ }
131
+
132
+ function addFileToManifest(folder, assetFile, manifest, done) {
133
+ var fullFilePath = path.join(folder, assetFile);
134
+ if (!fileExists(fullFilePath)) {
135
+ done(undefined);
136
+ return;
137
+ }
138
+
139
+ var readStream = fs.createReadStream(path.join(folder, assetFile));
140
+ var hashStream = crypto.createHash(HASH_ALGORITHM);
141
+
142
+ readStream.pipe(hashStream)
143
+ .on("error", function (error) {
144
+ throw error;
145
+ })
146
+ .on("finish", function () {
147
+ hashStream.end();
148
+ var buffer = hashStream.read();
149
+ var fileHash = buffer.toString("hex");
150
+ manifest.push(path.join(CODE_PUSH_FOLDER_PREFIX, assetFile).replace(/\\/g, "/") + ":" + fileHash);
151
+ done(fileHash);
152
+ });
153
+ }
154
+
155
+ function fileExists(file) {
156
+ try {
157
+ return fs.statSync(file).isFile();
158
+ } catch (e) {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ if (tempFileLocalPath) {
164
+ fs.unlinkSync(tempFileLocalPath);
165
+ }
@@ -0,0 +1,19 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+
4
+ // Utility function that collects the stats of every file in a directory
5
+ // as well as in its subdirectories.
6
+ function getFilesInFolder(folderName, fileList) {
7
+ var folderFiles = fs.readdirSync(folderName);
8
+ folderFiles.forEach(function(file) {
9
+ var fileStats = fs.statSync(path.join(folderName, file));
10
+ if (fileStats.isDirectory()) {
11
+ getFilesInFolder(path.join(folderName, file), fileList);
12
+ } else {
13
+ fileStats.path = path.join(folderName, file);
14
+ fileList.push(fileStats);
15
+ }
16
+ });
17
+ }
18
+
19
+ module.exports = getFilesInFolder;
@@ -0,0 +1,41 @@
1
+ /*
2
+ * This script creates a snapshot of the contents in the resource directory
3
+ * by creating a map with the modified time of all the files in the directory
4
+ * and saving it to a temp file. This snapshot is later referenced in
5
+ * "generatePackageHash.js" to figure out which files have changed or were
6
+ * newly generated by the "react-native bundle" command.
7
+ */
8
+
9
+ var fs = require("fs");
10
+ var path = require("path");
11
+
12
+ var getFilesInFolder = require("./getFilesInFolder");
13
+
14
+
15
+ var resourcesDir = process.argv[2];
16
+ var tempFileName = process.argv[3];
17
+
18
+ var tempFileLocalPath = path.join(require("os").tmpdir(), tempFileName);
19
+ var resourceFiles = [];
20
+
21
+ try {
22
+ getFilesInFolder(resourcesDir, resourceFiles);
23
+ } catch(error) {
24
+ var targetPathNotFoundExceptionMessage = "\nResources directory path does not exist.\n";
25
+ targetPathNotFoundExceptionMessage += "Unable to find '" + resourcesDir;
26
+ targetPathNotFoundExceptionMessage += "' directory. Please check version of Android Plugin for Gradle.";
27
+ error.message += targetPathNotFoundExceptionMessage;
28
+ throw error;
29
+ }
30
+
31
+ var fileToModifiedTimeMap = {};
32
+
33
+ resourceFiles.forEach(function(resourceFile) {
34
+ fileToModifiedTimeMap[resourceFile.path.substring(resourcesDir.length)] = resourceFile.mtime.getTime();
35
+ });
36
+
37
+ fs.writeFile(tempFileLocalPath, JSON.stringify(fileToModifiedTimeMap), function(err) {
38
+ if (err) {
39
+ throw err;
40
+ }
41
+ });
package/targeting.js ADDED
@@ -0,0 +1,17 @@
1
+ // Optional targeting identifiers the host app can set (e.g. at login). They are appended to the
2
+ // update-check request so the server can scope a release to specific device models / user ids.
3
+ // Shared singleton: the fetch adapter reads it, CodePush.setTargetingInfo writes it.
4
+ let info = { userId: null, deviceModel: null };
5
+
6
+ function setTargetingInfo(next) {
7
+ if (!next) return info;
8
+ if (next.userId !== undefined) info.userId = next.userId == null ? null : String(next.userId);
9
+ if (next.deviceModel !== undefined) info.deviceModel = next.deviceModel == null ? null : String(next.deviceModel);
10
+ return info;
11
+ }
12
+
13
+ function getTargetingInfo() {
14
+ return info;
15
+ }
16
+
17
+ module.exports = { setTargetingInfo, getTargetingInfo };