@webiny/cli 0.0.0-mt-3 → 0.0.0-unstable.2af142b57e

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/README.md CHANGED
@@ -4,4 +4,4 @@
4
4
  [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
5
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
6
 
7
- A pluggable tool to run commands within a Webiny project.
7
+ A pluggable tool to run commands within a Webiny project.
package/bin.js CHANGED
@@ -7,14 +7,14 @@ const semver = require("semver");
7
7
  const currentNodeVersion = process.versions.node;
8
8
 
9
9
  (async () => {
10
- if (!semver.satisfies(currentNodeVersion, "^12 || ^14")) {
10
+ if (!semver.satisfies(currentNodeVersion, ">=14")) {
11
11
  console.error(
12
12
  chalk.red(
13
- "You are running Node " +
14
- currentNodeVersion +
15
- ".\n" +
16
- "Webiny requires Node ^12 or ^14. \n" +
17
- "Please update your version of Node."
13
+ [
14
+ `You are running Node.js ${currentNodeVersion}, but Webiny requires version 14 or higher.`,
15
+ `Please switch to one of the required versions and try again.`,
16
+ `For more information, please visit https://docs.webiny.com/docs/tutorials/install-webiny#prerequisites.`
17
+ ].join(" ")
18
18
  )
19
19
  );
20
20
  process.exit(1);
@@ -22,13 +22,15 @@ const currentNodeVersion = process.versions.node;
22
22
 
23
23
  try {
24
24
  const { stdout } = await execa("yarn", ["--version"]);
25
- if (!semver.satisfies(stdout, "^2||^3")) {
26
- console.error(chalk.red(`"@webiny/cli" requires yarn ^2 or ^3 to be installed!`));
25
+ if (!semver.satisfies(stdout, ">=2")) {
26
+ console.error(chalk.red(`"@webiny/cli" requires yarn >=2!`));
27
27
  process.exit(1);
28
28
  }
29
29
  } catch (err) {
30
- console.error(chalk.red(`"@webiny/cli" requires yarn ^2 or ^3 to be installed!`));
31
- console.log(`Please visit https://yarnpkg.com/ to install "yarn".`);
30
+ console.error(chalk.red(`"@webiny/cli" requires yarn >=2!`));
31
+ console.log(
32
+ `Run ${chalk.blue("yarn set version berry")} to install a compatible version of yarn.`
33
+ );
32
34
  process.exit(1);
33
35
  }
34
36
 
package/cli.js CHANGED
@@ -1,32 +1,11 @@
1
1
  #!/usr/bin/env node
2
- const path = require("path");
3
2
  const yargs = require("yargs");
4
- const { log, getProject } = require("./utils");
5
- const { boolean } = require("boolean");
6
3
 
7
4
  // Disable help processing until after plugins are imported.
8
5
  yargs.help(false);
9
6
 
10
- // Immediately load .env.{PASSED_ENVIRONMENT} and .env files.
11
- // This way we ensure all of the environment variables are not loaded too late.
12
- const project = getProject();
13
- let paths = [path.join(project.root, ".env")];
14
-
15
- if (yargs.argv.env) {
16
- paths.push(path.join(project.root, `.env.${yargs.argv.env}`));
17
- }
18
-
19
- for (let i = 0; i < paths.length; i++) {
20
- const path = paths[i];
21
- const { error } = require("dotenv").config({ path });
22
- if (boolean(yargs.argv.debug)) {
23
- if (error) {
24
- log.debug(`No environment file found on ${log.debug.hl(path)}.`);
25
- } else {
26
- log.success(`Successfully loaded environment variables from ${log.success.hl(path)}.`);
27
- }
28
- }
29
- }
7
+ // Loads environment variables from multiple sources.
8
+ require("./utils/loadEnvVariables");
30
9
 
31
10
  const { blue, red } = require("chalk");
32
11
  const context = require("./context");
@@ -38,7 +17,7 @@ yargs
38
17
  .recommendCommands()
39
18
  .scriptName("webiny")
40
19
  .epilogue(
41
- `To find more information, docs and tutorials, see ${blue("https://docs.webiny.com")}.`
20
+ `To find more information, docs and tutorials, see ${blue("https://www.webiny.com/docs")}.`
42
21
  )
43
22
  .epilogue(`Want to contribute? ${blue("https://github.com/webiny/webiny-js")}.`)
44
23
  .fail(function (msg, error, yargs) {
package/commands/index.js CHANGED
@@ -5,6 +5,13 @@ const upgrade = require("./upgrade");
5
5
  module.exports.createCommands = async (yargs, context) => {
6
6
  context.plugins.register(run, telemetry, upgrade);
7
7
 
8
+ try {
9
+ const wcp = require("./wcp");
10
+ context.plugins.register(wcp);
11
+ } catch {
12
+ // Skip WCP command
13
+ }
14
+
8
15
  await context.loadUserPlugins();
9
16
 
10
17
  context.plugins.byType("cli-command").forEach(plugin => {
@@ -1,5 +1,6 @@
1
1
  const camelCase = require("camelcase");
2
2
  const findUp = require("find-up");
3
+ const path = require("path");
3
4
 
4
5
  module.exports = {
5
6
  type: "cli-command",
@@ -16,9 +17,16 @@ module.exports = {
16
17
  },
17
18
  async argv => {
18
19
  const configFile = findUp.sync(["webiny.config.ts", "webiny.config.js"]);
19
- const config = context.import(configFile);
20
+ let config = context.import(configFile);
20
21
 
21
22
  const command = camelCase(argv.command);
23
+ if (typeof config === "function") {
24
+ config = config({
25
+ options: { ...argv, cwd: path.dirname(configFile) },
26
+ context
27
+ });
28
+ }
29
+
22
30
  if (config.commands && typeof config.commands[command] === "function") {
23
31
  return await config.commands[command]({ ...argv }, context);
24
32
  }
@@ -0,0 +1,133 @@
1
+ const { encrypt, decrypt } = require("@webiny/wcp");
2
+ const { getUser, getProjectEnvironment, updateUserLastActiveOn } = require("./utils");
3
+
4
+ /**
5
+ * The two environment variables we set via these hooks are the following:
6
+ * - WCP_PROJECT_ENVIRONMENT - contains encrypted data about the deployed project environment
7
+ * - WCP_PROJECT_ENVIRONMENT_API_KEY - for easier access, we also set the API key
8
+ */
9
+
10
+ /**
11
+ * There are multiple ways the hooks below prepare the WCP-enabled project for deployment.
12
+ * 1. If `WCP_PROJECT_ENVIRONMENT` metadata env var is defined, we decrypt it, retrieve the
13
+ * API key from it, and assign it as the `WCP_PROJECT_ENVIRONMENT_API_KEY` env var.
14
+ * 2. If `WCP_PROJECT_ENVIRONMENT_API_KEY` env var is defined, then we use that as the
15
+ * project environment API key. We use that to load the project environment data
16
+ * and to also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.
17
+ * 3. If none of the above is defined, we retrieve (or create) the project environment,
18
+ * retrieve its API key and again assign it as `WCP_PROJECT_ENVIRONMENT_API_KEY` env var.
19
+ * As in 2), we also assign the `WCP_PROJECT_ENVIRONMENT` metadata env var.
20
+ */
21
+
22
+ let projectEnvironment;
23
+
24
+ const getEnvironmentHookHandler = async (args, context) => {
25
+ // If the project isn't linked with WCP, do nothing.
26
+ const wcpProjectId = context.project.config.id || process.env.WCP_PROJECT_ID;
27
+ if (!wcpProjectId) {
28
+ return;
29
+ }
30
+
31
+ // For development purposes, we allow setting the WCP_PROJECT_ENVIRONMENT env var directly.
32
+ if (process.env.WCP_PROJECT_ENVIRONMENT) {
33
+ // If we have WCP_PROJECT_ENVIRONMENT env var, we set the WCP_PROJECT_ENVIRONMENT_API_KEY too.
34
+ const decryptedProjectEnvironment = decrypt(process.env.WCP_PROJECT_ENVIRONMENT);
35
+ process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = decryptedProjectEnvironment.apiKey;
36
+ return;
37
+ }
38
+
39
+ // The `id` has the orgId/projectId structure, for example `my-org-x/my-project-y`.
40
+ const [orgId, projectId] = wcpProjectId.split("/");
41
+
42
+ const apiKey = process.env.WCP_PROJECT_ENVIRONMENT_API_KEY;
43
+
44
+ let projectEnvironment;
45
+ if (apiKey) {
46
+ projectEnvironment = await getProjectEnvironment({ apiKey });
47
+ } else {
48
+ const isValidId = orgId && projectId;
49
+ if (!isValidId) {
50
+ throw new Error(
51
+ `It seems the project ID, specified in "webiny.project.ts" file, is invalid.`
52
+ );
53
+ }
54
+
55
+ // If there is no API key, that means we need to retrieve the currently logged-in user.
56
+ const user = await getUser();
57
+ const project = user.projects.find(item => item.id === projectId);
58
+ if (!project) {
59
+ throw new Error(
60
+ `It seems you don't belong to the current project or the current project has been deleted.`
61
+ );
62
+ }
63
+
64
+ projectEnvironment = await getProjectEnvironment({
65
+ orgId,
66
+ projectId,
67
+ userId: user.id,
68
+ environmentId: args.env
69
+ });
70
+ }
71
+
72
+ if (projectEnvironment.org.id !== orgId) {
73
+ throw new Error(
74
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment doesn't belong to the "${orgId}" organization. Please check your WCP project ID (currently set to "${wcpProjectId}").`
75
+ );
76
+ }
77
+
78
+ if (projectEnvironment.project.id !== projectId) {
79
+ throw new Error(
80
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment doesn't belong to the "${wcpProjectId}" project. Please check your WCP project ID (currently set to "${wcpProjectId}").`
81
+ );
82
+ }
83
+
84
+ if (projectEnvironment && projectEnvironment.status !== "enabled") {
85
+ throw new Error(
86
+ `Cannot proceed with the deployment because the "${projectEnvironment.name}" project environment has been disabled.`
87
+ );
88
+ }
89
+
90
+ // Assign `WCP_PROJECT_ENVIRONMENT` and `WCP_PROJECT_ENVIRONMENT_API_KEY`
91
+ const wcpProjectEnvironment = {
92
+ id: projectEnvironment.id,
93
+ apiKey: projectEnvironment.apiKey,
94
+ org: { id: projectEnvironment.org.id },
95
+ project: { id: projectEnvironment.project.id }
96
+ };
97
+
98
+ process.env.WCP_PROJECT_ENVIRONMENT = encrypt(wcpProjectEnvironment);
99
+ process.env.WCP_PROJECT_ENVIRONMENT_API_KEY = projectEnvironment.apiKey;
100
+ };
101
+
102
+ const updateLastActiveOnHookHandler = async () => {
103
+ if (!projectEnvironment) {
104
+ return;
105
+ }
106
+
107
+ // Is this a user environment? If so, let's update his "last active" field.
108
+ if (projectEnvironment.user) {
109
+ await updateUserLastActiveOn();
110
+ }
111
+ };
112
+
113
+ // Export hooks plugins for deploy and watch commands.
114
+ module.exports = () => [
115
+ // Deploy hook handlers.
116
+ {
117
+ type: "hook-before-deploy",
118
+ name: "hook-before-deploy-environment-get-environment",
119
+ hook: getEnvironmentHookHandler
120
+ },
121
+ {
122
+ type: "hook-before-deploy",
123
+ name: "hook-before-deploy-update-last-active-on",
124
+ hook: updateLastActiveOnHookHandler
125
+ },
126
+
127
+ // Watch hook handlers.
128
+ {
129
+ type: "hook-before-watch",
130
+ name: "hook-before-watch-environment-get-environment",
131
+ hook: getEnvironmentHookHandler
132
+ }
133
+ ];
@@ -0,0 +1,8 @@
1
+ const { command: login } = require("./login");
2
+ const { command: logout } = require("./logout");
3
+ const { command: whoami } = require("./whoami");
4
+ const { command: project } = require("./project");
5
+
6
+ const hooks = require("./hooks");
7
+
8
+ module.exports = [login(), logout(), whoami(), project(), hooks()];
@@ -0,0 +1,228 @@
1
+ const open = require("open");
2
+ const { GraphQLClient } = require("graphql-request");
3
+ const { setProjectId, setWcpPat, sleep } = require("./utils");
4
+ const chalk = require("chalk");
5
+ const { getWcpGqlApiUrl, getWcpAppUrl } = require("@webiny/wcp");
6
+
7
+ // 120 retries * 2000ms interval = 4 minutes until the command returns an error.
8
+ const LOGIN_RETRIES_COUNT = 30;
9
+ const LOGIN_RETRIES_INTERVAL = 2000;
10
+
11
+ const USER_PAT_FIELDS = /* GraphQL */ `
12
+ fragment UserPatFields on UserPat {
13
+ name
14
+ meta
15
+ token
16
+ expiresOn
17
+ user {
18
+ email
19
+ }
20
+ }
21
+ `;
22
+
23
+ const GENERATE_USER_PAT = /* GraphQL */ `
24
+ mutation GenerateUserPat {
25
+ users {
26
+ generateUserPat
27
+ }
28
+ }
29
+ `;
30
+
31
+ const GET_USER_PAT = /* GraphQL */ `
32
+ ${USER_PAT_FIELDS}
33
+ query GetUserPat($token: ID!) {
34
+ users {
35
+ getUserPat(token: $token) {
36
+ ...UserPatFields
37
+ }
38
+ }
39
+ }
40
+ `;
41
+
42
+ const CREATE_USER_PAT = /* GraphQL */ `
43
+ ${USER_PAT_FIELDS}
44
+ mutation CreateUserPat($expiresIn: Int, $token: ID, $data: CreateUserPatDataInput) {
45
+ users {
46
+ createUserPat(expiresIn: $expiresIn, token: $token, data: $data) {
47
+ ...UserPatFields
48
+ }
49
+ }
50
+ }
51
+ `;
52
+
53
+ module.exports.command = () => ({
54
+ type: "cli-command",
55
+ name: "cli-command-wcp-login",
56
+ create({ yargs, context }) {
57
+ yargs.command(
58
+ "login [pat]",
59
+ `Log in to the Webiny Control Panel`,
60
+ yargs => {
61
+ yargs.example("$0 login");
62
+ yargs.positional("pat", {
63
+ describe: `Personal access token (PAT)`,
64
+ type: "string"
65
+ });
66
+ yargs.option("debug", {
67
+ describe: `Turn on debug logs`,
68
+ type: "boolean"
69
+ });
70
+ yargs.option("debug-level", {
71
+ default: 1,
72
+ describe: `Set the debug logs verbosity level`,
73
+ type: "number"
74
+ });
75
+ },
76
+ async ({ debug, debugLevel, pat: patFromParams }) => {
77
+ const graphQLClient = new GraphQLClient(getWcpGqlApiUrl());
78
+
79
+ let pat;
80
+
81
+ if (patFromParams) {
82
+ try {
83
+ graphQLClient.setHeaders({ authorization: patFromParams });
84
+ pat = await graphQLClient
85
+ .request(GET_USER_PAT, { token: patFromParams })
86
+ .then(({ users }) => users.getUserPat);
87
+
88
+ // If we've received a PAT that has expiration, let's create a long-lived PAT.
89
+ // We don't want to have our users interrupted because of an expired PAT.
90
+ if (pat.expiresOn) {
91
+ pat = await graphQLClient
92
+ .request(CREATE_USER_PAT, { data: { meta: pat.meta } })
93
+ .then(({ users }) => users.createUserPat);
94
+ }
95
+ } catch (e) {
96
+ if (debug) {
97
+ context.debug(
98
+ `Could not use the provided ${context.debug.hl(
99
+ patFromParams
100
+ )} PAT because of the following error:`
101
+ );
102
+ console.debug(e);
103
+ }
104
+
105
+ throw new Error(
106
+ `Invalid PAT received. Please try again or login manually via the ${context.error.hl(
107
+ "yarn webiny login"
108
+ )} command.`
109
+ );
110
+ }
111
+ } else {
112
+ const generatedPat = await graphQLClient
113
+ .request(GENERATE_USER_PAT)
114
+ .then(({ users }) => users.generateUserPat);
115
+
116
+ const queryParams = `pat=${generatedPat}&pat_name=${encodeURIComponent(
117
+ "Webiny CLI"
118
+ )}&ref=cli`;
119
+ const openUrl = `${getWcpAppUrl()}/login/cli?${queryParams}`;
120
+
121
+ debug && context.debug(`Opening ${context.debug.hl(openUrl)}...`);
122
+ await open(openUrl);
123
+
124
+ const graphql = {
125
+ variables: { token: generatedPat },
126
+ headers: {
127
+ Authorization: generatedPat
128
+ }
129
+ };
130
+
131
+ graphQLClient.setHeaders(graphql.headers);
132
+
133
+ let retries = 0;
134
+ const result = await new Promise(resolve => {
135
+ const interval = setInterval(async () => {
136
+ retries++;
137
+ if (retries > LOGIN_RETRIES_COUNT) {
138
+ clearInterval(interval);
139
+ resolve(null);
140
+ }
141
+
142
+ try {
143
+ const pat = await graphQLClient
144
+ .request(GET_USER_PAT, graphql.variables)
145
+ .then(({ users }) => users.getUserPat);
146
+
147
+ clearInterval(interval);
148
+ resolve(pat);
149
+ } catch (e) {
150
+ // Do nothing.
151
+ if (debug) {
152
+ context.debug(
153
+ `Could not login. Will try again in ${LOGIN_RETRIES_INTERVAL}ms.`
154
+ );
155
+ if (debugLevel > 1) {
156
+ context.debug("GraphQL Request: ");
157
+ console.log(JSON.stringify(graphql, null, 2));
158
+ }
159
+ if (debugLevel > 2) {
160
+ context.debug(e.message);
161
+ }
162
+ }
163
+ }
164
+ }, LOGIN_RETRIES_INTERVAL);
165
+ });
166
+
167
+ if (!result) {
168
+ throw new Error(
169
+ `Could not login. Did you complete the sign in / sign up process at ${getWcpAppUrl()}?`
170
+ );
171
+ }
172
+
173
+ pat = result;
174
+ }
175
+
176
+ setWcpPat(pat.token);
177
+
178
+ console.log(
179
+ `${chalk.green("✔")} You've successfully logged in to Webiny Control Panel.`
180
+ );
181
+
182
+ let projectInitialized = Boolean(
183
+ context.project.config.id || process.env.WCP_PROJECT_ID
184
+ );
185
+
186
+ // If we have `orgId` and `projectId` in PAT's metadata, let's immediately link the project.
187
+ if (pat.meta && pat.meta.orgId && pat.meta.projectId) {
188
+ await sleep();
189
+
190
+ console.log();
191
+
192
+ const { orgId, projectId } = pat.meta;
193
+
194
+ const id = `${orgId}/${projectId}`;
195
+ console.log(`Project ${chalk.green(id)} detected. Linking...`);
196
+
197
+ await sleep();
198
+
199
+ await setProjectId({
200
+ project: context.project,
201
+ orgId,
202
+ projectId
203
+ });
204
+
205
+ console.log(`Project ${context.success.hl(id)} linked successfully.`);
206
+ projectInitialized = true;
207
+ }
208
+
209
+ await sleep();
210
+
211
+ console.log();
212
+ console.log(chalk.bold("Next Steps"));
213
+
214
+ if (!projectInitialized) {
215
+ console.log(
216
+ `‣ link your project via the ${chalk.green(
217
+ "yarn webiny project link"
218
+ )} command`
219
+ );
220
+ }
221
+
222
+ console.log(
223
+ `‣ deploy your project via the ${chalk.green("yarn webiny deploy")} command`
224
+ );
225
+ }
226
+ );
227
+ }
228
+ });
@@ -0,0 +1,28 @@
1
+ const { setWcpPat } = require("./utils");
2
+
3
+ module.exports.command = () => ({
4
+ type: "cli-command",
5
+ name: "cli-command-wcp-logout",
6
+ create({ yargs }) {
7
+ yargs.command(
8
+ "logout",
9
+ `Log out from the Webiny Control Panel`,
10
+ yargs => {
11
+ yargs.example("$0 logout");
12
+ yargs.option("debug", {
13
+ describe: `Turn on debug logs`,
14
+ type: "boolean"
15
+ });
16
+ yargs.option("debug-level", {
17
+ default: 1,
18
+ describe: `Set the debug logs verbosity level`,
19
+ type: "number"
20
+ });
21
+ },
22
+ async () => {
23
+ setWcpPat(null);
24
+ console.log(`You've successfully logged out from Webiny Control Panel.`);
25
+ }
26
+ );
27
+ }
28
+ });