@applicaster/zapplicaster-cli 16.0.0-rc.99 → 17.0.0-alpha.1201533844

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.
Files changed (30) hide show
  1. package/README.md +9 -5
  2. package/package.json +7 -6
  3. package/src/commands/init/setUpEnvironment.js +2 -7
  4. package/src/commands/prepareWorkspace/__tests__/__snapshots__/prerequisitesChecker-incorrecNode.test.js.snap +1 -1
  5. package/src/commands/prepareWorkspace/__tests__/buildPluginsCreator.test.js +99 -0
  6. package/src/commands/prepareWorkspace/buildPluginsCreator.js +61 -0
  7. package/src/commands/prepareWorkspace/configFilesRetriever.js +3 -0
  8. package/src/commands/prepareWorkspace/prerequisitesChecker.js +2 -2
  9. package/src/commands/publishPlugin/README.md +46 -0
  10. package/src/commands/publishPlugin/__tests__/__snapshots__/configurator.test.js.snap +0 -2
  11. package/src/commands/publishPlugin/__tests__/commitToGit.test.js +1 -1
  12. package/src/commands/publishPlugin/__tests__/configurator.test.js +7 -4
  13. package/src/commands/publishPlugin/__tests__/manifests/android.json +3 -1
  14. package/src/commands/publishPlugin/__tests__/manifests/android_for_quickbrick.json +6 -0
  15. package/src/commands/publishPlugin/__tests__/manifests/android_tv_for_quickbrick.json +6 -0
  16. package/src/commands/publishPlugin/__tests__/manifests/ios.json +3 -1
  17. package/src/commands/publishPlugin/__tests__/manifests/ios_for_quickbrick.json +6 -0
  18. package/src/commands/publishPlugin/__tests__/manifests/tvos_for_quickbrick.json +6 -0
  19. package/src/commands/publishPlugin/__tests__/npmPublish.test.js +39 -23
  20. package/src/commands/publishPlugin/__tests__/zappifestPublish.integration.test.js +154 -0
  21. package/src/commands/publishPlugin/__tests__/zappifestPublish.test.js +61 -85
  22. package/src/commands/publishPlugin/commitToGit.js +1 -1
  23. package/src/commands/publishPlugin/configurator.js +1 -8
  24. package/src/commands/publishPlugin/npmPublish.js +6 -9
  25. package/src/commands/publishPlugin/updateCorePluginsIfNeeded.js +29 -12
  26. package/src/commands/publishPlugin/zappifestPublish.js +13 -39
  27. package/src/file/__tests__/file.test.js +7 -1
  28. package/src/file/index.js +14 -3
  29. package/test_helpers/fsMock.js +11 -0
  30. package/src/commands/publishPlugin/__tests__/__snapshots__/zappifestPublish.test.js.snap +0 -5
package/README.md CHANGED
@@ -30,7 +30,7 @@ $ node_modules/.bin/zapplicaster <command> <...args> [...options]
30
30
 
31
31
  #### `init`
32
32
 
33
- Sets up the applicaster environment. It will check installation of brew, zappifest, zapptool, yarn, nvm and node. If any of these tools aren't installed, the script will install them.
33
+ Sets up the applicaster environment. It will check installation of brew, zapptool, yarn and node. If any of these tools aren't installed, the script will install them. Manifest publishing uses the bundled npm dependency instead of a separately installed Ruby zappifest.
34
34
  This command will also prompt the user for some data required to run the App (Zapp Token, path to native folders, name of android emulators). It will also offer to clone the repositories if needed.
35
35
  Once all the data is configured, it is saved at `~/.applicaster.json`
36
36
 
@@ -116,9 +116,9 @@ npx zapplicaster-cli publish_plugin path/to/plugin [...options]
116
116
  This command can be used to publish a QuickBrick plugin to Zapp.
117
117
  It will push the plugin to npm, generate the manifests for the supported platforms, push the zappifests to Zapp, and commit the changes to your current branches.
118
118
 
119
- In order to work, you need to make sure you are logged in to npm to an account which is allowed to publish the npm package of your plugin. You also need to make sure you can run zappifest commands, which means you have the right ruby version, the latest version of zappifest, and the `ZAPP_TOKEN` environment variable set.
119
+ Requires Node.js 22+, npm publishing access for your plugin, and the `ZAPP_TOKEN` environment variable. Manifest uploads use `@applicaster/zappifest-nano` in-process; Ruby and the legacy zappifest CLI are not required. See the [publishing contract](src/commands/publishPlugin/README.md) for platform selection, dry-run behavior, and failure handling.
120
120
 
121
- You will also need to define an `applicaster` property in your package.json file to declare the list of platforms which are supported by the plugin. By default, the command will try to publish all plugins at once, but you can use the `-s, --single-platform` flag to target only one platform. However, if you ask the script to publish the plugin for a single platform, the script will not let you publish to a platform that is not listed in the supported platforms.
121
+ You will also need to define an `applicaster` property in your package.json file to declare the list of platforms which are supported by the plugin. By default, the command will publish all supported platforms, but you can use the `-s, --single-platform` flag to target only one platform. The selected platform must be listed in `supportedPlatforms`.
122
122
 
123
123
  ```json
124
124
  // package.json
@@ -127,8 +127,12 @@ You will also need to define an `applicaster` property in your package.json file
127
127
  "name": "my-awesome-plugin",
128
128
  "version": "1.5.0",
129
129
  "applicaster": {
130
- "supportedPlatforms": ["ios", "android", "tvos", "samsung"],
131
- "zappOwnerAccountId": "<plugin owner account from zapp>"
130
+ "supportedPlatforms": [
131
+ "ios_for_quickbrick",
132
+ "android_for_quickbrick",
133
+ "tvos_for_quickbrick",
134
+ "samsung_tv"
135
+ ]
132
136
  }
133
137
  }
134
138
  ```
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@applicaster/zapplicaster-cli",
3
- "version": "16.0.0-rc.99",
3
+ "version": "17.0.0-alpha.1201533844",
4
4
  "description": "CLI Tool for the zapp app and Quick Brick project",
5
5
  "main": "index.js",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
9
  "engines": {
10
- "node": ">= 18.0.0",
10
+ "node": ">= 22.0.0",
11
11
  "yarn": "^4.0.0"
12
12
  },
13
13
  "bin": "./index.js",
@@ -28,10 +28,11 @@
28
28
  },
29
29
  "homepage": "https://github.com/applicaster/quickbrick#readme",
