qa 0.0.7 → 0.0.9

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/dist/auth.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
+ import { intro } from '@clack/prompts';
3
+ import { askForUserAuth } from './commands/utils/prompts.js';
2
4
  import { TOKEN_PATH } from './constants.js';
3
5
  export async function getAccessToken(tokenParam) {
4
6
  if (tokenParam) {
@@ -10,12 +12,14 @@ export async function getAccessToken(tokenParam) {
10
12
  }
11
13
  const hasAccess = await fs.access(TOKEN_PATH).then(() => true).catch(() => false);
12
14
  if (!hasAccess) {
13
- throw new Error('User is not authenticated');
15
+ intro('Log into CodelessQA');
16
+ return askForUserAuth();
14
17
  }
15
18
  const rc = await fs.readFile(TOKEN_PATH, 'utf-8');
16
19
  const token = rc.split('\n').filter(Boolean).find((line) => line.startsWith('token='))?.split('=')[1];
17
20
  if (!token) {
18
- throw new Error('User is not authenticated');
21
+ intro('Log into CodelessQA');
22
+ return askForUserAuth();
19
23
  }
20
24
  return token;
21
25
  }
@@ -1,3 +1,4 @@
1
1
  import * as login from './login.js';
2
2
  import * as test from './test.js';
3
- export const commands = [login, test];
3
+ import * as init from './init.js';
4
+ export const commands = [login, init, test];
@@ -0,0 +1,19 @@
1
+ import type { Argv } from 'yargs';
2
+ export declare const command = "init [option]";
3
+ export declare const desc = "Create a new CodelessQA project";
4
+ export declare const cmdArgs: {
5
+ readonly token: {
6
+ readonly alias: "t";
7
+ readonly desc: "Provide an access token to authenticate with the platform";
8
+ readonly type: "string";
9
+ };
10
+ };
11
+ export declare const builder: (yargs: Argv) => Argv<import("yargs").Omit<{}, "token"> & import("yargs").InferredOptionTypes<{
12
+ readonly token: {
13
+ readonly alias: "t";
14
+ readonly desc: "Provide an access token to authenticate with the platform";
15
+ readonly type: "string";
16
+ };
17
+ }>>;
18
+ export declare const handler: (argv: typeof cmdArgs) => Promise<void>;
19
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1,64 @@
1
+ import { intro, outro, spinner } from '@clack/prompts';
2
+ import { getAccessToken } from '../auth.js';
3
+ import { getPresignUrl, uploadSpecification, fetchProjectNames, waitForUploadFinishes, createSpecification, generateTests, validateAuthToken } from './utils/index.js';
4
+ import { askTestingType, askSpecLocation, askProjectDetails, askSecurityParams, askServerParams, askForUserAuth } from './utils/prompts.js';
5
+ import { CLI_EPILOGUE } from '../constants.js';
6
+ export const command = 'init [option]';
7
+ export const desc = 'Create a new CodelessQA project';
8
+ export const cmdArgs = {
9
+ token: {
10
+ alias: 't',
11
+ desc: 'Provide an access token to authenticate with the platform',
12
+ type: 'string',
13
+ }
14
+ };
15
+ export const builder = (yargs) => {
16
+ return yargs
17
+ .options(cmdArgs)
18
+ .example('qa init', 'Creates a new CodelessQA project')
19
+ .epilogue(CLI_EPILOGUE)
20
+ .help();
21
+ };
22
+ export const handler = async (argv) => {
23
+ let token = await getAccessToken(argv.token);
24
+ const s = spinner();
25
+ intro('Start new CodelessQA project');
26
+ await askTestingType();
27
+ const { specPath, specString, spec } = await askSpecLocation();
28
+ s.start('Looking up user account...');
29
+ let userAuth = await validateAuthToken(token);
30
+ if (!userAuth.valid) {
31
+ s.stop('Couldn\'t authenticate with the platform.');
32
+ console.log('\n');
33
+ token = await askForUserAuth();
34
+ userAuth = await validateAuthToken(token);
35
+ }
36
+ /**
37
+ * start uploading the specification while continue to have the user answer questions
38
+ */
39
+ const uploadProcess = (async () => {
40
+ const presignedUrl = await getPresignUrl(token, specPath);
41
+ await uploadSpecification(presignedUrl, specString);
42
+ return waitForUploadFinishes(presignedUrl);
43
+ })();
44
+ const projectNames = await fetchProjectNames(token);
45
+ s.stop(`User ${userAuth.email} authenticated!`);
46
+ const projectProps = await askProjectDetails(projectNames, spec);
47
+ const securityParams = await askSecurityParams(spec);
48
+ const serverParam = await askServerParams(spec);
49
+ s.start('Uploading specification...');
50
+ const fileOrError = await uploadProcess.catch((err) => err);
51
+ if (fileOrError instanceof Error) {
52
+ s.stop();
53
+ outro(fileOrError.message);
54
+ process.exit(0);
55
+ }
56
+ s.stop(`Specification ${spec.info.title} (${spec.info.version}) uploaded!`);
57
+ s.start('Creating project...');
58
+ const id = await createSpecification(token, projectProps, fileOrError, s);
59
+ s.stop(`Project "${projectProps.name}" created!`);
60
+ s.start('Creating API tests...');
61
+ await generateTests(token, id, s, { securityParams, serverParam });
62
+ s.stop('API tests created!');
63
+ outro(`You're all set!\n\nNow run your first test with:\n> qa test "${projectProps.name}"`);
64
+ };
@@ -15,5 +15,5 @@ export declare const builder: (yargs: Argv) => Argv<import("yargs").Omit<{}, "to
15
15
  readonly type: "string";
16
16
  };
