@codeqlick/cli 0.1.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,17 +10,130 @@ npx @codeqlick/cli deploy dist --prod
10
10
 
11
11
  Every deployment gets its own address (`https://<project>--<id>.codeqlick.app`); `--prod` also
12
12
  publishes it at `https://<project>.codeqlick.app` and on your domains. `codeqlick rollback` goes
13
- back in a second.
14
-
15
- | Command | What it does |
16
- | ------------------------------------------- | -------------------------------------------- |
17
- | `login [--token <cqk_…>]` | Sign in through the browser, or save a token |
18
- | `logout` / `whoami` | Forget the token / your account and teams |
19
- | `init` | Link the folder to a project |
20
- | `deploy [folder] [--prod] [-m <text>]` | Upload the folder as a new deployment |
21
- | `deployments` / `promote <id>` / `rollback` | List, publish an earlier one, go back |
22
- | `domains [add\|check\|rm <domain>]` | The project's own domains |
23
- | `open` | Open the published site |
13
+ back in a second. A deployment is named by its id or short id (see `deployments`); `files`,
14
+ `diff` and `unlock` take `--json` to print the API's answer.
15
+
16
+ Going back to an older deployment (`rollback`, or `promote` of an older one) **locks**
17
+ production: builds from Git still run, but deploy as previews, so the bug you rolled back can't
18
+ return with the next push. `deploy --prod`, promoting a newer deployment or `codeqlick unlock`
19
+ (team admins) lifts the lock.
20
+
21
+ | Command | What it does |
22
+ | ------------------------------------------- | ----------------------------------------------------------------------- |
23
+ | `login [--token <cqk_…>]` | Sign in through the browser, or save a token |
24
+ | `logout` / `whoami` | Forget the token / your account and teams |
25
+ | `init` | Link the folder to a project |
26
+ | `deploy [folder] [--prod] [-m <text>]` | Upload the folder as a new deployment |
27
+ | `deployments` / `promote <id>` / `rollback` | List, publish an earlier one, go back |
28
+ | `unlock` | Let production builds go live again after a rollback |
29
+ | `files <id>` / `diff <id> [other]` | A deployment's files / compare it with production or another deployment |
30
+ | `download [id] [-o <file>] [--force]` | Save a deployment's files as a `tar.gz` |
31
+ | `domains [add\|check\|rm <domain>]` | The project's own domains |
32
+ | `monitors [pause\|resume <id\|name>]` | The team's monitors, or pause and resume one (`--team`) |
33
+ | `open` | Open the published site |
34
+
35
+ `download` saves the production deployment (or the one you name, by its short id) as
36
+ `<project>-<id>.tar.gz` in the current folder; unpack it with `tar -xzf`. It never overwrites a
37
+ file unless you pass `--force`, and a cut download leaves nothing behind. A team can download 10
38
+ deployments an hour.
39
+
40
+ Builds from Git (connect GitHub once in the console's Git tab):
41
+
42
+ | Command | What it does |
43
+ | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
44
+ | `git` / `git connect <owner/repo>` / `git disconnect` | The repository and build settings |
45
+ | `env` / `env add <KEY> [value]` / `env rm <KEY> [--branch]` | Variables (without a value: stdin or hidden prompt) |
46
+ | `env import <file> [--production] [--preview] [--overwrite]` | Add a `.env` file's variables, all or nothing |
47
+ | `hooks` / `hooks add <name> [--branch]` / `hooks rm <id or name>` | Deploy hooks: a secret URL a CMS calls to rebuild a branch |
48
+ | `builds` / `builds start [--branch] [--no-cache]` / `builds cancel <n>` | List, build now and follow (`--no-cache`: without the dependency cache), cancel |
49
+ | `logs [number] [-o <file>] [--force]` | A build's log, followed while it runs (`-o`: save the whole log to a file) |
50
+
51
+ `env add <KEY> --branch <name>` saves a variable only for previews of that Git branch (it implies
52
+ `--preview`): there it replaces the variable with the same name for every preview, and production
53
+ never gets it. `env rm <KEY> --branch <name>` deletes that one; `env` shows each variable's branch.
54
+ `env import` has no `--branch`: it saves variables for every build of the targets chosen.
55
+
56
+ `env import` reads dotenv syntax (`KEY=value`, `export `, quotes, `#` comments) and saves nothing
57
+ when a line is wrong, printing each line's problem; names that already exist are skipped unless
58
+ `--overwrite`. Values are never printed. `-` as the file reads it from standard input
59
+ (`some-secret-tool export | codeqlick env import -`).
60
+
61
+ `hooks add` prints the hook's URL once: paste it in the CMS's webhook (a `POST`, no body needed). Builds a hook queued show as `<branch> (hook <name>)` in `builds`.
62
+
63
+ With `git connect`'s default install and build commands (`npm ci`, `npm run build`), each build picks npm, pnpm or Yarn from the repository's lockfile; a `--install` or `--build` you set is used as it is.
64
+
65
+ `git connect` reads the repository (its `package.json`, `.nvmrc` or `.node-version`) and suggests
66
+ the build command, output folder and Node version for the framework it finds (Astro, Docusaurus,
67
+ Gatsby, Next.js, Nuxt, SvelteKit, Eleventy, Create React App, Vite). It prints what it found and
68
+ any notes, and uses the suggestion for each of `--build`, `--output` and `--node` you don't give.
69
+ A project already connected to that repository keeps its saved settings instead.
70
+
71
+ `logs --out` writes the whole kept log (at most 1 MB) instead of following it and, like `download`,
72
+ never overwrites a file unless you pass `--force`.
73
+
74
+ `builds start` and `logs` exit with 1 when the build fails, so CI can wait on a build.
75
+
76
+ Analytics and the key-value store:
77
+
78
+ | Command | What it does |
79
+ | ---------------------------------------------- | --------------------------------------------------- |
80
+ | `analytics [--period 24h\|7d\|30d\|90d\|365d]` | Visitors, page views, top pages, sources and events |
81
+ | `kv [ls] [prefix]` | The project's keys |
82
+ | `kv get <key>` / `kv rm <key>` | Read or delete a key |
83
+ | `kv set <key> <value> [--ttl <s>]` | Save JSON (or text); `-` reads standard input |
84
+ | `kv incr <key> [--by <n>]` | Add to a counter atomically |
85
+
86
+ Password protection (to show work in progress to a client without making it public):
87
+
88
+ | Command | What it does |
89
+ | ------------------------------------ | ------------------------------------------- |
90
+ | `protect` | Which addresses ask visitors for a password |
91
+ | `protect previews [--days 1\|7\|30]` | Ask for it on every deployment's address |
92
+ | `protect all [--days 1\|7\|30]` | Also on production and your domains |
93
+ | `protect off` | Every address is public again |
94
+ | `protect bypass` | Make (or replace) the bypass token |
95
+ | `protect bypass --revoke` | Remove the bypass token |
96
+
97
+ The password is asked twice without echo, or read from standard input when it isn't a terminal
98
+ (`echo "$PASSWORD" | codeqlick protect previews`); an empty answer keeps the current one, to
99
+ change only the mode or the days. `--days` is how long access lasts once it's entered. While a
100
+ printed address asks for the password, `deploy` and `builds` say so on standard error.
101
+
102
+ The bypass token lets automation (end-to-end tests in CI, link checkers, `curl`) reach protected
103
+ addresses without the password: send it in the `X-Codeqlick-Bypass` header. `protect bypass`
104
+ prints only the token on standard output, once, and everything else on standard error, so it pipes
105
+ into a CI secret (`codeqlick protect bypass | gh secret set CQ_BYPASS`). Making a new one replaces
106
+ the old, which stops working at once. `protect` shows whether one is set; `--json` prints the API's
107
+ answer (`{ token, prefix, createdAt }`, or `{}` with `--revoke`).
108
+
109
+ Redirects, rewrites and headers go in the same `codeqlick.json` as the project link:
110
+
111
+ ```json
112
+ {
113
+ "$schema": "https://api.codeqlick.com/v1/cloud/schema/codeqlick.json",
114
+ "cleanUrls": true,
115
+ "trailingSlash": false,
116
+ "redirects": [{ "source": "/old/:slug", "destination": "/blog/:slug", "status": 301 }],
117
+ "rewrites": [{ "source": "/app/*", "destination": "/app/index.html" }],
118
+ "headers": [{ "source": "/*", "headers": { "Cache-Control": "public, max-age=300" } }]
119
+ }
120
+ ```
121
+
122
+ `deploy` sends the `codeqlick.json` of the folder you run it in (not the deployed folder's), and
123
+ prints the API's problems one per line with their path if the file is refused. `codeqlick config
124
+ check` validates it against your team's plan without deploying (`--json` prints the API's
125
+ answer; exit 1 when there are problems). `init` only sets `team`, `project` and `dir`: every
126
+ other key stays as it was, and a file that isn't valid JSON is never overwritten.
127
+
128
+ `deploy --url-only` prints only the new deployment's URL, to chain it with `audit`:
129
+
130
+ ```yaml
131
+ - run: |
132
+ url=$(npx @codeqlick/cli deploy dist --url-only)
133
+ npx @codeqlick/cli audit "$url" --min-score 80
134
+ env:
135
+ CODEQLICK_TOKEN: ${{ secrets.CODEQLICK_TOKEN }}
136
+ ```
24
137
 
25
138
  In CI, set `CODEQLICK_TOKEN` (a token from the console) and keep `codeqlick.json` in the
26
139
  repository, or pass `--team` and `--project` (`CODEQLICK_TEAM`, `CODEQLICK_PROJECT`).
@@ -36,4 +149,6 @@ npm run build # dist/, what is published
36
149
  CODEQLICK_API_URL=http://localhost:4000/v1 node dist/cli.js whoami
37
150
  ```
38
151
 
39
- Publishing (`npm publish --access public`, from this folder) needs the `@codeqlick` scope on npm.
152
+ Releasing: bump `version` in `package.json` and `src/version.ts` (a test checks they match), merge, then push a tag `cli-v<version>` (`git tag cli-v0.1.1 && git push origin
153
+ cli-v0.1.1`). The workflow `CLI publish` publishes it with npm's Trusted Publishing (no token or
154
+ 2FA code; configured on npmjs.com for `.github/workflows/cli-publish.yml`).
package/dist/api.js CHANGED
@@ -1,14 +1,36 @@
1
1
  import { openAsBlob } from 'node:fs';
2
- /** A failed API call: the problem details' text and status. */
2
+ import { VERSION } from './version.js';
3
+ /** A failed API call: the problem details' text and status, and its field errors. */
3
4
  export class ApiError extends Error {
4
5
  status;
5
- constructor(status, message) {
6
+ /** The per-field problems of a 400 (`codeqlick.json`: the exact path of each). */
7
+ errors;
8
+ constructor(status, message, errors = []) {
6
9
  super(message);
7
10
  this.status = status;
11
+ this.errors = errors;
8
12
  }
9
13
  }
10
- const USER_AGENT = 'codeqlick-cli/0.1.0';
11
- /** The Cloud API (`/v1/cloud`), with the token when there is one. */
14
+ /** One line per problem, `path: message`, indented. */
15
+ export function formatConfigErrors(errors) {
16
+ return errors.map((e) => ` ${e.path ? `${e.path}: ` : ''}${e.message}`);
17
+ }
18
+ /** The text to print for a failed call: the reason, then the problems with their paths. */
19
+ export function formatApiError(error) {
20
+ if (error.errors.length === 0)
21
+ return error.message;
22
+ const lines = formatConfigErrors(error.errors);
23
+ // Without a `detail` the message is already the joined problems: don't say them twice.
24
+ const joined = error.errors.map((e) => `${e.path}: ${e.message}`).join('; ');
25
+ return error.message === joined ? lines.join('\n') : [error.message, ...lines].join('\n');
26
+ }
27
+ const USER_AGENT = `codeqlick-cli/${VERSION}`;
28
+ /** The API's problem details (architecture 4.4) as an ApiError. */
29
+ function problemError(status, data) {
30
+ const problem = (data ?? {});
31
+ const fields = problem.errors?.map((e) => `${e.path}: ${e.message}`).join('; ');
32
+ return new ApiError(status, problem.detail ?? fields ?? problem.title ?? `HTTP ${status}`, Array.isArray(problem.errors) ? problem.errors : []);
33
+ }
12
34
  export class Api {
13
35
  base;
14
36
  token;
@@ -17,12 +39,7 @@ export class Api {
17
39
  this.token = token;
18
40
  }
19
41
  async request(method, path, body) {
20
- const headers = {
21
- Accept: 'application/json',
22
- 'User-Agent': USER_AGENT,
23
- };
24
- if (this.token)
25
- headers.Authorization = `Bearer ${this.token}`;
42
+ const headers = this.headers('application/json');
26
43
  let payload;
27
44
  if (body instanceof FormData)
28
45
  payload = body;
@@ -47,13 +64,42 @@ export class Api {
47
64
  catch {
48
65
  // Not JSON.
49
66
  }
50
- if (!response.ok) {
51
- const problem = (data ?? {});
52
- const fields = problem.errors?.map((e) => `${e.path}: ${e.message}`).join('; ');
53
- throw new ApiError(response.status, problem.detail ?? fields ?? problem.title ?? `HTTP ${response.status}`);
54
- }
67
+ if (!response.ok)
68
+ throw problemError(response.status, data);
55
69
  return data;
56
70
  }
71
+ headers(accept) {
72
+ const headers = { Accept: accept, 'User-Agent': USER_AGENT };
73
+ if (this.token)
74
+ headers.Authorization = `Bearer ${this.token}`;
75
+ return headers;
76
+ }
77
+ /** A GET whose body is read as a stream (a download), or the API's problem when it fails. */
78
+ async stream(path, accept) {
79
+ let response;
80
+ try {
81
+ response = await fetch(`${this.base}${path}`, { headers: this.headers(accept) });
82
+ }
83
+ catch (error) {
84
+ throw new ApiError(0, `Can't reach ${this.base} (${error.message})`);
85
+ }
86
+ if (!response.ok || !response.body) {
87
+ const text = await response.text();
88
+ let data = undefined;
89
+ try {
90
+ data = text ? JSON.parse(text) : undefined;
91
+ }
92
+ catch {
93
+ // Not JSON.
94
+ }
95
+ throw problemError(response.status, data);
96
+ }
97
+ return response.body;
98
+ }
99
+ /** A deployment's files as a `tar.gz` stream (built by the API while it is read). */
100
+ archive = (project, deployment) => this.stream(`/cloud/projects/${project}/deployments/${deployment}/archive`, 'application/gzip, application/json');
101
+ /** A build's whole kept log as a text stream (the log download route). */
102
+ buildLog = (project, number) => this.stream(`/cloud/projects/${project}/builds/${number}/log`, 'text/plain, application/json');
57
103
  me = () => this.request('GET', '/cloud/me');
58
104
  projects = (team) => this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/projects`).then((r) => r.items);
59
105
  createProject = (team, name, slug) => this.request('POST', `/cloud/teams/${encodeURIComponent(team)}/projects`, {
@@ -62,10 +108,75 @@ export class Api {
62
108
  });
63
109
  deployments = (project, page = 1) => this.request('GET', `/cloud/projects/${project}/deployments?page=${page}&pageSize=50`);
64
110
  promote = (project, deployment) => this.request('POST', `/cloud/projects/${project}/deployments/${deployment}/promote`);
111
+ unlockProduction = (project) => this.request('POST', `/cloud/projects/${project}/production/unlock`);
112
+ files = (project, deployment) => this.request('GET', `/cloud/projects/${project}/deployments/${deployment}/files`);
113
+ compare = (project, deployment, other) => this.request('GET', `/cloud/projects/${project}/deployments/${deployment}/compare?with=${encodeURIComponent(other)}`);
65
114
  domains = (project) => this.request('GET', `/cloud/projects/${project}/domains`).then((r) => r.items);
66
115
  addDomain = (project, name) => this.request('POST', `/cloud/projects/${project}/domains`, { name });
67
116
  checkDomain = (project, id) => this.request('POST', `/cloud/projects/${project}/domains/${id}/check`);
68
117
  removeDomain = (project, id) => this.request('DELETE', `/cloud/projects/${project}/domains/${id}`);
118
+ protection = (project) => this.request('GET', `/cloud/projects/${project}/protection`);
119
+ setProtection = (project, settings) => this.request('PUT', `/cloud/projects/${project}/protection`, settings);
120
+ createBypass = (project) => this.request('POST', `/cloud/projects/${project}/protection/bypass`);
121
+ revokeBypass = (project) => this.request('DELETE', `/cloud/projects/${project}/protection/bypass`);
122
+ audit = (teamSlug, url, locale) => this.request('POST', '/cloud/audits', { teamSlug, url, locale });
123
+ teamGithub = (team) => this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/github`);
124
+ repos = (team, installationId) => this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/github/repos?installationId=${installationId}`).then((r) => r.items);
125
+ detect = (team, input) => {
126
+ const query = new URLSearchParams({
127
+ installationId: String(input.installationId),
128
+ repoId: String(input.repoId),
129
+ branch: input.branch,
130
+ rootDir: input.rootDir,
131
+ });
132
+ return this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/github/detect?${query.toString()}`);
133
+ };
134
+ git = (project) => this.request('GET', `/cloud/projects/${project}/git`);
135
+ setGit = (project, settings) => this.request('PUT', `/cloud/projects/${project}/git`, settings);
136
+ disconnectGit = (project) => this.request('DELETE', `/cloud/projects/${project}/git`);
137
+ env = (project) => this.request('GET', `/cloud/projects/${project}/env`).then((r) => r.items);
138
+ setEnv = (project, variable) => this.request('PUT', `/cloud/projects/${project}/env`, variable).then((r) => r.items);
139
+ importEnv = (project, input) => this.request('POST', `/cloud/projects/${project}/env/import`, input);
140
+ /** Deletes a variable: the one of `branch`, or the general one without it. */
141
+ deleteEnv = (project, key, branch) => this.request('DELETE', `/cloud/projects/${project}/env?key=${encodeURIComponent(key)}${branch ? `&branch=${encodeURIComponent(branch)}` : ''}`);
142
+ builds = (project, pageSize = 20) => this.request('GET', `/cloud/projects/${project}/builds?page=1&pageSize=${pageSize}`).then((r) => r.items);
143
+ build = (project, number, after = 0) => this.request('GET', `/cloud/projects/${project}/builds/${number}?after=${after}`);
144
+ startBuild = (project, branch, noCache) => this.request('POST', `/cloud/projects/${project}/builds`, {
145
+ ...(branch ? { branch } : {}),
146
+ ...(noCache ? { noCache: true } : {}),
147
+ });
148
+ cancelBuild = (project, number) => this.request('POST', `/cloud/projects/${project}/builds/${number}/cancel`);
149
+ hooks = (project) => this.request('GET', `/cloud/projects/${project}/hooks`).then((r) => r.items);
150
+ createHook = (project, name, branch) => this.request('POST', `/cloud/projects/${project}/hooks`, {
151
+ name,
152
+ ...(branch ? { branch } : {}),
153
+ });
154
+ deleteHook = (project, id) => this.request('DELETE', `/cloud/projects/${project}/hooks/${encodeURIComponent(id)}`);
155
+ analytics = (project, period) => this.request('GET', `/cloud/projects/${project}/analytics?period=${period}`);
156
+ kvList = (project, prefix, cursor) => {
157
+ const query = new URLSearchParams({ limit: '100' });
158
+ if (prefix)
159
+ query.set('prefix', prefix);
160
+ if (cursor)
161
+ query.set('cursor', cursor);
162
+ return this.request('GET', `/cloud/projects/${project}/kv?${query.toString()}`);
163
+ };
164
+ kvGet = (project, key) => this.request('GET', `/cloud/projects/${project}/kv/${encodeURIComponent(key)}`);
165
+ kvSet = (project, key, value, ttl) => this.request('PUT', `/cloud/projects/${project}/kv/${encodeURIComponent(key)}`, {
166
+ value,
167
+ ttl,
168
+ });
169
+ kvDelete = (project, key) => this.request('DELETE', `/cloud/projects/${project}/kv/${encodeURIComponent(key)}`);
170
+ kvIncr = (project, key, by) => this.request('POST', `/cloud/projects/${project}/kv/${encodeURIComponent(key)}/incr`, { by });
171
+ monitors = (team) => this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/monitors`);
172
+ setMonitorEnabled = (id, enabled) => this.request('PATCH', `/cloud/monitors/${encodeURIComponent(id)}`, { enabled });
173
+ checkConfig = (teamSlug, config) => {
174
+ // Multipart text fields (no file part), like the deployment upload.
175
+ const form = new FormData();
176
+ form.set('teamSlug', teamSlug);
177
+ form.set('config', config);
178
+ return this.request('POST', '/cloud/config/check', form);
179
+ };
69
180
  startDevice = (clientName, locale) => this.request('POST', `/cloud/cli/device?locale=${locale}`, { clientName });
70
181
  pollDevice = (deviceCode) => this.request('POST', '/cloud/cli/device/token', { deviceCode });
71
182
  async deploy(project, bundle, fields) {
@@ -77,6 +188,8 @@ export class Api {
77
188
  form.set('commit', fields.commit);
78
189
  if (fields.branch)
79
190
  form.set('branch', fields.branch.slice(0, 100));
191
+ if (fields.config !== undefined)
192
+ form.set('config', fields.config);
80
193
  form.set('bundle', await openAsBlob(bundle, { type: 'application/gzip' }), 'site.tar.gz');
81
194
  return this.request('POST', `/cloud/projects/${project}/deployments`, form);
82
195
  }