30
30
  "dependencies": {
31
- "@applicaster/zapp-react-dom-cli-template": "16.0.0-rc.99",
32
- "@applicaster/zapp-react-native-android-tv-cli-template": "16.0.0-rc.99",
33
- "@applicaster/zapp-react-native-cli-template": "16.0.0-rc.99",
34
- "@applicaster/zapp-react-native-tvos-cli-template": "16.0.0-rc.99",
31
+ "@applicaster/zapp-react-dom-cli-template": "17.0.0-alpha.1201533844",
32
+ "@applicaster/zapp-react-native-android-tv-cli-template": "17.0.0-alpha.1201533844",
33
+ "@applicaster/zapp-react-native-cli-template": "17.0.0-alpha.1201533844",
34
+ "@applicaster/zapp-react-native-tvos-cli-template": "17.0.0-alpha.1201533844",
35
+ "@applicaster/zappifest-nano": "^1.0.0",
35
36
  "axios": "^0.28.0",
36
37
  "camelize": "^1.0.0",
37
38
  "chalk": "^2.3.2",
@@ -2,14 +2,13 @@ const logger = require("../../logger");
2
2
  const { runInShellAsync } = require("../../shell");
3
3
 
4
4
  const BREW = "brew";
5
- const ZAPPIFEST = "zappifest";
6
5
  const ZAPPTOOL = "zapptool";
7
6
  const YARN = "yarn";
8
7
  const NODE = "node";
9
8
 
10
- const LIBS = [BREW, ZAPPIFEST, ZAPPTOOL, YARN, NODE];
9
+ const LIBS = [BREW, ZAPPTOOL, YARN, NODE];
11
10
 
12
- const NODE_VERSION = "12.16.1";
11
+ const NODE_VERSION = "22";
13
12
  const YARN_VERSION = "1.21.1";
14
13
 
15
14
  const INSTALL_SCRIPTS = {
@@ -22,10 +21,6 @@ const INSTALL_SCRIPTS = {
22
21
  await runInShellAsync("brew tap applicaster/tap");
23
22
  },
24
23
 
25
- async [ZAPPIFEST]() {
26
- await runInShellAsync("brew install zappifest");
27
- },
28
-
29
24
  async [ZAPPTOOL]() {
30
25
  await runInShellAsync("brew install zapptool");
31
26
  },
@@ -1,3 +1,3 @@
1
1
  // Jest Snapshot v1, https://goo.gl/fbAQLP
2
2
 
3
- exports[`prerequisitesChecker node version requirements are not satisfied throws when running on a invalid node version 1`] = `"Unsupported node version - please use any version compliant with >= 12.0.0"`;
3
+ exports[`prerequisitesChecker node version requirements are not satisfied throws when running on a invalid node version 1`] = `"Unsupported node version - please use any version compliant with >= 22.0.0"`;
@@ -0,0 +1,99 @@
1
+ const fs = require("fs");
2
+ const os = require("os");
3
+ const path = require("path");
4
+
5
+ jest.mock("../../../render", () => ({
6
+ saveConfigFile: jest.fn(),
7
+ }));
8
+
9
+ jest.mock("../../../settings/paths", () => ({
10
+ getFileDestinationPath: jest.fn(),
11
+ }));
12
+
13
+ jest.mock("../../../logger", () => ({
14
+ error: jest.fn(),
15
+ }));
16
+
17
+ const { saveConfigFile } = require("../../../render");
18
+ const { getFileDestinationPath } = require("../../../settings/paths");
19
+ const logger = require("../../../logger");
20
+
21
+ const {
22
+ buildPluginsCreator,
23
+ getBuildPlugins,
24
+ } = require("../buildPluginsCreator");
25
+
26
+ const pluginConfigurations = [
27
+ {
28
+ plugin: {
29
+ identifier: "zeta",
30
+ name: "Zeta",
31
+ manifest_version: "2.0.0",
32
+ dependency_version: "1.0.0",
33
+ },
34
+ configuration_json: { key: "value" },
35
+ },
36
+ { plugin: { identifier: "alpha", dependency_version: "3.1.0" } },
37
+ { plugin: { name: "no identifier, skipped" } },
38
+ { configuration_json: {} },
39
+ ];
40
+
41
+ const expected = [
42
+ { id: "alpha", name: null, version: "3.1.0" },
43
+ { id: "zeta", name: "Zeta", version: "2.0.0" },
44
+ ];
45
+
46
+ const configuration = { destinationPath: "path/to/workspace", platform: "ios" };
47
+
48
+ describe("getBuildPlugins", () => {
49
+ it("maps plugins to id, name, version sorted by id, preferring manifest_version", () => {
50
+ expect(getBuildPlugins(pluginConfigurations)).toEqual(expected);
51
+ });
52
+ });
53
+
54
+ describe("buildPluginsCreator", () => {
55
+ const file = path.join(
56
+ os.tmpdir(),
57
+ `plugin_configurations_${process.pid}.json`
58
+ );
59
+
60
+ afterEach(() => {
61
+ jest.clearAllMocks();
62
+ fs.rmSync(file, { force: true });
63
+ });
64
+
65
+ it("writes build_plugins.json from the downloaded plugin_configurations.json", async () => {
66
+ fs.writeFileSync(file, JSON.stringify(pluginConfigurations));
67
+ getFileDestinationPath.mockReturnValue(file);
68
+
69
+ await buildPluginsCreator(configuration);
70
+
71
+ expect(getFileDestinationPath).toHaveBeenCalledWith({
72
+ ...configuration,
73
+ folder: "config",
74
+ fileName: "plugin_configurations.json",
75
+ });
76
+
77
+ expect(saveConfigFile).toHaveBeenCalledWith(
78
+ configuration,
79
+ "build_plugins.json",
80
+ expected
81
+ );
82
+
83
+ expect(logger.error).not.toHaveBeenCalled();
84
+ });
85
+
86
+ it("writes an empty list and logs an error when plugin_configurations.json is missing", async () => {
87
+ getFileDestinationPath.mockReturnValue(file);
88
+
89
+ await buildPluginsCreator(configuration);
90
+
91
+ expect(saveConfigFile).toHaveBeenCalledWith(
92
+ configuration,
93
+ "build_plugins.json",
94
+ []
95
+ );
96
+
97
+ expect(logger.error).toHaveBeenCalled();
98
+ });
99
+ });
@@ -0,0 +1,61 @@
1
+ const fs = require("fs");
2
+
3
+ const { saveConfigFile } = require("../../render");
4
+ const { getFileDestinationPath } = require("../../settings/paths");
5
+ const logger = require("../../logger");
6
+
7
+ /**
8
+ * Plugins the app is built with, as [{ id, name, version }] sorted by id.
9
+ * version is manifest_version, falling back to dependency_version.
10
+ * @param {Array} pluginConfigurations content of plugin_configurations.json
11
+ */
12
+ function getBuildPlugins(pluginConfigurations) {
13
+ return pluginConfigurations
14
+ .filter((entry) => typeof entry?.plugin?.identifier === "string")
15
+ .map(({ plugin }) => ({
16
+ id: plugin.identifier,
17
+ name: plugin.name ?? null,
18
+ version: plugin.manifest_version ?? plugin.dependency_version ?? null,
19
+ }))
20
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
21
+ }
22
+
23
+ /**
24
+ * Writes build_plugins.json next to the downloaded plugin_configurations.json.
25
+ * The app bundles it on every platform (plugin_configurations.json itself is only bundled in __DEV__),
26
+ * so tools like X-Ray can report what the build contains, not what Zapp serves now.
27
+ * @param {Object} configuration
28
+ * @param {String} configuration.destinationPath path of the workspace
29
+ * @param {String} configuration.platform platform of the app
30
+ */
31
+ async function buildPluginsCreator(configuration) {
32
+ const { destinationPath, platform } = configuration;
33
+
34
+ let buildPlugins = [];
35
+
36
+ try {
37
+ const pluginConfigurations = JSON.parse(
38
+ fs.readFileSync(
39
+ getFileDestinationPath({
40
+ destinationPath,
41
+ platform,
42
+ folder: "config",
43
+ fileName: "plugin_configurations.json",
44
+ }),
45
+ "utf8"
46
+ )
47
+ );
48
+
49
+ buildPlugins = getBuildPlugins(pluginConfigurations);
50
+ } catch (e) {
51
+ logger.error(
52
+ `Could not read plugin_configurations.json, build_plugins.json will be empty: ${e.message}`
53
+ );
54
+ }
55
+
56
+ await saveConfigFile(configuration, "build_plugins.json", buildPlugins);
57
+
58
+ return true;
59
+ }
60
+
61
+ module.exports = { buildPluginsCreator, getBuildPlugins };
@@ -7,6 +7,7 @@ const {
7
7
  } = require("../../download");
8
8
 
9
9
  const { renderConfigFile } = require("../../render");
10
+ const { buildPluginsCreator } = require("./buildPluginsCreator");
10
11
 
11
12
  /**
12
13
  * @typedef configuration
@@ -45,6 +46,8 @@ async function configFilesRetriever(configuration) {
45
46
  R.map(saveRemoteJsonToFile(configuration), configFilesUrls)
46
47
  );
47
48
 
49
+ await buildPluginsCreator(configuration);
50
+
48
51
  const { fonts_url, fonts, assets_url } = buildParams;
49
52
  saveFontFiles(configuration, fonts_url, fonts);
50
53
  saveAssets(configuration, assets_url);
@@ -17,9 +17,9 @@ function prerequisitesChecker() {
17
17
  }
18
18
 
19
19
  // runs node LTS
20
- if (!semver.satisfies(process.version, ">= 12.0.0")) {
20
+ if (!semver.satisfies(process.version, ">= 22.0.0")) {
21
21
  throw new Error(
22
- "Unsupported node version - please use any version compliant with >= 12.0.0"
22
+ "Unsupported node version - please use any version compliant with >= 22.0.0"
23
23
  );
24
24
  }
25
25
 
@@ -0,0 +1,46 @@
1
+ # Plugin manifest publishing
2
+
3
+ `publish_plugin` generates platform manifests and delegates their upload to the
4
+ published `@applicaster/zappifest-nano` CommonJS API. QuickBrick owns manifest
5
+ generation, npm package publishing, Apple templates, core-plugin updates, and Git
6
+ commits; Nano owns Zapp requests, validation, identifier grouping, and uploads.
7
+
8
+ ## Requirements
9
+
10
+ - Node.js 22+ and `ZAPP_TOKEN` for live uploads.
11
+ - Optional `ZAPP_URL` to override the Zapp Admin API endpoint.
12
+ - An existing Zapp plugin for each manifest identifier. QuickBrick does not
13
+ automatically create plugins or overwrite existing version records.
14
+
15
+ `applicaster.zappOwnerAccountId` is no longer required. Existing metadata remains
16
+ accepted, but is not forwarded as an account-validation request: the established
17
+ account-free publishing path makes no Accounts API calls.
18
+
19
+ ## Selection and safety
20
+
21
+ The adapter passes exactly the configured platform files in one `publish` call.
22
+ It deliberately does not scan the directory, so `--single-platform` cannot upload
23
+ stale manifests from other platforms. Nano reads fresh JSON from disk, validates
24
+ the selected batch, shares mapping lookups, and uploads platforms with the same
25
+ identifier in parallel. Different identifiers run sequentially.
26
+
27
+ Both `--dry-run` and `--manifest-only` map to Nano's `dryRun: true`: this step
28
+ validates locally without authentication, network calls, or Zapp writes.
29
+ `--manifest-only` can still generate local JSON in the earlier generation step.
30
+
31
+ Nano synchronizes supplied parent metadata once per identifier when it differs
32
+ from the server, without changing owner or whitelist. Conflicting parent metadata
33
+ within one identifier is rejected. Mapping fallbacks are surfaced through the CLI
34
+ warning logger; progress uses the regular CLI logger.
35
+
36
+ Failures propagate to the task runner. Uploads are not transactional: successful
37
+ platforms or parent updates may remain applied after a failure. Inspect Zapp
38
+ before retrying. No Ruby subprocess fallback remains; `USE_LEGACY_ZAPPIFEST` no
39
+ longer selects a different publisher.
40
+
41
+ ## CI
42
+
43
+ The checked-in primary-image recipe no longer installs Ruby or zappifest.
44
+ Publishing uses the workspace dependency. The existing prebuilt
45
+ `applicaster/quick-brick:3.0` image is unchanged until the image is rebuilt and
46
+ released separately; this migration does not require that image release.
@@ -50,8 +50,6 @@ exports[`publish plugin configurator throws when the package json cannot be foun
50
50
 
51
51
  exports[`publish plugin configurator throws when the package.json doesn't contain the applicaster property 1`] = `[Error: your plugin's package.json is missing the applicaster property]`;
52
52
 
53
- exports[`publish plugin configurator throws when the package.json doesn't contain the zapp account owner Id 1`] = `[Error: your plugin's package.json is missing zappOwnerAccountId]`;
54
-
55
53
  exports[`publish plugin configurator throws when the packages.json applicaster prop doesn't have list of supported platforms 1`] = `[Error: your plugin's package.json doesn't have a list of supported platforms]`;
56
54
 
57
55
  exports[`publish plugin configurator throws when the plugin path cannot be resolved 1`] = `[Error: cannot resolve file]`;
@@ -16,7 +16,7 @@ const mocked_gitInstance = {
16
16
  ),
17
17
  };
18
18
 
19
- jest.mock("simple-git/promise", () => jest.fn(() => mocked_gitInstance));
19
+ jest.mock("simple-git", () => jest.fn(() => mocked_gitInstance));
20
20
 
21
21
  jest.mock("../../../logger", () => ({
22
22
  log: jest.fn(),
@@ -14,7 +14,7 @@ const getOptions = (opts = {}) => ({
14
14
  },
15
15
  });
16
16
 
17
- jest.mock("simple-git/promise", () =>
17
+ jest.mock("simple-git", () =>
18
18
  jest.fn((path) => {
19
19
  return {
20
20
  status: function () {
@@ -87,7 +87,7 @@ jest.mock("fs", () => ({
87
87
  }));
88
88
 
89
89
  const logger = require("../../../logger");
90
- const git = require("simple-git/promise");
90
+ const git = require("simple-git");
91
91
 
92
92
  const { configurator } = require("../configurator");
93
93
 
@@ -123,9 +123,12 @@ describe("publish plugin configurator", () => {
123
123
  expect(configurator(options)).rejects.toMatchSnapshot();
124
124
  });
125
125
 
126
- it("throws when the package.json doesn't contain the zapp account owner Id", async () => {
126
+ it("allows publishing existing plugins without a zapp account owner Id", async () => {
127
127
  const options = getOptions({ pluginPath: "bad_missing_zapp_account" });
128
- expect(configurator(options)).rejects.toMatchSnapshot();
128
+ const config = await configurator(options);
129
+
130
+ expect(config.platforms).toEqual(["ios", "android"]);
131
+ expect(config.zappOwnerAccountId).toBeUndefined();
129
132
  });
130
133
 
131
134
  it("throws when the packages.json applicaster prop doesn't have list of supported platforms", async () => {
@@ -1,4 +1,6 @@
1
1
  {
2
2
  "name": "my plugin name",
3
- "platform": "android"
3
+ "identifier": "my_plugin",
4
+ "platform": "android",
5
+ "manifest_version": "1.0.0"
4
6
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Cell Info",
3
+ "identifier": "cell_info_mobile",
4
+ "platform": "android_for_quickbrick",
5
+ "manifest_version": "1.0.0"
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Cell Info TV",
3
+ "identifier": "cell_info_tv",
4
+ "platform": "android_tv_for_quickbrick",
5
+ "manifest_version": "1.0.0"
6
+ }
@@ -1,4 +1,6 @@
1
1
  {
2
2
  "name": "my plugin name",
3
- "platform": "ios"
3
+ "identifier": "my_plugin",
4
+ "platform": "ios",
5
+ "manifest_version": "1.0.0"
4
6
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Cell Info",
3
+ "identifier": "cell_info_mobile",
4
+ "platform": "ios_for_quickbrick",
5
+ "manifest_version": "1.0.0"
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Cell Info TV",
3
+ "identifier": "cell_info_tv",
4
+ "platform": "tvos_for_quickbrick",
5
+ "manifest_version": "1.0.0"
6
+ }
@@ -42,11 +42,21 @@ const { npmPublish } = require("../npmPublish");
42
42
  const { runInShellAsync } = require("../../../shell");
43
43
  const logger = require("../../../logger");
44
44
  const { retryPublishCommand } = require("../../utils/retryPublishCommand");
45
+ const { readJsonFile, writeJsonToFile } = require("../../../file");
46
+
47
+ jest.mock("../../../file", () => ({
48
+ readJsonFile: jest.fn(() =>
49
+ Promise.resolve({ name: "my-plugin", version: "1.0.0" })
50
+ ),
51
+ writeJsonToFile: jest.fn(() => Promise.resolve()),
52
+ }));
45
53
 
46
54
  function clearMocks() {
47
55
  logger.log.mockClear();
48
56
  retryPublishCommand.mockClear();
49
57
  runInShellAsync.mockClear();
58
+ if (writeJsonToFile.mockClear) writeJsonToFile.mockClear();
59
+ if (readJsonFile.mockClear) readJsonFile.mockClear();
50
60
  jest.resetModules();
51
61
  }
52
62
 
@@ -58,12 +68,10 @@ describe("npm publish step", () => {
58
68
  const configuration = getConfig();
59
69
  expect(await npmPublish(configuration)).toEqual(true);
60
70
  expect(retryPublishCommand).toHaveBeenCalledTimes(1);
61
- expect(runInShellAsync).toHaveBeenCalledTimes(1);
62
71
 
63
- expect(runInShellAsync).toHaveBeenNthCalledWith(
64
- 1,
65
- `npm version ${configuration.version}`,
66
- expect.objectContaining({ cwd: configuration.pluginPath })
72
+ expect(writeJsonToFile).toHaveBeenCalledWith(
73
+ "plugins/my-plugin/package.json",
74
+ expect.objectContaining({ version: configuration.version })
67
75
  );
68
76
 
69
77
  expect(retryPublishCommand).toHaveBeenNthCalledWith(
@@ -75,8 +83,12 @@ describe("npm publish step", () => {
75
83
  });
76
84
 
77
85
  it("throws if the npm command fails", async () => {
78
- const configuration = getConfig({ version: "fail" });
79
- expect(npmPublish(configuration)).rejects.toMatchSnapshot();
86
+ retryPublishCommand.mockImplementationOnce(() =>
87
+ Promise.reject(mock_publish_error)
88
+ );
89
+
90
+ const configuration = getConfig();
91
+ await expect(npmPublish(configuration)).rejects.toMatchSnapshot();
80
92
  });
81
93
 
82
94
  it.skip("re tries 3 times if the npm command fails with ESOCKETTIMEDOUT", async () => {
@@ -134,15 +146,14 @@ describe("npm publish step", () => {
134
146
  const configuration = getConfig({ dryRun: true });
135
147
 
136
148
  expect(await npmPublish(configuration)).toEqual(true);
137
- expect(runInShellAsync).toHaveBeenCalledTimes(1);
138
- expect(retryPublishCommand).toHaveBeenCalledTimes(1);
139
149
 
140
- expect(runInShellAsync).toHaveBeenNthCalledWith(
141
- 1,
142
- `npm version ${configuration.version}`,
143
- expect.objectContaining({ cwd: configuration.pluginPath })
150
+ expect(writeJsonToFile).toHaveBeenCalledWith(
151
+ "plugins/my-plugin/package.json",
152
+ expect.objectContaining({ version: configuration.version })
144
153
  );
145
154
 
155
+ expect(retryPublishCommand).toHaveBeenCalledTimes(1);
156
+
146
157
  expect(retryPublishCommand).toHaveBeenNthCalledWith(
147
158
  1,
148
159
  "npm publish --dry-run",
@@ -167,15 +178,13 @@ describe("npm publish step", () => {
167
178
 
168
179
  expect(await npmPublish(configuration)).toEqual(true);
169
180
 
170
- expect(runInShellAsync).toHaveBeenCalledTimes(1);
171
- expect(retryPublishCommand).toHaveBeenCalledTimes(1);
172
-
173
- expect(runInShellAsync).toHaveBeenNthCalledWith(
174
- 1,
175
- `npm version ${configuration.version}`,
176
- expect.objectContaining({ cwd: configuration.pluginPath })
181
+ expect(writeJsonToFile).toHaveBeenCalledWith(
182
+ "plugins/my-plugin/package.json",
183
+ expect.objectContaining({ version: configuration.version })
177
184
  );
178
185
 
186
+ expect(retryPublishCommand).toHaveBeenCalledTimes(1);
187
+
179
188
  expect(retryPublishCommand).toHaveBeenNthCalledWith(
180
189
  1,
181
190
  "npm publish --tag next",
@@ -190,9 +199,16 @@ describe("npm publish step", () => {
190
199
  expect(await npmPublish(configuration)).toEqual(true);
191
200
  expect(retryPublishCommand).toHaveBeenCalledTimes(1);
192
201
 
193
- expect(runInShellAsync).toHaveBeenCalledWith(
194
- `npm version ${configuration.version} --git-tag-version=false --commit-hooks=false --workspaces-update=false`,
195
- expect.objectContaining({ cwd: configuration.pluginPath })
202
+ expect(writeJsonToFile).toHaveBeenCalledWith(
203
+ "plugins/my-plugin/package.json",
204
+ expect.objectContaining({ version: configuration.version })
205
+ );
206
+
207
+ expect(retryPublishCommand).toHaveBeenNthCalledWith(
208
+ 1,
209
+ "npm publish --tag next",
210
+ expect.objectContaining({ cwd: configuration.pluginPath }),
211
+ configuration.version
196
212
  );
197
213
  });
198
214
  });
@@ -0,0 +1,154 @@
1
+ const { resolve } = require("path");
2
+
3
+ jest.mock("../../../logger", () => ({
4
+ log: jest.fn(),
5
+ warn: jest.fn(),
6
+ }));
7
+
8
+ const { zappifestPublish } = require("../zappifestPublish");
9
+
10
+ const configuration = {
11
+ pluginPath: resolve(__dirname),
12
+ platforms: ["ios_for_quickbrick", "android_for_quickbrick"],
13
+ };
14
+
15
+ describe("published Nano integration", () => {
16
+ const originalFetch = global.fetch;
17
+ const originalToken = process.env.ZAPP_TOKEN;
18
+ const originalUrl = process.env.ZAPP_URL;
19
+ let requests;
20
+ let pendingUploads;
21
+
22
+ beforeEach(() => {
23
+ requests = [];
24
+ pendingUploads = [];
25
+ process.env.ZAPP_TOKEN = "test-token";
26
+ process.env.ZAPP_URL = "https://zapp.example.test/api/v1/admin";
27
+
28
+ global.fetch = jest.fn(async (url, options) => {
29
+ const path = new URL(url).pathname;
30
+ requests.push({ path, options });
31
+
32
+ if (path.endsWith("/targets.json")) {
33
+ return Response.json([
34
+ { name: "mobile", id: 1 },
35
+ { name: "tv", id: 2 },
36
+ ]);
37
+ }
38
+
39
+ if (path.endsWith("/ui_frameworks.json")) {
40
+ return Response.json([{ name: "quickbrick", id: 2 }]);
41
+ }
42
+
43
+ if (path.endsWith("/plugins/cell_info_mobile.json")) {
44
+ return Response.json({ id: 11, name: "Cell Info" });
45
+ }
46
+
47
+ if (path.endsWith("/plugins/cell_info_tv.json")) {
48
+ return Response.json({ id: 22, name: "Cell Info TV" });
49
+ }
50
+
51
+ if (path.endsWith("/plugin_versions")) {
52
+ return new Promise((resolve) => {
53
+ pendingUploads.push(resolve);
54
+
55
+ if (pendingUploads.length === 2) {
56
+ pendingUploads.splice(0).forEach((finish) => {
57
+ finish(Response.json({ ok: true }));
58
+ });
59
+ }
60
+ });
61
+ }
62
+
63
+ throw new Error(`Unexpected request: ${path}`);
64
+ });
65
+ });
66
+
67
+ afterEach(() => {
68
+ global.fetch = originalFetch;
69
+
70
+ if (originalToken === undefined) delete process.env.ZAPP_TOKEN;
71
+ else process.env.ZAPP_TOKEN = originalToken;
72
+
73
+ if (originalUrl === undefined) delete process.env.ZAPP_URL;
74
+ else process.env.ZAPP_URL = originalUrl;
75
+ });
76
+
77
+ it("shares mappings and uploads each identifier's platforms concurrently without account calls", async () => {
78
+ await expect(
79
+ zappifestPublish({
80
+ ...configuration,
81
+ platforms: [
82
+ ...configuration.platforms,
83
+ "android_tv_for_quickbrick",
84
+ "tvos_for_quickbrick",
85
+ ],
86
+ })
87
+ ).resolves.toBe(true);
88
+
89
+ expect(requests.map(({ path }) => path)).toEqual([
90
+ "/api/v1/admin/targets.json",
91
+ "/api/v1/admin/ui_frameworks.json",
92
+ "/api/v1/admin/plugins/cell_info_mobile.json",
93
+ "/api/v1/admin/plugin_versions",
94
+ "/api/v1/admin/plugin_versions",
95
+ "/api/v1/admin/plugins/cell_info_tv.json",
96
+ "/api/v1/admin/plugin_versions",
97
+ "/api/v1/admin/plugin_versions",
98
+ ]);
99
+
100
+ const uploads = requests.filter(({ options }) => options.method === "POST");
101
+
102
+ expect(
103
+ uploads.map(({ options }) =>
104
+ options.body.get("plugin_version[plugin_id]")
105
+ )
106
+ ).toEqual(["11", "11", "22", "22"]);
107
+
108
+ expect(
109
+ uploads.every(
110
+ ({ options }) => options.body.get("access_token") === "test-token"
111
+ )
112
+ ).toBe(true);
113
+ });
114
+
115
+ it.each([{ dryRun: true }, { manifestOnly: true }])(
116
+ "validates real fixture files without a token or network for %j",
117
+ async (options) => {
118
+ delete process.env.ZAPP_TOKEN;
119
+
120
+ await expect(
121
+ zappifestPublish({ ...configuration, ...options })
122
+ ).resolves.toBe(true);
123
+
124
+ expect(global.fetch).not.toHaveBeenCalled();
125
+ }
126
+ );
127
+
128
+ it("rejects a missing selected file before any network request", async () => {
129
+ await expect(
130
+ zappifestPublish({
131
+ ...configuration,
132
+ platforms: ["ios_for_quickbrick", "missing_platform"],
133
+ })
134
+ ).rejects.toThrow("Cannot read manifest");
135
+
136
+ expect(global.fetch).not.toHaveBeenCalled();
137
+ });
138
+
139
+ it("propagates an HTTP upload failure with partial-success context", async () => {
140
+ const fetchManifestRequest = global.fetch.getMockImplementation();
141
+
142
+ global.fetch.mockImplementation(async (url, options) => {
143
+ if (new URL(url).pathname.endsWith("/plugin_versions")) {
144
+ return new Response(null, { status: 422 });
145
+ }
146
+
147
+ return fetchManifestRequest(url, options);
148
+ });
149
+
150
+ await expect(zappifestPublish(configuration)).rejects.toThrow(
151
+ /HTTP 422.*Batch stopped/
152
+ );
153
+ });
154
+ });
@@ -1,114 +1,90 @@
1
- const getConfig = (config = {}) => ({
2
- platforms: ["android", "ios"],
3
- pluginPath: "plugins/my-plugn",
4
- dryRun: false,
5
- zappOwnerAccountId: "A1234",
6
- ...config,
7
- });
8
-
9
- jest.mock("path", () => ({
10
- resolve: jest.fn((path, platformpath) => {
11
- if (path.includes("resolve_error")) {
12
- throw new Error("cannot resolve manifest");
13
- }
14
-
15
- if (path.includes("zappifest_error")) {
16
- /* eslint-disable-next-line no-path-concat */
17
- return __dirname + "/zappifest_error.json";
18
- }
19
-
20
- /* eslint-disable-next-line no-path-concat */
21
- return __dirname + "/" + platformpath;
22
- }),
23
- }));
1
+ const { resolve } = require("path");
24
2
 