17
17
  }>>;
18
- export declare const handler: (argv: typeof cmdArgs) => Promise<void>;
18
+ export declare const handler: (argv?: Record<keyof typeof cmdArgs, string>) => Promise<string>;
19
19
  //# sourceMappingURL=login.d.ts.map
@@ -23,12 +23,18 @@ export const builder = (yargs) => {
23
23
  .help();
24
24
  };
25
25
  export const handler = async (argv) => {
26
- if (argv.token) {
27
- return console.log('Logging in via access token', argv.token);
26
+ if (argv?.token) {
27
+ console.log('Logging in via access token', argv.token);
28
+ return argv.token;
28
29
  }
29
30
  const ticket = uuidv4();
30
31
  const loginUrl = `${PLATFORM_URL}/login/${ticket}`;
31
- console.log('🦄 Logging in via UI 🙌\n', `👉 Visit the following URL to log in: ${loginUrl}\n`, '\n', '...waiting for user to be authenticated...');
32
+ console.log([
33
+ '🦄 Logging in via UI 🙌',
34
+ `👉 Visit the following URL to log in: ${loginUrl}`,
35
+ '',
36
+ '...waiting for user to be authenticated...'
37
+ ].join('\n'));
32
38
  execSync(`open ${loginUrl}`);
33
39
  try {
34
40
  const token = await new Promise((resolve, reject) => {
@@ -48,6 +54,7 @@ export const handler = async (argv) => {
48
54
  });
49
55
  await fs.writeFile(TOKEN_PATH, `token=${token}\n`);
50
56
  console.log('🎉 Successfully logged in!');
57
+ return token;
51
58
  }
52
59
  catch (err) {
53
60
  console.log(`🚨 Failed to log-in: ${err.message}`);
@@ -4,7 +4,7 @@ import WebSocket from 'ws';
4
4
  import { getAuthenticatedClient } from '@codeless.qa/contracts/client';
5
5
  import { pullTestSuite } from '../api.js';
6
6
  import { getAccessToken } from '../auth.js';
7
- import { CLI_EPILOGUE, WORKER_HOSTNAME } from '../constants.js';
7
+ import { CLI_EPILOGUE, WORKER_URL } from '../constants.js';
8
8
  const SUPPORTED_REPORTER = [
9
9
  'classic', 'doc', 'dot', 'dump', 'json', 'jsonstream', 'landing',
10
10
  'list', 'markdown', 'min', 'nyan', 'progress', 'silent', 'spec',
@@ -41,18 +41,14 @@ export const builder = (yargs) => {
41
41
  export const handler = async (argv) => {
42
42
  const token = await getAccessToken(argv.token);
43
43
  const client = getAuthenticatedClient(token);
44
- // console.log('Running test on project', argv.project)
45
44
  const reporter = argv.reporter;
46
45
  if (!SUPPORTED_REPORTER.includes(reporter)) {
47
46
  throw new Error(`Reporter ${argv.reporter} is not supported, please select one of the following: ${SUPPORTED_REPORTER.join(', ')}`);
48
47
  }
49
48
  const { testplan, specification } = await pullTestSuite(client, argv.project);
50
- const workerUrl = `ws://${WORKER_HOSTNAME}/session`;
51
- // console.log(`Connecting with worker at ${workerUrl}`)
49
+ const workerUrl = `${WORKER_URL}/session`;
52
50
  const ws = new WebSocket(workerUrl);
53
- ws.on('error', console.error);
54
51
  ws.on('open', function open() {
55
- // console.log(`Connected to worker at ${workerUrl}`)
56
52
  const payload = {
57
53
  type: 0,
58
54
  value: {
@@ -62,20 +58,40 @@ export const handler = async (argv) => {
62
58
  };
63
59
  ws.send(JSON.stringify(payload));
64
60
  });
61
+ ws.on('error', (error) => {
62
+ if ('code' in error && error.code === 'ECONNRESET') {
63
+ console.error(`Failed to connect to worker at ${workerUrl}: ${error.message}!\n` +
64
+ 'This is unexpected, we apologize for the inconvenience!\n' +
65
+ 'Please send us a message and let us know at: support@codeless.qa\n\n' +
66
+ 'Thank you! 🙏');
67
+ process.exit(1);
68
+ return;
69
+ }
70
+ console.error(error);
71
+ });
65
72
  const success = await new Promise((resolve, reject) => {
66
73
  const reporterProcess = spawn('node', [require.resolve('tap-mocha-reporter'), reporter], {
67
74
  stdio: ['pipe', 'inherit', 'inherit']
68
75
  });
69
76
  ws.on('message', function message(data) {
70
- const msg = JSON.parse(data.toString());
71
- if (msg.type === 3) {
72
- return reporterProcess.stdin.write(msg.value.log);
73
- }
74
- if (msg.type === 2) {
75
- return resolve(msg.value.success);
77
+ try {
78
+ const msg = JSON.parse(data.toString());
79
+ if ('error' in msg && msg.error) {
80
+ return reject(new Error(msg.error));
81
+ }
82
+ if (msg.type === 3) {
83
+ return reporterProcess.stdin.write(msg.value.log);
84
+ }
85
+ if (msg.type === 2) {
86
+ return resolve(msg.value.success);
87
+ }
88
+ if (msg.type === 4) {
89
+ return reject(new Error(msg.value.error));
90
+ }
76
91
  }
77
- if (msg.type === 4) {
78
- return reject(new Error(msg.value.error));
92
+ catch (err) {
93
+ const error = err instanceof Error ? err : new Error('Unknown error');
94
+ return reject(new Error(`Uups! Something went wrong: ${error.message}`));
79
95
  }
80
96
  });
81
97
  });
@@ -0,0 +1,50 @@
1
+ import type { SecurityObject, ServerObject } from '@codeless.qa/contracts';
2
+ import type { ProjectProps } from './prompts.js';
3
+ type Spinner = {
4
+ stop: () => void;
5
+ };
6
+ export declare function getPresignUrl(token: string, specPath: string): Promise<{
7
+ url: string;
8
+ key: string;
9
+ fileName: string;
10
+ fileType: string;
11
+ fileUrl: string;
12
+ pollingJwt: string;
13
+ pollingUrl: string;
14
+ contentDisposition: string;
15
+ fields: {
16
+ key: string;
17
+ acl: string;
18
+ "Content-Type": string;
19
+ "Content-Disposition": string;
20
+ bucket: string;
21
+ "X-Amz-Algorithm": string;
22
+ "X-Amz-Credential": string;
23
+ "X-Amz-Date": string;
24
+ Policy: string;
25
+ "X-Amz-Signature": string;
26
+ };
27
+ customId?: any;
28
+ }>;
29
+ export declare function uploadSpecification(presignedUrl: {
30
+ url: string;
31
+ fields: Record<string, string>;
32
+ }, specString: string): Promise<void>;
33
+ export declare function waitForUploadFinishes(presignedUrl: {
34
+ pollingUrl: string;
35
+ pollingJwt: string;
36
+ }): Promise<string>;
37
+ export declare function createSpecification(token: string, projectProps: ProjectProps, file: string, spinner: Spinner): Promise<string>;
38
+ export declare function generateTests(token: string, id: string, spinner: Spinner, body: {
39
+ securityParams: SecurityObject[];
40
+ serverParam: ServerObject;
41
+ }): Promise<void>;
42
+ export declare function fetchProjectNames(token: string): Promise<string[]>;
43
+ export declare function validateAuthToken(token: string): Promise<{
44
+ valid: false;
45
+ } | {
46
+ valid: true;
47
+ email: string;
48
+ }>;
49
+ export {};
50
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,134 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs/promises';
3
+ import { outro } from '@clack/prompts';
4
+ import { getAuthenticatedClient } from '@codeless.qa/contracts/client';
5
+ export async function getPresignUrl(token, specPath) {
6
+ const client = getAuthenticatedClient(token);
7
+ const stat = await fs.stat(specPath);
8
+ const presigned = await client.specification.upload({
9
+ query: { actionType: 'upload', slug: 'openAPISpecUploader' },
10
+ body: {
11
+ files: [{
12
+ name: path.basename(specPath),
13
+ size: stat.size,
14
+ type: 'application/json'
15
+ }]
16
+ }
17
+ });
18
+ if (presigned.status !== 200) {
19
+ const error = typeof presigned.body === 'object' && presigned.body && 'error' in presigned.body && presigned.body.error instanceof Error
20
+ ? presigned.body.error
21
+ : new Error('Unknown error');
22
+ throw error;
23
+ }
24
+ return presigned.body[0];
25
+ }
26
+ export async function uploadSpecification(presignedUrl, specString) {
27
+ const formData = new FormData();
28
+ for (const [key, value] of Object.entries(presignedUrl.fields)) {
29
+ formData.append(key, value);
30
+ }
31
+ formData.append('file', Buffer.from(specString));
32
+ const res = await fetch(presignedUrl.url, {
33
+ method: 'POST',
34
+ body: formData,
35
+ });
36
+ if (res.status !== 204) {
37
+ const error = typeof res.body === 'object' && res.body && 'error' in res.body && res.body.error instanceof Error
38
+ ? res.body.error
39
+ : new Error('Unknown error');
40
+ throw error;
41
+ }
42
+ }
43
+ const UPLOAD_TIMEOUT = 1000 * 60;
44
+ export async function waitForUploadFinishes(presignedUrl) {
45
+ const start = Date.now();
46
+ let finalKey;
47
+ while (true) {
48
+ const waitRes = await fetch(presignedUrl.pollingUrl, {
49
+ headers: {
50
+ authorization: presignedUrl.pollingJwt
51
+ }
52
+ });
53
+ if (waitRes.status !== 200) {
54
+ const error = typeof waitRes.body === 'object' && waitRes.body && 'error' in waitRes.body && waitRes.body.error instanceof Error
55
+ ? waitRes.body.error
56
+ : new Error('Unknown error');
57
+ throw error;
58
+ }
59
+ const body = await waitRes.json();
60
+ if (body.status === 'done') {
61
+ finalKey = body.callbackData.key;
62
+ break;
63
+ }
64
+ if (Date.now() - start > UPLOAD_TIMEOUT) {
65
+ outro(`Timeout after ${UPLOAD_TIMEOUT / 1000} seconds!`);
66
+ process.exit(0);
67
+ }
68
+ await new Promise((resolve) => setTimeout(resolve, 500));
69
+ }
70
+ if (!finalKey) {
71
+ throw new Error('Upload failed!');
72
+ }
73
+ return finalKey;
74
+ }
75
+ export async function createSpecification(token, projectProps, file, spinner) {
76
+ const client = getAuthenticatedClient(token);
77
+ const resSpecCreation = await client.specifications.create({
78
+ body: {
79
+ ...projectProps,
80
+ file
81
+ }
82
+ });
83
+ if (resSpecCreation.status !== 201) {
84
+ spinner.stop();
85
+ const error = typeof resSpecCreation.body === 'object' && resSpecCreation.body && 'error' in resSpecCreation.body && resSpecCreation.body.error instanceof Error
86
+ ? resSpecCreation.body.error
87
+ : new Error('Unknown error');
88
+ outro(error.message);
89
+ process.exit(0);
90
+ }
91
+ return resSpecCreation.body.data.id;
92
+ }
93
+ export async function generateTests(token, id, spinner, body) {
94
+ const client = getAuthenticatedClient(token);
95
+ const resTests = await client.specification.generate({
96
+ params: { id },
97
+ body: {
98
+ securityObjects: body.securityParams,
99
+ server: body.serverParam
100
+ }
101
+ });
102
+ if (resTests.status !== 200 || 'error' in resTests.body) {
103
+ spinner.stop();
104
+ const error = typeof resTests.body === 'object' && resTests.body && 'error' in resTests.body
105
+ ? resTests.body.error instanceof Error
106
+ ? resTests.body.error
107
+ : new Error(resTests.body.error)
108
+ : new Error('Unknown error');
109
+ outro(error.message);
110
+ process.exit(0);
111
+ }
112
+ }
113
+ export async function fetchProjectNames(token) {
114
+ const client = getAuthenticatedClient(token);
115
+ const projectNames = [];
116
+ try {
117
+ const res = await client.specifications.get();
118
+ if (res.status === 200) {
119
+ projectNames.push(...res.body.data.map((spec) => spec.name));
120
+ }
121
+ }
122
+ catch {
123
+ // noop
124
+ }
125
+ return projectNames;
126
+ }
127
+ export async function validateAuthToken(token) {
128
+ const client = getAuthenticatedClient(token);
129
+ const res = await client.auth.validatingAccessToken();
130
+ if (res.status !== 200) {
131
+ return { valid: false };
132
+ }
133
+ return res.body;
134
+ }
@@ -0,0 +1,18 @@
1
+ import { type SecurityObject, ServerObject } from '@codeless.qa/contracts';
2
+ import { type OpenAPIV3 } from 'openapi-types';
3
+ export declare function askTestingType(): Promise<string>;
4
+ export declare function askSpecLocation(): Promise<{
5
+ spec: OpenAPIV3.Document<{}>;
6
+ specPath: string;
7
+ specString: string;
8
+ }>;
9
+ export interface ProjectProps {
10
+ name: string;
11
+ description: string;
12
+ version: string;
13
+ }
14
+ export declare function askProjectDetails(existingProjectNames: string[], spec: OpenAPIV3.Document): Promise<ProjectProps>;
15
+ export declare function askSecurityParams(spec: OpenAPIV3.Document): Promise<SecurityObject[]>;
16
+ export declare function askServerParams(spec: OpenAPIV3.Document): Promise<ServerObject>;
17
+ export declare function askForUserAuth(): Promise<string>;
18
+ //# sourceMappingURL=prompts.d.ts.map
@@ -0,0 +1,199 @@
1
+ import fs from 'node:fs';
2
+ import { TestParameterType } from '@codeless.qa/contracts';
3
+ import { select, text, confirm, outro, isCancel } from '@clack/prompts';
4
+ import { handler as loginFlow } from '../login.js';
5
+ export async function askTestingType() {
6
+ const answerTestingType = await select({
7
+ message: 'What type of testing you would like to do?',
8
+ options: [
9
+ { value: 'api', label: 'API Testing' },
10
+ { value: 'ui', label: 'Function UI Testing in a web browser', hint: 'not yet supported' },
11
+ ]
12
+ });
13
+ if (isCancel(answerTestingType)) {
14
+ outro('Bye!');
15
+ process.exit(0);
16
+ }
17
+ return answerTestingType;
18
+ }
19
+ export async function askSpecLocation() {
20
+ const specPath = await text({
21
+ message: 'Please provide an absolute path to your OpenAPI specification or Postman collection!',
22
+ validate: (path) => {
23
+ try {
24
+ fs.accessSync(path);
25
+ }
26
+ catch {
27
+ return 'Path does not exist';
28
+ }
29
+ }
30
+ });
31
+ if (isCancel(specPath) || typeof specPath !== 'string') {
32
+ outro('Bye!');
33
+ process.exit(0);
34
+ }
35
+ try {
36
+ const specString = fs.readFileSync(specPath, 'utf8');
37
+ const spec = JSON.parse(specString);
38
+ return { spec, specPath, specString };
39
+ }
40
+ catch (err) {
41
+ const error = err instanceof Error ? err : new Error('Unknown error');
42
+ outro(`Error: ${error.message}`);
43
+ process.exit(0);
44
+ }
45
+ throw new Error('I should never reach here');
46
+ }
47
+ const PROJECT_PROPS = {
48
+ name: 'What is the name of your project?',
49
+ description: 'What is the description of your project?',
50
+ version: 'What is the version of your API specification?',
51
+ };
52
+ export async function askProjectDetails(existingProjectNames, spec) {
53
+ const projectProps = {};
54
+ for (const [key, message] of Object.entries(PROJECT_PROPS)) {
55
+ const opts = {
56
+ message,
57
+ initialValue: spec.info[key] || spec.info.title,
58
+ };
59
+ if (key === 'name') {
60
+ opts.validate = (value) => existingProjectNames.includes(value)
61
+ ? `Project naem "${value}" already exists`
62
+ : undefined;
63
+ }
64
+ const value = await text(opts);
65
+ if (isCancel(value)) {
66
+ outro('Bye!');
67
+ process.exit(0);
68
+ }
69
+ projectProps[key] = value;
70
+ }
71
+ return projectProps;
72
+ }
73
+ export async function askSecurityParams(spec) {
74
+ if (!spec.components ||
75
+ !spec.components.securitySchemes ||
76
+ (Array.isArray(spec.components.securitySchemes) &&
77
+ spec.components.securitySchemes.length === 0)) {
78
+ return [];
79
+ }
80
+ const securitySchemes = new Set(Object.values(spec.components.securitySchemes).filter((schema) => 'type' in schema));
81
+ const securityObjects = [];
82
+ for (const secScheme of securitySchemes) {
83
+ const isBasicAuth = secScheme.type === 'http' && secScheme.scheme === 'basic';
84
+ const isJWTAuth = secScheme.type === 'http' && secScheme.scheme === 'bearer' && secScheme.bearerFormat === 'JWT';
85
+ const message = isBasicAuth
86
+ ? 'Can you provide a username and password to access the API?'
87
+ : isJWTAuth
88
+ ? 'Can you provide an example JWT token to access the API?'
89
+ : secScheme.type === 'apiKey'
90
+ ? `Can you provide an example value for the "${secScheme.name}" ${secScheme.in} parameter?`
91
+ : undefined;
92
+ if (!message || 'in' in secScheme && secScheme.in === 'query') {
93
+ continue;
94
+ }
95
+ const value = await text({
96
+ message,
97
+ placeholder: '(leave empty to skip or press "s" to cancel and skip all)',
98
+ });
99
+ if (isCancel(value)) {
100
+ outro('Bye!');
101
+ process.exit(0);
102
+ }
103
+ if (value === 's') {
104
+ break;
105
+ }
106
+ if (!value) {
107
+ continue;
108
+ }
109
+ const scope = secScheme.in.slice(0, 1).toUpperCase() +
110
+ secScheme.in.slice(1);
111
+ securityObjects.push({
112
+ id: Math.random().toString(36).slice(2).toLowerCase(),
113
+ type: TestParameterType.Security,
114
+ payload: {
115
+ name: isBasicAuth || isJWTAuth
116
+ ? 'Authorization'
117
+ : secScheme.name,
118
+ value,
119
+ scope
120
+ }
121
+ });
122
+ }
123
+ return securityObjects;
124
+ }
125
+ async function askCustomServer() {
126
+ const customServerPrompt = await text({
127
+ message: 'What is the server url?',
128
+ placeholder: 'https://api.gigantic-server.com/v1',
129
+ });
130
+ if (isCancel(customServerPrompt)) {
131
+ outro('Bye!');
132
+ process.exit(0);
133
+ }
134
+ return customServerPrompt;
135
+ }
136
+ export async function askServerParams(spec) {
137
+ const CUSTOM_SERVER = 'custom';
138
+ if (!spec.servers || spec.servers.length === 0) {
139
+ const customServer = await askCustomServer();
140
+ return { url: customServer };
141
+ }
142
+ const server = await select({
143
+ message: 'Which server do you want to use?',
144
+ options: [
145
+ ...spec.servers.map((server, value) => ({
146
+ label: server.description || server.url,
147
+ value,
148
+ hint: server.description ? server.url : undefined
149
+ })),
150
+ {
151
+ label: 'Custom server url',
152
+ value: CUSTOM_SERVER
153
+ }
154
+ ]
155
+ });
156
+ if (isCancel(server)) {
157
+ outro('Bye!');
158
+ process.exit(0);
159
+ }
160
+ const serverVars = {};
161
+ if (typeof server === 'number' && spec.servers[server].variables) {
162
+ for (const [name, val] of Object.entries(spec.servers[server].variables)) {
163
+ const varPrompt = await text({
164
+ message: `What is the value for the "${name}" variable?`,
165
+ initialValue: val.default,
166
+ });
167
+ if (isCancel(varPrompt)) {
168
+ outro('Bye!');
169
+ process.exit(0);
170
+ }
171
+ serverVars[name] = varPrompt;
172
+ }
173
+ }
174
+ let customServerUrl;
175
+ if (typeof server === 'string' && server === CUSTOM_SERVER) {
176
+ customServerUrl = await askCustomServer();
177
+ }
178
+ const serverObject = {
179
+ url: typeof server === 'number'
180
+ ? spec.servers[server].url
181
+ : customServerUrl,
182
+ variables: serverVars
183
+ };
184
+ return serverObject;
185
+ }
186
+ export async function askForUserAuth() {
187
+ const runLoginWorkflow = await confirm({
188
+ message: 'It seems like you are not logged in. Would you like to login now?',
189
+ initialValue: true
190
+ });
191
+ if (isCancel(runLoginWorkflow) || !runLoginWorkflow) {
192
+ outro('Bye!');
193
+ process.exit(0);
194
+ }
195
+ console.log('');
196
+ const token = await loginFlow();
197
+ console.log('');
198
+ return token;
199
+ }
@@ -1,6 +1,6 @@
1
1
  export declare const pkg: any;
2
2
  export declare const CLI_EPILOGUE: string;
3
3
  export declare const PLATFORM_URL: string;
4
- export declare const WORKER_HOSTNAME: string;
4
+ export declare const WORKER_URL: string;
5
5
  export declare const TOKEN_PATH: string;
6
6
  //# sourceMappingURL=constants.d.ts.map
package/dist/constants.js CHANGED
@@ -3,7 +3,10 @@ import { homedir } from 'node:os';
3
3
  import { createRequire } from 'node:module';
4
4
  const require = createRequire(import.meta.url);
5
5
  export const pkg = require('../package.json');
6
- export const CLI_EPILOGUE = `Documentation: https://codeless.qa/docs/cli\n@wdio/cli (v${pkg.version})`;
6
+ export const CLI_EPILOGUE = `Documentation: https://codeless.qa/docs/cli
7
+ qa (v${pkg.version})
8
+ © 2024 CodelessQA, Inc.
9
+ `;
7
10
  export const PLATFORM_URL = 'https://codeless.qa' || 'http://localhost:4000';
8
- export const WORKER_HOSTNAME = 'worker.codeless.qa' || 'localhost:8080';
11
+ export const WORKER_URL = 'wss://worker.codeless.qa' || 'ws://localhost:8080';
9
12
  export const TOKEN_PATH = path.join(homedir(), '/.codeless-qa');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qa",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "author": "Christian Bromann <christian@codeless.qa>",
5
5
  "description": "Codeless QA CLI",
6
6
  "license": "Apache-2.0",
@@ -10,6 +10,7 @@
10
10
  },
11
11
  "keywords": [],
12
12
  "dependencies": {
13
+ "@clack/prompts": "^0.7.0",
13
14
  "@types/uuid": "^9.0.8",
14
15
  "@types/ws": "^8.5.10",
15
16
  "@types/yargs": "^17.0.32",
@@ -18,7 +19,7 @@
18
19
  "uuid": "^9.0.1",
19
20
  "ws": "^8.17.0",
20
21
  "yargs": "^17.7.2",
21
- "@codeless.qa/contracts": "0.0.2"
22
+ "@codeless.qa/contracts": "0.0.3"
22
23
  },
23
24
  "devDependencies": {
24
25
  "replace-in-files-cli": "^3.0.0",