25
- jest.mock("../../../shell", () => ({
26
- runInShellAsync: jest.fn((command) => {
27
- return command.includes("zappifest_error")
28
- ? Promise.reject(new Error("zappifest failed"))
29
- : Promise.resolve(true);
30
- }),
3
+ jest.mock("@applicaster/zappifest-nano", () => ({
4
+ publish: jest.fn().mockResolvedValue({ uploaded: 2 }),
31
5
  }));
32
6
 
33
7
  jest.mock("../../../logger", () => ({
34
8
  log: jest.fn(),
9
+ warn: jest.fn(),
35
10
  }));
36
11
 
37
- const { zappifestPublish } = require("../zappifestPublish");
38
- const { runInShellAsync } = require("../../../shell");
12
+ const { publish } = require("@applicaster/zappifest-nano");
39
13
  const logger = require("../../../logger");
40
- const { inspect } = require("util");
14
+ const { zappifestPublish } = require("../zappifestPublish");
41
15
 
42
- function clearMocks() {
43
- logger.log.mockClear();
44
- runInShellAsync.mockClear();
45
- }
16
+ const configuration = {
17
+ platforms: ["android", "ios"],
18
+ pluginPath: resolve(__dirname),
19
+ };
46
20
 
47
21
  describe("publish zappifests", () => {
48
- beforeEach(clearMocks);
49
-
50
- it("runs the zappifest command for all platforms", async () => {
51
- const configuration = getConfig();
22
+ beforeEach(() => {
23
+ publish.mockReset().mockResolvedValue({ uploaded: 2 });
24
+ jest.clearAllMocks();
25
+ });
52
26
 
53
- const expectedResult = new Array(configuration.platforms.length)
54
- .fill()
55
- .map(() => true);
27
+ it("delegates the selected manifests in one batch without requiring an account", async () => {
28
+ expect(await zappifestPublish(configuration)).toBe(true);
56
29
 
57
- expect(await zappifestPublish(configuration)).toEqual(expectedResult);
30
+ expect(publish).toHaveBeenCalledTimes(1);
58
31
 
59
- expect(runInShellAsync).toHaveBeenCalledTimes(
60
- configuration.platforms.length
61
- );
32
+ expect(publish).toHaveBeenCalledWith({
33
+ manifestPaths: [
34
+ resolve(__dirname, "manifests/android.json"),
35
+ resolve(__dirname, "manifests/ios.json"),
36
+ ],
37
+ dryRun: false,
38
+ log: logger.log,
39
+ onWarning: logger.warn,
40
+ });
41
+ });
62
42
 
63
- configuration.platforms.forEach((val, index) => {
64
- expect(runInShellAsync).toHaveBeenNthCalledWith(
65
- index + 1,
66
- `zappifest publish --manifest ${__dirname}/manifests/${val}.json --account A1234`
67
- );
43
+ it("does not pass legacy owner metadata as an account-validation request", async () => {
44
+ await zappifestPublish({
45
+ ...configuration,
46
+ zappOwnerAccountId: "A1234",
68
47
  });
48
+
49
+ expect(publish.mock.calls[0][0]).not.toHaveProperty("account");
69
50
  });
70
51
 
71
- it("only logs in the console when running with dry run flag", async () => {
72
- const configuration = getConfig({ dryRun: true });
52
+ it("publishes only the configured platform, not the entire manifest directory", async () => {
53
+ await zappifestPublish({
54
+ ...configuration,
55
+ platforms: ["ios"],
56
+ });
73
57
 
74
- const expectedResult = new Array(configuration.platforms.length)
75
- .fill()
76
- .map(() => true);
58
+ expect(publish.mock.calls[0][0].manifestPaths).toEqual([
59
+ resolve(__dirname, "manifests/ios.json"),
60
+ ]);
61
+ });
77
62
 
78
- expect(await zappifestPublish(configuration)).toEqual(expectedResult);
79
- expect(runInShellAsync).not.toHaveBeenCalled();
63
+ it.each([{ dryRun: true }, { manifestOnly: true }])(
64
+ "does not upload with %j",
65
+ async (options) => {
66
+ expect(await zappifestPublish({ ...configuration, ...options })).toBe(
67
+ true
68
+ );
80
69
 
81
- expect(logger.log).toHaveBeenCalledTimes(
82
- 1 + configuration.platforms.length * 2
83
- );
70
+ expect(publish.mock.calls[0][0].dryRun).toBe(true);
71
+ }
72
+ );
84
73
 
85
- expect(logger.log).toHaveBeenNthCalledWith(
86
- 1,
87
- "Running with --dry-run or --manifest-only option - not actually pushing to zapp"
88
- );
74
+ it.each([undefined, []])("skips absent platforms: %j", async (platforms) => {
75
+ expect(await zappifestPublish({ ...configuration, platforms })).toBe(true);
89
76
 
90
- configuration.platforms.forEach((val, index) => {
91
- expect(logger.log).toHaveBeenNthCalledWith(
92
- index * 2 + 2,
93
- expect.stringMatching(
94
- /running zappifest publish --manifest .*(ios|android)\.json/
95
- )
96
- );
77
+ expect(publish).not.toHaveBeenCalled();
97
78
 
98
- expect(logger.log).toHaveBeenNthCalledWith(
99
- index * 2 + 3,
100
- `with manifest: ${inspect(require(`./manifests/${val}.json`))}`
101
- );
102
- });
79
+ expect(logger.log).toHaveBeenCalledWith(
80
+ "Manifest does not exist, Skipping publishing"
81
+ );
103
82
  });
104
83
 
105
- it("it throws if a manifest cannot be found", async () => {
106
- const configuration = getConfig({ pluginPath: "resolve_error" });
107
- expect(zappifestPublish(configuration)).rejects.toMatchSnapshot();
108
- });
84
+ it("propagates validation, file, and upload failures to the task runner", async () => {
85
+ const error = new Error("Cannot read manifest");
86
+ publish.mockRejectedValueOnce(error);
109
87
 
110
- it("it throws if the zappifest command fails", async () => {
111
- const configuration = getConfig({ pluginPath: "zappifest_error" });
112
- expect(zappifestPublish(configuration)).rejects.toMatchSnapshot();
88
+ await expect(zappifestPublish(configuration)).rejects.toBe(error);
113
89
  });
114
90
  });
@@ -1,4 +1,4 @@
1
- const git = require("simple-git/promise");
1
+ const git = require("simple-git");
2
2
  const fs = require("fs");
3
3
  const path = require("path");
4
4
 
@@ -1,7 +1,7 @@
1
1
  const R = require("ramda");
2
2
  const { resolve } = require("path");
3
3
  const semver = require("semver");
4
- const git = require("simple-git/promise");
4
+ const git = require("simple-git");
5
5
  const logger = require("../../logger");
6
6
  const { existsSync } = require("fs");
7
7
 
@@ -50,13 +50,6 @@ function resolvePluginPath(pluginPath) {
50
50
  );
51
51
  }
52
52
 
53
- if (
54
- manifestExists(pluginPath) &&
55
- !pluginPackageJson.applicaster.zappOwnerAccountId
56
- ) {
57
- throw new Error("your plugin's package.json is missing zappOwnerAccountId");
58
- }
59
-
60
53
  return [resolvedPluginPath, pluginPackageJson];
61
54
  }
62
55
 
@@ -1,6 +1,7 @@
1
- const { runInShellAsync } = require("../../shell");
1
+ const path = require("path");
2
2
  const logger = require("../../logger");
3
3
  const { retryPublishCommand } = require("../utils/retryPublishCommand");
4
+ const { readJsonFile, writeJsonToFile } = require("../../file");
4
5
 
5
6
  async function npmPublish(configuration) {
6
7
  const { dryRun, yarn, next, version, pluginPath, manifestOnly } =
@@ -29,14 +30,10 @@ async function npmPublish(configuration) {
29
30
  }
30
31
 
31
32
  if (version) {
32
- if (yarn) {
33
- await runInShellAsync(
34
- `npm version ${version} --git-tag-version=false --commit-hooks=false --workspaces-update=false`,
35
- cmdOptions
36
- );
37
- } else {
38
- await runInShellAsync(`npm version ${version}`, cmdOptions);
39
- }
33
+ const packageJsonPath = path.join(pluginPath, "package.json");
34
+ const packageJson = await readJsonFile(packageJsonPath);
35
+ packageJson.version = version;
36
+ await writeJsonToFile(packageJsonPath, packageJson);
40
37
  }
41
38
 
42
39
  await retryPublishCommand(publishCommand, cmdOptions, version);
@@ -1,39 +1,41 @@
1
1
  const R = require("ramda");
2
2
  const path = require("path");
3
3
 
4
- const { writeJsonToFile } = require("../../file");
4
+ const { writeJsonToFile, readJsonFile } = require("../../file");
5
5
  const logger = require("../../logger");
6
6
 
7
7
  const PACKAGE_DOT_JSON = "package.json";
8
8
  const QUICK_BRICK_WORKSPACE_NAME = "quick-brick";
9
9
  const CORE_PLUGINS_PATH = "packages/quick-brick-core-plugins";
10
10
 
11
- async function updateCorePluginsIfNeeded(configuration) {
12
- const { name: workspaceName } = require(
13
- path.join(process.cwd(), PACKAGE_DOT_JSON)
14
- );
11
+ let writeLock = Promise.resolve();
12
+
13
+ async function doUpdateCorePlugins(configuration) {
14
+ const rootPackageJsonPath = path.join(process.cwd(), PACKAGE_DOT_JSON);
15
+ const rootPackageJson = await readJsonFile(rootPackageJsonPath);
15
16
 
16
- if (workspaceName !== QUICK_BRICK_WORKSPACE_NAME) {
17
+ if (rootPackageJson.name !== QUICK_BRICK_WORKSPACE_NAME) {
17
18
  return;
18
19
  }
19
20
 
20
21
  const { version, pluginPackageJson } = configuration;
21
22
  const { name } = pluginPackageJson;
22
23
 
23
- const corePluginsPackageJson = require(
24
- path.join(process.cwd(), CORE_PLUGINS_PATH, PACKAGE_DOT_JSON)
24
+ const corePluginsPackageJsonPath = path.join(
25
+ process.cwd(),
26
+ CORE_PLUGINS_PATH,
27
+ PACKAGE_DOT_JSON
25
28
  );
26
29
 
30
+ const corePluginsPackageJson = await readJsonFile(corePluginsPackageJsonPath);
31
+
27
32
  const { dependencies } = corePluginsPackageJson;
28
33
  const isPluginCore = R.contains(name, R.keys(dependencies));
29
34
 
30
35
  if (isPluginCore) {
31
36
  corePluginsPackageJson.dependencies[name] = version;
32
37
 
33
- await writeJsonToFile(
34
- path.join(process.cwd(), CORE_PLUGINS_PATH, PACKAGE_DOT_JSON),
35
- corePluginsPackageJson
36
- );
38
+ await writeJsonToFile(corePluginsPackageJsonPath, corePluginsPackageJson);
37
39
 
38
40
  logger.log(`Core Plugins updated with ${name}@${version}`);
39
41
  } else {
@@ -41,4 +43,19 @@ async function updateCorePluginsIfNeeded(configuration) {
41
43
  }
42
44
  }
43
45
 
46
+ async function updateCorePluginsIfNeeded(configuration) {
47
+ // During monorepo deploy (--skip-git), scripts/deploy updates quick-brick-core-plugins
48
+ // once in memory across all published plugins and writes it prior to its own publish.
49
+ // Skipping here prevents concurrent workers from racing to overwrite the file on disk.
50
+ if (configuration.skipGit) {
51
+ return;
52
+ }
53
+
54
+ // Ensure that concurrent publishing tasks do not race when updating core plugins
55
+ const result = writeLock.then(() => doUpdateCorePlugins(configuration));
56
+ writeLock = result.catch(() => {});
57
+
58
+ return result;
59
+ }
60
+
44
61
  module.exports = { updateCorePluginsIfNeeded };
@@ -1,53 +1,27 @@
1
- const R = require("ramda");
2
1
  const { resolve } = require("path");
3
- const { inspect } = require("util");
2
+ const { publish } = require("@applicaster/zappifest-nano");
4
3
 
5
- const { runInShellAsync } = require("../../shell");
6
4
  const logger = require("../../logger");
7
5
 
8
- function pushZappifest({
9
- pluginPath,
10
- dryRun,
11
- manifestOnly,
12
- zappOwnerAccountId,
13
- }) {
14
- return async function (platform) {
15
- const manifestPath = resolve(pluginPath, `manifests/${platform}.json`);
16
- const publishCommand = `zappifest publish --manifest ${manifestPath} --account ${zappOwnerAccountId}`;
17
-
18
- if (dryRun || manifestOnly) {
19
- logger.log(`running ${publishCommand}`);
20
- logger.log(`with manifest: ${inspect(require(manifestPath))}`);
21
-
22
- return true;
23
- }
24
-
25
- return await runInShellAsync(publishCommand);
26
- };
27
- }
28
-
29
6
  async function zappifestPublish(configuration) {
30
- const { platforms, pluginPath, dryRun, manifestOnly, zappOwnerAccountId } =
31
- configuration;
32
-
33
- if (dryRun || manifestOnly) {
34
- logger.log(
35
- "Running with --dry-run or --manifest-only option - not actually pushing to zapp"
36
- );
37
- }
7
+ const { platforms, pluginPath, dryRun, manifestOnly } = configuration;
38
8
 
39
- if (!platforms || !zappOwnerAccountId) {
9
+ if (!platforms || platforms.length === 0) {
40
10
  logger.log("Manifest does not exist, Skipping publishing");
41
11
 
42
12
  return true;
43
13
  }
44
14
 
45
- return Promise.all(
46
- R.map(
47
- pushZappifest({ pluginPath, dryRun, manifestOnly, zappOwnerAccountId }),
48
- platforms
49
- )
50
- );
15
+ await publish({
16
+ manifestPaths: platforms.map((platform) =>
17
+ resolve(pluginPath, `manifests/${platform}.json`)
18
+ ),
19
+ dryRun: Boolean(dryRun || manifestOnly),
20
+ log: logger.log,
21
+ onWarning: logger.warn,
22
+ });
23
+
24
+ return true;
51
25
  }
52
26
 
53
27
  module.exports = { zappifestPublish };
@@ -22,10 +22,16 @@ describe("writeJsonTofile", () => {
22
22
  await writeJsonToFile(filePath, json);
23
23
 
24
24
  expect(fs.writeFile).toHaveBeenCalledWith(
25
- filePath,
25
+ expect.stringMatching(/^someFile\.json\.tmp\./),
26
26
  JSON.stringify(json, null, 2),
27
27
  expect.any(Function)
28
28
  );
29
+
30
+ expect(fs.rename).toHaveBeenCalledWith(
31
+ expect.stringMatching(/^someFile\.json\.tmp\./),
32
+ filePath,
33
+ expect.any(Function)
34
+ );
29
35
  });
30
36
  });
31
37
 
package/src/file/index.js CHANGED
@@ -5,23 +5,34 @@ const R = require("ramda");
5
5
  * @module @applicaster/zapplicaster-cli/util/file
6
6
  */
7
7
 
8
- const { writeFile, readFile, readdir, copyFile, copyFileSync } = require("fs");
8
+ const {
9
+ writeFile,
10
+ readFile,
11
+ readdir,
12
+ copyFile,
13
+ copyFileSync,
14
+ rename,
15
+ } = require("fs");
16
+
9
17
  const { promisify } = require("util");
10
18
  const { join } = require("path");
11
19
 
12
20
  const writeFileAsync = promisify(writeFile);
21
+ const renameAsync = promisify(rename);
13
22
  const readFileAsync = promisify(readFile);
14
23
  const readdirAsync = promisify(readdir);
15
24
  const copyFileAsync = promisify(copyFile);
16
25
 
17
26
  /**
18
- * Writes a pretty-printed json file from a javascript object
27
+ * Writes a pretty-printed json file from a javascript object atomically
19
28
  * @param {String} path : path of the file to write
20
29
  * @param {Object} object : object to write to the file
21
30
  * @returns {Promise}
22
31
  */
23
32
  async function writeJsonToFile(path, object) {
24
- return await writeFileAsync(path, JSON.stringify(object, null, 2));
33
+ const tmpPath = `${path}.tmp.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`;
34
+ await writeFileAsync(tmpPath, JSON.stringify(object, null, 2));
35
+ await renameAsync(tmpPath, path);
25
36
  }
26
37
 
27
38
  /**
@@ -48,6 +48,16 @@ function copyFileSync() {
48
48
  return { status: "ok" };
49
49
  }
50
50
 
51
+ function rename(oldPath, newPath, callback) {
52
+ const file = fs.__writenFiles.find((f) => f.fileName === oldPath);
53
+
54
+ if (file) {
55
+ file.fileName = newPath;
56
+ }
57
+
58
+ callback(null);
59
+ }
60
+
51
61
  function existsSync(path) {
52
62
  return R.includes(path, R.map(R.prop("fileName"), fs.__writenFiles));
53
63
  }
@@ -87,6 +97,7 @@ fs.readFile = jest.fn(readFile);
87
97
  fs.readFileSync = jest.fn(readFileSync);
88
98
  fs.copyFile = jest.fn(copyFile);
89
99
  fs.copyFileSync = jest.fn(copyFileSync);
100
+ fs.rename = jest.fn(rename);
90
101
  fs.existsSync = jest.fn(existsSync);
91
102
  fs.statSync = jest.fn(statSync);
92
103
 
@@ -1,5 +0,0 @@
1
- // Jest Snapshot v1, https://goo.gl/fbAQLP
2
-
3
- exports[`publish zappifests it throws if a manifest cannot be found 1`] = `[Error: cannot resolve manifest]`;
4
-
5
- exports[`publish zappifests it throws if the zappifest command fails 1`] = `[Error: zappifest failed]`;