@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/dist/cli.js CHANGED
@@ -1,16 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFile, spawn } from 'node:child_process';
3
3
  import { realpathSync } from 'node:fs';
4
- import { mkdtemp, rm, stat } from 'node:fs/promises';
4
+ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
5
5
  import { hostname, tmpdir } from 'node:os';
6
- import { join, resolve } from 'node:path';
6
+ import { join, relative, resolve } from 'node:path';
7
7
  import { createInterface } from 'node:readline/promises';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { parseArgs, promisify } from 'node:util';
10
- import { Api, ApiError } from './api.js';
11
- import { DEFAULT_API, configPath, forgetConfig, readConfig, readProjectFile, saveConfig, writeProjectFile, PROJECT_FILE, } from './config.js';
10
+ import { Api, ApiError, formatApiError, formatConfigErrors, } from './api.js';
11
+ import { DEFAULT_API, ProjectFileError, configPath, forgetConfig, hasRules, parseProjectText, readConfig, readProjectFile, readProjectText, saveConfig, writeProjectFile, PROJECT_FILE, } from './config.js';
12
+ import { archivePath, downloadFailure, exists, logPath, saveArchive } from './download.js';
12
13
  import { collect, pack } from './pack.js';
13
- const VERSION = '0.1.0';
14
+ import { VERSION } from './version.js';
14
15
  const run = promisify(execFile);
15
16
  const tty = process.stdout.isTTY;
16
17
  const paint = (code) => (text) => (tty ? `\x1b[${code}m${text}\x1b[0m` : text);
@@ -32,12 +33,90 @@ Commands:
32
33
  deploy [folder] Upload a built folder as a new deployment
33
34
  --prod publish it (otherwise it's a preview)
34
35
  -m, --message <text> shown in the console
36
+ --url-only print only the deployment's URL (for scripts)
35
37
  deployments The project's deployments, newest first
36
- promote <id> Publish an earlier deployment (its short id)
38
+ promote <id> Publish an earlier deployment (its id or short id)
37
39
  rollback Publish the deployment before the current one
40
+ download [id] Save a deployment's files as <project>-<id>.tar.gz (production
41
+ by default); unpack it with tar -xzf
42
+ -o, --out <file> where to save it
43
+ --force overwrite an existing file
44
+ (this locks production: builds from Git deploy as previews)
45
+ unlock Let production builds go live again after a rollback (admins)
46
+ files <id> What a deployment contains: each file's size and path
47
+ diff <id> [other] Compare a deployment with production (or another deployment)
48
+ --json (files, diff, unlock) print the API's answer
38
49
  domains [add|check|rm <domain>] The project's own domains
50
+ audit <url> Run the website check (speed, mobile, Google, security)
51
+ --min-score <n> exit 1 below this score (0-100)
52
+ --fail-on <fail|warn> exit 1 when a check has that result or worse
53
+ --json print the report as JSON
54
+ config check Check this folder's ${PROJECT_FILE} (redirects, rewrites, headers)
55
+ --json print the API's answer
39
56
  open Open the published site
40
57
 
58
+ Builds from Git:
59
+ git The connected repository and build settings
60
+ git connect <owner/repo> Connect a repository (install the GitHub app in the console first);
61
+ build, output and Node are suggested from the repository unless given
62
+ (not when the project is already connected to that repository)
63
+ --branch <name> production branch (the repository's default)
64
+ --root <dir> --install <cmd> --build <cmd> --output <dir> --node <20|22|24>
65
+ git disconnect Stop building from Git
66
+ env Environment variables (names only: values can't be read back)
67
+ env add <KEY> [value] Save one (no value: read from stdin, or asked without echo)
68
+ --production --preview where it applies (both when neither is given)
69
+ --branch <name> only previews of that Git branch (implies --preview)
70
+ env import <file> Add the variables of a .env file ("-" reads stdin), all or nothing
71
+ --production --preview where they apply (both when neither is given)
72
+ --overwrite replace the ones that exist (otherwise they're skipped)
73
+ env rm <KEY> [--branch <name>] Delete one (the branch's, or the general one)
74
+ hooks Deploy hooks: secret URLs a CMS calls to rebuild a branch
75
+ hooks add <name> [--branch <name>] Make one (the production branch by default); its URL is shown once
76
+ hooks rm <id or name> Delete one: its URL stops working at once
77
+ builds The latest builds
78
+ builds start [--branch <name>] [--no-cache]
79
+ Build the branch's latest commit and follow the log;
80
+ --no-cache skips the dependency cache
81
+ builds cancel <number> Cancel a queued or running build
82
+ logs [number] A build's log (the latest by default), followed while it runs
83
+ -o, --out <file> save the whole log to a file instead (--force overwrites one)
84
+ --json (git, env, hooks, builds) print the API's answer
85
+
86
+ Monitors (the team's, no linked project needed; --team or CODEQLICK_TEAM):
87
+ monitors The team's monitors: state, time in it and last check
88
+ monitors pause <id|name> Stop checking one (no alerts); its id or exact name
89
+ monitors resume <id|name> Check it again (its state is UNKNOWN until the next check)
90
+ --json (monitors) print the API's answer
91
+
92
+ Analytics and key-value store:
93
+ analytics Visitors, page views, top pages and sources
94
+ --period <24h|7d|30d|90d|365d> (7d by default)
95
+ kv [ls] [prefix] The project's keys
96
+ kv get <key> A key's value (JSON)
97
+ kv set <key> <value> Save a value: JSON, or text when it isn't ("-" reads stdin)
98
+ --ttl <seconds> expire it
99
+ kv rm <key> Delete a key
100
+ kv incr <key> [--by <n>] Add to a counter atomically (starts at 0)
101
+ --json (analytics, kv) print the API's answer
102
+
103
+ Password protection:
104
+ protect Which addresses ask visitors for a password
105
+ protect previews|all Ask for it on the deployments' addresses, or on every one
106
+ --days <1|7|30> how long access lasts once it's entered
107
+ (the password is asked without echo, or read from stdin;
108
+ empty keeps the current one)
109
+ protect off Every address is public again
110
+ protect bypass Make (or replace) the project's bypass token for automation
111
+ (CI tests, link checkers): the token goes to standard output
112
+ once, the rest to standard error; send it as
113
+ X-Codeqlick-Bypass: <token>
114
+ --revoke remove the bypass token
115
+ --json (protect) print the API's answer
116
+
117
+ Redirects, rewrites and headers: add them to ${PROJECT_FILE} (cleanUrls, trailingSlash,
118
+ redirects, rewrites, headers); \`deploy\` sends them, \`config check\` validates them.
119
+
41
120
  Options:
42
121
  --team <slug> --project <slug> Override ${PROJECT_FILE} (or CODEQLICK_TEAM, CODEQLICK_PROJECT)
43
122
  -h, --help -v, --version
@@ -163,6 +242,10 @@ async function whoami() {
163
242
  }
164
243
  async function init() {
165
244
  const { api } = await signedIn();
245
+ // Fail before asking anything when the file can't be kept (it is never overwritten).
246
+ const existing = await readProjectText();
247
+ if (existing !== null && existing.trim() !== '')
248
+ parseProjectText(existing);
166
249
  const me = await api.me();
167
250
  if (me.teams.length === 0)
168
251
  throw new UsageError('Create a team first at https://cloud.codeqlick.com');
@@ -209,6 +292,10 @@ async function gitInfo() {
209
292
  async function deploy(folder, options) {
210
293
  const { api } = await signedIn();
211
294
  const file = await readProjectFile();
295
+ // The rules of the folder the command runs in (not of the deployed one); a file with only the
296
+ // link keys isn't sent, so it can't hide a ${PROJECT_FILE} inside the bundle.
297
+ const text = await readProjectText();
298
+ const config = text !== null && hasRules(text) ? text : undefined;
212
299
  const root = resolve(folder ?? file.dir ?? 'dist');
213
300
  if (!(await stat(root).catch(() => null))?.isDirectory()) {
214
301
  throw new UsageError(`${root} isn't a folder: build your site first, or pass the folder.`);
@@ -223,19 +310,29 @@ async function deploy(folder, options) {
223
310
  const bundle = join(work, 'site.tar.gz');
224
311
  const size = await pack(files, bundle);
225
312
  const total = files.reduce((sum, f) => sum + f.size, 0);
226
- console.log(`Uploading ${files.length} files (${bytes(total)}, ${bytes(size)} compressed) to ${bold(project.slug)}…`);
313
+ const quiet = options['url-only'] === true;
314
+ if (!quiet) {
315
+ console.log(`Uploading ${files.length} files (${bytes(total)}, ${bytes(size)} compressed) to ${bold(project.slug)}…`);
316
+ }
227
317
  const { commit, branch } = await gitInfo();
228
318
  const deployment = await api.deploy(project.id, bundle, {
229
319
  target: options.prod ? 'production' : 'preview',
230
320
  message: options.message,
231
321
  commit: commit && /^[0-9a-f]{4,40}$/i.test(commit) ? commit : undefined,
232
322
  branch,
323
+ config,
233
324
  });
325
+ if (quiet) {
326
+ console.log(deployment.url);
327
+ warnProtected(project.protection, { preview: true, production: false });
328
+ return;
329
+ }
234
330
  console.log(`${green('✓')} Deployment ${bold(deployment.shortId)}: ${deployment.url}`);
235
331
  if (deployment.isProduction)
236
332
  console.log(`${green('✓')} Published: ${bold(project.url)}`);
237
333
  else
238
334
  console.log(dim(` A preview. Publish it with: codeqlick promote ${deployment.shortId}`));
335
+ warnProtected(project.protection, { preview: true, production: deployment.isProduction });
239
336
  }
240
337
  finally {
241
338
  await rm(work, { recursive: true, force: true });
@@ -256,16 +353,24 @@ async function deployments(options) {
256
353
  console.log(`${bold(d.shortId)} ${tag} ${when} ${d.message ?? ''}`.trimEnd());
257
354
  }
258
355
  }
356
+ /** A deployment given by its id or short id, among the project's last 50. */
357
+ function findDeployment(list, id) {
358
+ const found = list.find((d) => d.shortId === id || d.id === id);
359
+ if (!found)
360
+ throw new UsageError(`No deployment "${id}" among the last 50.`);
361
+ return found;
362
+ }
259
363
  async function promote(id, options) {
260
364
  if (!id)
261
365
  throw new UsageError('Which deployment? `codeqlick promote <id>` (see `codeqlick deployments`).');
262
366
  const { api } = await signedIn();
263
367
  const project = await target(api, options);
264
- const found = (await allDeployments(api, project.id)).find((d) => d.shortId === id || d.id === id);
265
- if (!found)
266
- throw new UsageError(`No deployment "${id}" among the last 50.`);
267
- await api.promote(project.id, found.id);
368
+ const found = findDeployment(await allDeployments(api, project.id), id);
369
+ const updated = await api.promote(project.id, found.id);
268
370
  console.log(`${green('✓')} ${bold(found.shortId)} is published: ${project.url}`);
371
+ const note = lockNote(project, updated);
372
+ if (note)
373
+ console.log(dim(note));
269
374
  }
270
375
  async function rollback(options) {
271
376
  const { api } = await signedIn();
@@ -276,8 +381,141 @@ async function rollback(options) {
276
381
  const previous = older.find((d) => d.target === 'production') ?? older[0];
277
382
  if (!previous)
278
383
  throw new UsageError('There is no earlier deployment to go back to.');
279
- await api.promote(project.id, previous.id);
384
+ const updated = await api.promote(project.id, previous.id);
280
385
  console.log(`${green('✓')} Back to ${bold(previous.shortId)}: ${project.url}`);
386
+ const note = lockNote(project, updated);
387
+ if (note)
388
+ console.log(dim(note));
389
+ }
390
+ /** What `rollback` and `promote` add, from the project's lock before and after the call. */
391
+ export function lockNote(before, after) {
392
+ if (!after.productionLock)
393
+ return null;
394
+ return `Production is ${before.productionLock ? 'still' : 'now'} locked: builds from Git deploy as previews until you publish with \`codeqlick deploy --prod\`, promote a newer deployment, or run \`codeqlick unlock\`.`;
395
+ }
396
+ /** What `unlock` says, from whether the project was locked before the call. */
397
+ export function unlockMessage(wasLocked) {
398
+ return wasLocked
399
+ ? 'Production unlocked: the next production build goes live.'
400
+ : "Production wasn't locked.";
401
+ }
402
+ async function unlock(options) {
403
+ const { api } = await signedIn();
404
+ const project = await target(api, options);
405
+ let updated;
406
+ try {
407
+ updated = await api.unlockProduction(project.id);
408
+ }
409
+ catch (error) {
410
+ if (error instanceof ApiError && error.status === 403) {
411
+ throw new UsageError(`Only the team's admins can unlock production of ${project.slug}.`);
412
+ }
413
+ throw error;
414
+ }
415
+ if (options.json)
416
+ return console.log(JSON.stringify(updated, null, 2));
417
+ const wasLocked = Boolean(project.productionLock);
418
+ console.log(`${wasLocked ? green('✓') + ' ' : ''}${unlockMessage(wasLocked)}`);
419
+ }
420
+ async function download(id, options) {
421
+ const { api } = await signedIn();
422
+ const project = await target(api, options);
423
+ let found;
424
+ if (id) {
425
+ found = (await allDeployments(api, project.id)).find((d) => d.shortId === id || d.id === id);
426
+ if (!found)
427
+ throw new UsageError(`No deployment "${id}" among the last 50.`);
428
+ }
429
+ else {
430
+ found = project.production;
431
+ if (!found) {
432
+ throw new UsageError('The project has nothing published: pass a deployment (see `codeqlick deployments`).');
433
+ }
434
+ }
435
+ const file = archivePath(options.out, project.slug, found.shortId);
436
+ if (!options.force && (await exists(file))) {
437
+ throw new UsageError(`${file} already exists: pass --force to overwrite it.`);
438
+ }
439
+ const body = await api.archive(project.id, found.id);
440
+ let size;
441
+ try {
442
+ size = await saveArchive(body, file);
443
+ }
444
+ catch (error) {
445
+ throw downloadFailure(error, file);
446
+ }
447
+ const shown = relative(process.cwd(), file) || file;
448
+ console.log(`${green('✓')} ${bold(found.shortId)} saved to ${shown} (${bytes(size)})`);
449
+ console.log(dim(` Unpack it with: tar -xzf ${shown}`));
450
+ }
451
+ /** `size path` lines, sizes right-aligned, what the API left out (it lists 10,000), the total. */
452
+ export function filesLines(listing) {
453
+ if (listing.items.length === 0)
454
+ return ['No files.'];
455
+ const sizes = listing.items.map((f) => bytes(f.size));
456
+ const width = Math.max(...sizes.map((s) => s.length));
457
+ const more = listing.count - listing.items.length;
458
+ return [
459
+ ...listing.items.map((f, i) => `${sizes[i].padStart(width)} ${f.path}`),
460
+ ...(more > 0
461
+ ? [
462
+ `… ${more.toLocaleString('en-US')} more ${more === 1 ? 'file' : 'files'} not listed (first ${listing.items.length.toLocaleString('en-US')} shown)`,
463
+ ]
464
+ : []),
465
+ `${listing.count.toLocaleString('en-US')} ${listing.count === 1 ? 'file' : 'files'}, ${bytes(listing.totalBytes)}`,
466
+ ];
467
+ }
468
+ /** `+ path`, `- path` and `~ path (old → new)` lines, grouped, then the counts. */
469
+ export function diffLines(comparison) {
470
+ const { added, removed, changed, unchanged } = comparison;
471
+ return [
472
+ ...added.map((f) => `+ ${f.path}`),
473
+ ...removed.map((f) => `- ${f.path}`),
474
+ ...changed.map((f) => `~ ${f.path} (${bytes(f.previousSize)} → ${bytes(f.size)})`),
475
+ `${added.length} added, ${removed.length} removed, ${changed.length} changed, ${unchanged} unchanged`,
476
+ ];
477
+ }
478
+ /** Turns the API's 404 and 409 into messages that say what to do. */
479
+ function filesError(error, project, gone) {
480
+ if (error instanceof ApiError && error.status === 404)
481
+ throw new UsageError(gone);
482
+ if (error instanceof ApiError && error.status === 409) {
483
+ throw new UsageError(`${project.slug} has nothing published to compare with: pass another deployment.`);
484
+ }
485
+ throw error;
486
+ }
487
+ async function files(id, options) {
488
+ if (!id)
489
+ throw new UsageError('Which deployment? `codeqlick files <id>` (see `codeqlick deployments`).');
490
+ const { api } = await signedIn();
491
+ const project = await target(api, options);
492
+ const found = findDeployment(await allDeployments(api, project.id), id);
493
+ const listing = await api
494
+ .files(project.id, found.id)
495
+ .catch((error) => filesError(error, project, `The files of ${found.shortId} aren't available: it was deleted, or they're gone.`));
496
+ if (options.json)
497
+ return console.log(JSON.stringify(listing, null, 2));
498
+ for (const line of filesLines(listing))
499
+ console.log(line);
500
+ }
501
+ async function diff(id, other, options) {
502
+ if (!id)
503
+ throw new UsageError('Which deployment? `codeqlick diff <id> [other]` (see `codeqlick deployments`).');
504
+ const { api } = await signedIn();
505
+ const project = await target(api, options);
506
+ const list = await allDeployments(api, project.id);
507
+ const found = findDeployment(list, id);
508
+ const against = !other || other === 'production' ? null : findDeployment(list, other);
509
+ const comparison = await api
510
+ .compare(project.id, found.id, against?.id ?? 'production')
511
+ .catch((error) => filesError(error, project, `The files of ${found.shortId} or of ${against ? against.shortId : 'the production deployment'} aren't available: one of them was deleted, or its files are gone.`));
512
+ if (options.json)
513
+ return console.log(JSON.stringify(comparison, null, 2));
514
+ const withShort = against?.shortId ?? list.find((d) => d.id === comparison.withId)?.shortId ?? comparison.withId;
515
+ console.log(dim(`${found.shortId} (${bytes(comparison.totalBytes)}) against ${against ? '' : 'production, '}${withShort} (${bytes(comparison.withTotalBytes)})`));
516
+ const paintLine = (line) => line.startsWith('+ ') ? green(line) : line.startsWith('- ') ? pink(line) : line;
517
+ for (const line of diffLines(comparison))
518
+ console.log(paintLine(line));
281
519
  }
282
520
  async function domains(action, name, options) {
283
521
  const { api } = await signedIn();
@@ -317,13 +555,935 @@ async function domains(action, name, options) {
317
555
  else
318
556
  throw new UsageError(`Unknown action "${action}": add, check or rm.`);
319
557
  }
558
+ /** The team a command acts for: the flag, the environment, codeqlick.json, or the only one. */
559
+ async function teamOf(api, options) {
560
+ const file = await readProjectFile();
561
+ const team = options.team ?? process.env.CODEQLICK_TEAM ?? file.team;
562
+ if (team)
563
+ return team;
564
+ const teams = (await api.me()).teams;
565
+ if (teams.length === 1)
566
+ return teams[0].slug;
567
+ throw new UsageError('Which team? Pass --team <slug> (or set CODEQLICK_TEAM).');
568
+ }
569
+ async function audit(url, options) {
570
+ if (!url || !/^https?:\/\//i.test(url))
571
+ throw new UsageError('Which address? codeqlick audit https://…');
572
+ const minScore = options['min-score'] === undefined ? null : Number(options['min-score']);
573
+ if (minScore !== null && !(Number.isInteger(minScore) && minScore >= 0 && minScore <= 100)) {
574
+ throw new UsageError('--min-score must be a whole number from 0 to 100.');
575
+ }
576
+ const failOn = options['fail-on'];
577
+ if (failOn !== undefined && failOn !== 'fail' && failOn !== 'warn') {
578
+ throw new UsageError('--fail-on must be fail or warn.');
579
+ }
580
+ const { api } = await signedIn();
581
+ const locale = (process.env.LANG ?? '').startsWith('es') ? 'es' : 'en';
582
+ const report = await api.audit(await teamOf(api, options), url, locale);
583
+ const checks = report.categories.flatMap((c) => c.checks);
584
+ const failed = (minScore !== null && report.score < minScore) ||
585
+ (failOn === 'fail' && checks.some((c) => c.status === 'fail')) ||
586
+ (failOn === 'warn' && checks.some((c) => c.status !== 'pass'));
587
+ if (options.json) {
588
+ console.log(JSON.stringify(report, null, 2));
589
+ return failed ? 1 : 0;
590
+ }
591
+ const paintScore = report.score >= 90 ? green : report.score >= 50 ? (s) => s : pink;
592
+ console.log(`${bold(paintScore(`${report.score}/100`))} ${report.finalUrl}`);
593
+ console.log(dim(report.categories.map((c) => `${c.name} ${c.score}`).join(' · ')));
594
+ for (const check of checks.filter((c) => c.status !== 'pass')) {
595
+ console.log(`${check.status === 'fail' ? pink('✗') : '!'} ${check.title}`);
596
+ console.log(dim(` ${check.advice}`));
597
+ }
598
+ if (failed) {
599
+ console.error(minScore !== null && report.score < minScore
600
+ ? `The score ${report.score} is under ${minScore}.`
601
+ : `There are checks that ${failOn === 'warn' ? "didn't pass" : 'failed'}.`);
602
+ }
603
+ return failed ? 1 : 0;
604
+ }
605
+ /** `config check`: validates the folder's codeqlick.json with the API; exit 1 on any problem. */
606
+ async function configCommand(action, options) {
607
+ if (action !== 'check')
608
+ throw new UsageError('Usage: codeqlick config check [--json]');
609
+ const { api } = await signedIn();
610
+ const text = await readProjectText();
611
+ if (text === null)
612
+ throw new UsageError(`There's no ${PROJECT_FILE} in this folder.`);
613
+ const result = await api.checkConfig(await teamOf(api, options), text);
614
+ if (options.json) {
615
+ console.log(JSON.stringify(result, null, 2));
616
+ return result.ok ? 0 : 1;
617
+ }
618
+ console.log(configCheckText(result));
619
+ return result.ok ? 0 : 1;
620
+ }
621
+ /** The lines `config check` prints: the summary, or each problem with its path. */
622
+ export function configCheckText(result) {
623
+ if (!result.ok) {
624
+ const count = result.errors.length;
625
+ return [
626
+ `${PROJECT_FILE} has ${count} ${count === 1 ? 'problem' : 'problems'}:`,
627
+ ...formatConfigErrors(result.errors),
628
+ ].join('\n');
629
+ }
630
+ const { redirects, rewrites, headers, cleanUrls, trailingSlash } = result.summary;
631
+ const parts = [
632
+ `${redirects} ${redirects === 1 ? 'redirect' : 'redirects'}`,
633
+ `${rewrites} ${rewrites === 1 ? 'rewrite' : 'rewrites'}`,
634
+ `${headers} header ${headers === 1 ? 'rule' : 'rules'}`,
635
+ ];
636
+ if (cleanUrls === false)
637
+ parts.push('cleanUrls off');
638
+ if (trailingSlash !== null && trailingSlash !== undefined)
639
+ parts.push(`trailingSlash ${trailingSlash}`);
640
+ return `${green('✓')} ok: ${parts.join(', ')}`;
641
+ }
320
642
  async function openSite(options) {
321
643
  const { api } = await signedIn();
322
644
  const project = await target(api, options);
323
645
  console.log(project.url);
324
646
  openBrowser(project.url);
325
647
  }
648
+ // ── Builds from Git ───────────────────────────────────────────────────────────────────────────
649
+ const CONSOLE = 'https://cloud.codeqlick.com';
650
+ const ENV_KEY = /^[A-Z_][A-Z0-9_]{0,63}$/;
651
+ function showGit(settings) {
652
+ if (!settings.repo) {
653
+ console.log(dim('Not connected to a repository: codeqlick git connect <owner/repo>'));
654
+ return;
655
+ }
656
+ console.log(`${bold(settings.repo)} ${dim(`production: ${settings.branch}`)}`);
657
+ const rows = [
658
+ ['root', settings.rootDir || '.'],
659
+ ['install', settings.installCommand],
660
+ ['build', settings.buildCommand],
661
+ ['output', settings.outputDir],
662
+ ['node', settings.nodeVersion],
663
+ [
664
+ 'previews',
665
+ `${settings.buildBranches ? 'branches' : ''}${settings.buildBranches && settings.buildPullRequests ? ', ' : ''}${settings.buildPullRequests ? 'pull requests' : ''}` ||
666
+ 'off',
667
+ ],
668
+ ];
669
+ if (settings.previewChecks)
670
+ rows.push(['check previews', 'website check on each pull request']);
671
+ for (const [name, value] of rows)
672
+ console.log(` ${dim(name.padEnd(16))}${value}`);
673
+ }
674
+ const FRAMEWORKS = {
675
+ astro: 'Astro',
676
+ docusaurus: 'Docusaurus',
677
+ gatsby: 'Gatsby',
678
+ next: 'Next.js',
679
+ nuxt: 'Nuxt',
680
+ sveltekit: 'SvelteKit',
681
+ eleventy: 'Eleventy',
682
+ cra: 'Create React App',
683
+ vite: 'Vite',
684
+ };
685
+ const DETECT_NOTES = {
686
+ 'next-not-static': "Next.js needs output: 'export' in next.config to be served as static files.",
687
+ 'sveltekit-no-static-adapter': 'SvelteKit needs @sveltejs/adapter-static.',
688
+ 'node-unsupported': "The repository asks for a Node version Cloud doesn't offer: check --node.",
689
+ 'no-package-json': 'No package.json in this folder: pick the right root folder (--root), or use codeqlick deploy for a site that needs no build.',
690
+ };
691
+ /** The build settings to send: each option given wins over the suggestion (architecture 4.13). */
692
+ export function withSuggestion(options, suggestion) {
693
+ return {
694
+ buildCommand: options.build ?? suggestion?.buildCommand,
695
+ outputDir: options.output ?? suggestion?.outputDir,
696
+ nodeVersion: options.node ?? suggestion?.nodeVersion,
697
+ };
698
+ }
699
+ /**
700
+ * Whether a suggestion may fill the options not given: only while the project isn't connected, or
701
+ * when it moves to another repository. A project's saved settings for its own repository stay.
702
+ */
703
+ export function suggestionApplies(current, repoId) {
704
+ return current.repoId === null || current.repoId !== repoId;
705
+ }
706
+ /** The warning when the suggestion can't be had: the API then keeps what the project has. */
707
+ export function detectFailed(current, error) {
708
+ const kept = current.repoId === null ? 'keeping the defaults' : 'keeping the current settings';
709
+ return `Couldn't suggest build settings (${error.message}): ${kept}.`;
710
+ }
711
+ /** What the suggestion found, then its notes, one line each. */
712
+ export function detectSummary(suggestion) {
713
+ const from = suggestion.nodeFrom === 'engines' ? 'engines in package.json' : suggestion.nodeFrom;
714
+ const settings = `build "${suggestion.buildCommand}", output ${suggestion.outputDir || '.'}, Node ${suggestion.nodeVersion}${from ? ` (${from})` : ''}`;
715
+ const found = suggestion.framework
716
+ ? `Detected ${FRAMEWORKS[suggestion.framework] ?? suggestion.framework} (package.json): ${settings}`
717
+ : `No framework detected: ${settings}`;
718
+ return [found, ...suggestion.notes.map((note) => `Note: ${DETECT_NOTES[note] ?? note}`)];
719
+ }
720
+ async function git(action, name, options) {
721
+ const { api } = await signedIn();
722
+ const project = await target(api, options);
723
+ if (!action || action === 'status') {
724
+ const settings = await api.git(project.id);
725
+ if (options.json)
726
+ console.log(JSON.stringify(settings, null, 2));
727
+ else
728
+ showGit(settings);
729
+ return;
730
+ }
731
+ if (action === 'disconnect') {
732
+ await api.disconnectGit(project.id);
733
+ console.log(`${green('✓')} ${bold(project.slug)} no longer builds from Git.`);
734
+ return;
735
+ }
736
+ if (action !== 'connect')
737
+ throw new UsageError(`Unknown action "${action}": connect or disconnect.`);
738
+ if (!name || !/^[\w.-]+\/[\w.-]+$/.test(name)) {
739
+ throw new UsageError('Which repository? codeqlick git connect <owner/repo>');
740
+ }
741
+ const team = project.team.slug;
742
+ const github = await api.teamGithub(team);
743
+ if (!github.configured)
744
+ throw new UsageError("Builds from Git aren't available yet.");
745
+ const consoleUrl = `${CONSOLE}/en/console/${team}/${project.slug}?tab=git`;
746
+ const installations = github.installations.filter((i) => !i.suspended);
747
+ if (installations.length === 0) {
748
+ throw new UsageError(`Install the Codeqlick Cloud app on GitHub first (it needs the browser): ${consoleUrl}`);
749
+ }
750
+ const wanted = name.toLowerCase();
751
+ for (const installation of installations) {
752
+ const repo = (await api.repos(team, installation.id)).find((r) => r.fullName.toLowerCase() === wanted);
753
+ if (!repo)
754
+ continue;
755
+ const branch = options.branch ?? repo.defaultBranch;
756
+ const current = await api.git(project.id);
757
+ let suggestion = null;
758
+ const missing = options.build === undefined || options.output === undefined || options.node === undefined;
759
+ if (missing && suggestionApplies(current, repo.id)) {
760
+ try {
761
+ suggestion = await api.detect(team, {
762
+ installationId: installation.id,
763
+ repoId: repo.id,
764
+ branch,
765
+ // The API keeps the saved root folder when --root isn't given, so detect in that one.
766
+ rootDir: options.root ?? current.rootDir,
767
+ });
768
+ for (const line of detectSummary(suggestion))
769
+ console.log(line);
770
+ }
771
+ catch (error) {
772
+ console.error(detectFailed(current, error));
773
+ }
774
+ }
775
+ const settings = await api.setGit(project.id, {
776
+ installationId: installation.id,
777
+ repoId: repo.id,
778
+ branch,
779
+ rootDir: options.root,
780
+ installCommand: options.install,
781
+ ...withSuggestion(options, suggestion),
782
+ });
783
+ console.log(`${green('✓')} ${bold(project.slug)} builds from ${bold(repo.fullName)}.`);
784
+ showGit(settings);
785
+ console.log(dim(` Pushes to ${settings.branch} are published; push now, or: codeqlick builds start`));
786
+ return;
787
+ }
788
+ throw new UsageError(`The app can't see ${name}: add it to the app's repositories on GitHub (${consoleUrl}).`);
789
+ }
790
+ async function readStdin() {
791
+ const chunks = [];
792
+ for await (const chunk of process.stdin)
793
+ chunks.push(chunk);
794
+ return Buffer.concat(chunks)
795
+ .toString('utf8')
796
+ .replace(/\r?\n$/, '');
797
+ }
798
+ /** Asks for a value without showing what is typed. */
799
+ async function askSecret(question) {
800
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
801
+ process.stdout.write(question);
802
+ rl._writeToOutput = () => undefined;
803
+ try {
804
+ return await rl.question('');
805
+ }
806
+ finally {
807
+ rl.close();
808
+ process.stdout.write('\n');
809
+ }
810
+ }
811
+ async function env(action, key, value, options) {
812
+ const { api } = await signedIn();
813
+ const project = await target(api, options);
814
+ const show = (items) => {
815
+ if (options.json)
816
+ return console.log(JSON.stringify(items, null, 2));
817
+ if (items.length === 0)
818
+ console.log(dim('No variables yet: codeqlick env add <KEY>'));
819
+ for (const v of items) {
820
+ const where = [v.production && 'production', v.preview && 'preview'].filter(Boolean);
821
+ const branch = v.branch ? ` branch ${v.branch}` : '';
822
+ const when = dim(new Date(v.updatedAt).toLocaleString());
823
+ console.log(`${bold(v.key)} ${where.join(', ')}${branch} ${when}`);
824
+ }
825
+ };
826
+ if (!action || action === 'ls' || action === 'list')
827
+ return show(await api.env(project.id));
828
+ if (action === 'import')
829
+ return importEnvFile(api, project.id, key, options);
830
+ if (!key || !ENV_KEY.test(key)) {
831
+ throw new UsageError(`Which variable? codeqlick env ${action} <KEY> (upper-case letters, digits, _)`);
832
+ }
833
+ const branch = envBranch(options);
834
+ if (action === 'rm' || action === 'remove') {
835
+ await api.deleteEnv(project.id, key, branch);
836
+ console.log(`${green('✓')} Deleted ${key}${branch ? ` (branch ${branch})` : ''}`);
837
+ return;
838
+ }
839
+ if (action !== 'add' && action !== 'set')
840
+ throw new UsageError(`Unknown action "${action}": add or rm.`);
841
+ const targets = envTargets(options);
842
+ const secret = value ??
843
+ (process.stdin.isTTY ? await askSecret(`Value of ${key} (hidden): `) : await readStdin());
844
+ if (secret.length > 4096)
845
+ throw new UsageError('Values are at most 4 KB.');
846
+ const items = await api.setEnv(project.id, { key, value: secret, ...targets });
847
+ if (options.json)
848
+ return show(items);
849
+ const where = targets.branch ? ` for previews of ${targets.branch}` : '';
850
+ console.log(`${green('✓')} Saved ${bold(key)}${where}: it applies from the next build.`);
851
+ }
852
+ /** `--branch` of `env add` / `env rm`, trimmed; undefined without it. */
853
+ export function envBranch(options) {
854
+ if (options.branch === undefined)
855
+ return undefined;
856
+ const branch = options.branch.trim();
857
+ if (!branch || /\s/.test(branch)) {
858
+ throw new UsageError('--branch needs a Git branch name, e.g. --branch staging');
859
+ }
860
+ return branch;
861
+ }
862
+ /**
863
+ * Where `env add` saves a variable: both targets when neither flag is given; with `--branch`,
864
+ * previews of that branch only (architecture 4.13).
865
+ */
866
+ export function envTargets(options) {
867
+ const branch = envBranch(options);
868
+ if (branch) {
869
+ if (options.production) {
870
+ throw new UsageError('A branch variable is for previews only: drop --production.');
871
+ }
872
+ return { production: false, preview: true, branch };
873
+ }
874
+ const both = !options.production && !options.preview;
875
+ return {
876
+ production: both || options.production === true,
877
+ preview: both || options.preview === true,
878
+ };
879
+ }
880
+ /** A refused import's problems, one line each (the API never sends values back). */
881
+ export function importErrorLines(errors) {
882
+ return errors.map((e) => {
883
+ const where = e.line === undefined ? '' : `line ${e.line}: `;
884
+ const name = e.key ? `${e.key}: ` : '';
885
+ return ` ${where}${name}${e.message}`;
886
+ });
887
+ }
888
+ /** The most a `.env` file imported at once may weigh. */
889
+ const ENV_IMPORT_MAX_BYTES = 256 * 1024;
890
+ async function importEnvFile(api, projectId, file, options) {
891
+ if (!file) {
892
+ throw new UsageError('Which file? codeqlick env import <file> [--production] [--preview] [--overwrite]');
893
+ }
894
+ if (file === '-' && process.stdin.isTTY) {
895
+ throw new UsageError('"-" reads the file from standard input: pipe it in (codeqlick env import - < .env).');
896
+ }
897
+ let content;
898
+ try {
899
+ content = file === '-' ? await readStdin() : await readFile(file, 'utf8');
900
+ }
901
+ catch (error) {
902
+ throw new UsageError(`Can't read ${file}: ${error.message}`);
903
+ }
904
+ if (Buffer.byteLength(content, 'utf8') > ENV_IMPORT_MAX_BYTES) {
905
+ throw new UsageError('The file is over 256 KB.');
906
+ }
907
+ if (options.branch !== undefined) {
908
+ throw new UsageError('env import saves variables for every build: --branch is for env add.');
909
+ }
910
+ const input = { content, ...envTargets(options), overwrite: options.overwrite === true };
911
+ let result;
912
+ try {
913
+ result = await api.importEnv(projectId, input);
914
+ }
915
+ catch (error) {
916
+ if (error instanceof ApiError && error.errors.some((e) => e.line !== undefined)) {
917
+ const lines = importErrorLines(error.errors);
918
+ throw new UsageError([`Nothing was imported from ${file}:`, ...lines].join('\n'));
919
+ }
920
+ throw error;
921
+ }
922
+ if (options.json)
923
+ return console.log(JSON.stringify(result, null, 2));
924
+ const list = (keys) => (keys.length > 0 ? keys.join(', ') : dim('none'));
925
+ console.log(`${green('✓')} Imported ${file}: it applies from the next build.`);
926
+ console.log(` created ${list(result.created)}`);
927
+ console.log(` updated ${list(result.updated)}`);
928
+ const hint = result.skipped.length > 0 ? dim(' (already there: --overwrite replaces them)') : '';
929
+ console.log(` skipped ${list(result.skipped)}${hint}`);
930
+ }
931
+ const FINISHED = ['SUCCEEDED', 'FAILED', 'CANCELED'];
932
+ function statusText(status) {
933
+ const text = {
934
+ QUEUED: 'queued',
935
+ RUNNING: 'building',
936
+ SUCCEEDED: 'ready',
937
+ FAILED: 'failed',
938
+ CANCELED: 'canceled',
939
+ }[status];
940
+ return status === 'SUCCEEDED' ? green(text) : status === 'FAILED' ? pink(text) : dim(text);
941
+ }
942
+ function duration(ms) {
943
+ if (ms === null)
944
+ return '';
945
+ const seconds = Math.round(ms / 1000);
946
+ return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
947
+ }
948
+ /** What a build was for: the pull request, or the branch (with the hook's name for hook builds). */
949
+ export function buildSubject(b) {
950
+ if (b.pullRequest)
951
+ return `#${b.pullRequest}`;
952
+ return b.trigger === 'hook' ? `${b.branch} (hook ${b.hookName ?? '?'})` : b.branch;
953
+ }
954
+ function buildLine(b) {
955
+ const subject = buildSubject(b);
956
+ const message = (b.commitMessage ?? '').split('\n')[0].slice(0, 60);
957
+ return [
958
+ bold(`${b.number}`.padStart(4)),
959
+ statusText(b.status).padEnd(tty ? 17 : 8),
960
+ b.target.padEnd(10),
961
+ subject,
962
+ dim(b.commit.slice(0, 7)),
963
+ duration(b.durationMs),
964
+ message,
965
+ ]
966
+ .filter(Boolean)
967
+ .join(' ');
968
+ }
969
+ /** Prints a build's log until it finishes; the exit code is 1 unless it succeeded. */
970
+ async function follow(api, project, number) {
971
+ let after = 0;
972
+ let waiting = false;
973
+ for (;;) {
974
+ const build = await api.build(project.id, number, after);
975
+ if (build.log)
976
+ process.stdout.write(build.log);
977
+ after = build.logOffset;
978
+ if (build.status === 'QUEUED' && !waiting) {
979
+ console.log(dim(`Build ${number} is queued: waiting for a build server…`));
980
+ waiting = true;
981
+ }
982
+ if (FINISHED.includes(build.status)) {
983
+ if (build.log && !build.log.endsWith('\n'))
984
+ process.stdout.write('\n');
985
+ if (build.status === 'SUCCEEDED') {
986
+ const deployment = (await allDeployments(api, project.id)).find((d) => d.id === build.deploymentId);
987
+ console.log(`${green('✓')} Build ${number} is ready (${duration(build.durationMs)})${deployment ? `: ${deployment.url}` : ''}`);
988
+ if (build.target === 'production')
989
+ console.log(`${green('✓')} Published: ${bold(project.url)}`);
990
+ warnProtected(project.protection, {
991
+ preview: deployment !== undefined,
992
+ production: build.target === 'production',
993
+ });
994
+ return 0;
995
+ }
996
+ console.error(`Build ${number} ${build.status === 'FAILED' ? `failed${build.error ? `: ${build.error}` : ''}` : 'was canceled'}.`);
997
+ return 1;
998
+ }
999
+ await sleep(2_000);
1000
+ }
1001
+ }
1002
+ async function builds(action, arg, options) {
1003
+ const { api } = await signedIn();
1004
+ const project = await target(api, options);
1005
+ if (!action || action === 'ls' || action === 'list') {
1006
+ const list = await api.builds(project.id);
1007
+ if (options.json)
1008
+ console.log(JSON.stringify(list, null, 2));
1009
+ else if (list.length === 0)
1010
+ console.log(dim('No builds yet: push to the repository, or codeqlick builds start'));
1011
+ else
1012
+ list.forEach((b) => console.log(buildLine(b)));
1013
+ return 0;
1014
+ }
1015
+ if (action === 'start') {
1016
+ const build = await api.startBuild(project.id, options.branch, options['no-cache']);
1017
+ if (options.json) {
1018
+ console.log(JSON.stringify(build, null, 2));
1019
+ return 0;
1020
+ }
1021
+ console.log(`Build ${bold(String(build.number))}: ${build.branch} ${dim(build.commit.slice(0, 7))} (${build.target})`);
1022
+ return follow(api, project, build.number);
1023
+ }
1024
+ if (action === 'cancel') {
1025
+ const number = Number(arg);
1026
+ if (!Number.isInteger(number) || number < 1)
1027
+ throw new UsageError('Which build? codeqlick builds cancel <number>');
1028
+ const build = await api.cancelBuild(project.id, number);
1029
+ console.log(`${green('✓')} Build ${build.number} is ${statusText(build.status)}.`);
1030
+ return 0;
1031
+ }
1032
+ throw new UsageError(`Unknown action "${action}": start or cancel.`);
1033
+ }
1034
+ /** The hook an argument names: its id, else its name (names are unique in a project). */
1035
+ export function findHook(hooks, ref) {
1036
+ return hooks.find((h) => h.id === ref) ?? hooks.find((h) => h.name === ref);
1037
+ }
1038
+ function showHook(h) {
1039
+ const called = h.lastCalledAt ? new Date(h.lastCalledAt).toLocaleString() : 'never called';
1040
+ console.log(`${bold(h.name)} ${h.branch} ${dim(`${h.prefix}…`)} ${dim(h.createdBy?.name ?? '')} ${dim(called)}`);
1041
+ }
1042
+ async function hooks(action, arg, options) {
1043
+ const { api } = await signedIn();
1044
+ const project = await target(api, options);
1045
+ if (!action || action === 'ls' || action === 'list') {
1046
+ const list = await api.hooks(project.id);
1047
+ if (options.json)
1048
+ console.log(JSON.stringify(list, null, 2));
1049
+ else if (list.length === 0)
1050
+ console.log(dim('No deploy hooks yet: codeqlick hooks add <name>'));
1051
+ else
1052
+ list.forEach(showHook);
1053
+ return;
1054
+ }
1055
+ if (action === 'add') {
1056
+ if (!arg || arg.length > 60)
1057
+ throw new UsageError('What name (1-60)? codeqlick hooks add <name>');
1058
+ const hook = await api.createHook(project.id, arg, options.branch);
1059
+ if (options.json)
1060
+ return console.log(JSON.stringify(hook, null, 2));
1061
+ console.log(`${green('✓')} Deploy hook ${bold(hook.name)} builds ${bold(hook.branch)}.`);
1062
+ console.log(`\n ${hook.url ?? ''}\n`);
1063
+ console.log("Paste it in your CMS's webhook (a POST, no body needed). It is shown only now: keep it secret.");
1064
+ return;
1065
+ }
1066
+ if (action === 'rm' || action === 'remove') {
1067
+ if (!arg)
1068
+ throw new UsageError('Which hook? codeqlick hooks rm <id or name>');
1069
+ const found = findHook(await api.hooks(project.id), arg);
1070
+ if (!found)
1071
+ throw new UsageError(`${project.slug} has no deploy hook "${arg}".`);
1072
+ await api.deleteHook(project.id, found.id);
1073
+ console.log(`${green('✓')} Deleted ${found.name}: its URL no longer works.`);
1074
+ return;
1075
+ }
1076
+ throw new UsageError(`Unknown action "${action}": add or rm.`);
1077
+ }
1078
+ async function logs(arg, options) {
1079
+ const { api } = await signedIn();
1080
+ const project = await target(api, options);
1081
+ let number = arg === undefined ? NaN : Number(arg);
1082
+ if (arg === undefined) {
1083
+ const latest = (await api.builds(project.id, 1))[0];
1084
+ if (!latest)
1085
+ throw new UsageError('No builds yet.');
1086
+ number = latest.number;
1087
+ }
1088
+ if (!Number.isInteger(number) || number < 1)
1089
+ throw new UsageError('Which build? codeqlick logs <number>');
1090
+ if (options.out === undefined)
1091
+ return follow(api, project, number);
1092
+ if (!options.out)
1093
+ throw new UsageError('--out needs a file name.');
1094
+ const file = logPath(options.out);
1095
+ if (!options.force && (await exists(file))) {
1096
+ throw new UsageError(`${file} already exists: pass --force to overwrite it.`);
1097
+ }
1098
+ const body = await api.buildLog(project.id, number);
1099
+ let size;
1100
+ try {
1101
+ size = await saveArchive(body, file);
1102
+ }
1103
+ catch (error) {
1104
+ throw downloadFailure(error, file);
1105
+ }
1106
+ const shown = relative(process.cwd(), file) || file;
1107
+ console.log(`${green('✓')} Build ${bold(String(number))} log saved to ${shown} (${bytes(size)})`);
1108
+ return 0;
1109
+ }
326
1110
  // ── Entry ─────────────────────────────────────────────────────────────────────────────────────
1111
+ const PERIODS = ['24h', '7d', '30d', '90d', '365d'];
1112
+ function table(title, rows, unit) {
1113
+ console.log(`\n${bold(title)}`);
1114
+ if (rows.length === 0)
1115
+ return console.log(dim(' nothing yet'));
1116
+ const width = Math.min(48, Math.max(...rows.map((r) => r.key.length)));
1117
+ for (const row of rows) {
1118
+ console.log(` ${row.key.slice(0, 48).padEnd(width)} ${String(row.visitors).padStart(6)} visitors ${String(row.count).padStart(6)} ${unit}`);
1119
+ }
1120
+ }
1121
+ /**
1122
+ * The change of a total against the previous period: `+12 %`, `-8 %`, `0 %`, `new` (nothing
1123
+ * before, something now) or null (both 0, or the previous window isn't complete).
1124
+ */
1125
+ export function changeText(current, previous, complete) {
1126
+ if (!complete)
1127
+ return null;
1128
+ if (previous === 0)
1129
+ return current > 0 ? 'new' : null;
1130
+ const percent = Math.round(((current - previous) / previous) * 100);
1131
+ return percent > 0 ? `+${percent} %` : `${percent === 0 ? 0 : percent} %`;
1132
+ }
1133
+ /** A total with its change next to it, e.g. `120 visitors (+12 %)`. */
1134
+ export function totalText(current, previous, complete, label) {
1135
+ const change = changeText(current, previous, complete);
1136
+ return `${bold(String(current))} ${label}${change ? ` ${dim(`(${change})`)}` : ''}`;
1137
+ }
1138
+ async function analytics(options) {
1139
+ const period = (options.period ?? '7d');
1140
+ if (!PERIODS.includes(period))
1141
+ throw new UsageError(`--period is one of ${PERIODS.join(', ')}.`);
1142
+ const { api } = await signedIn();
1143
+ const project = await target(api, options);
1144
+ const report = await api.analytics(project.id, period);
1145
+ if (options.json)
1146
+ return console.log(JSON.stringify(report, null, 2));
1147
+ if (!report.enabled) {
1148
+ console.log(dim(`Analytics are off for ${project.slug}: switch them on in the console and add`));
1149
+ console.log(dim(` ${report.snippet}`));
1150
+ }
1151
+ const { totals, previous } = report;
1152
+ console.log(`${bold(project.slug)} · ${period}: ${totalText(totals.visitors, previous.visitors, previous.complete, 'visitors')}, ${totalText(totals.pageviews, previous.pageviews, previous.complete, 'page views')}`);
1153
+ table('Pages', report.pages, 'views');
1154
+ table('Sources', report.referrers, 'views');
1155
+ if (report.events.length > 0)
1156
+ table('Events', report.events, 'times');
1157
+ }
1158
+ /** The state a monitor shows: `PAUSED` also when it is switched off. */
1159
+ export function monitorState(m) {
1160
+ return m.enabled ? m.status : 'PAUSED';
1161
+ }
1162
+ /** A span of time as `5 min`, `3 h` or `2 d`. */
1163
+ export function spanText(ms) {
1164
+ const minutes = Math.max(0, Math.floor(ms / 60_000));
1165
+ if (minutes < 1)
1166
+ return '<1 min';
1167
+ if (minutes < 60)
1168
+ return `${minutes} min`;
1169
+ const hours = Math.floor(minutes / 60);
1170
+ return hours < 48 ? `${hours} h` : `${Math.floor(hours / 24)} d`;
1171
+ }
1172
+ /** The rows of the `monitors` table, plain text (colours are added when printing). */
1173
+ export function monitorRows(monitors, now = Date.now()) {
1174
+ return monitors.map((m) => {
1175
+ const checked = m.kind === 'HTTP' ? m.lastCheckedAt : m.lastPingAt;
1176
+ return {
1177
+ name: m.name,
1178
+ kind: m.kind,
1179
+ state: monitorState(m),
1180
+ since: spanText(now - Date.parse(m.statusSince)),
1181
+ last: checked ? `${spanText(now - Date.parse(checked))} ago` : '-',
1182
+ };
1183
+ });
1184
+ }
1185
+ /** The table `codeqlick monitors` prints: a header, then a line per monitor. */
1186
+ export function monitorTable(monitors, now = Date.now()) {
1187
+ const rows = monitorRows(monitors, now);
1188
+ const head = { name: 'NAME', kind: 'KIND', state: 'STATE', since: 'SINCE', last: 'LAST CHECK' };
1189
+ const all = [head, ...rows];
1190
+ const w = (key) => Math.max(...all.map((r) => r[key].length));
1191
+ const widths = { name: w('name'), kind: w('kind'), state: w('state'), since: w('since') };
1192
+ const stateColour = (state) => (state === 'UP' ? green : state === 'DOWN' ? pink : dim);
1193
+ return all.map((r, i) => {
1194
+ const cells = [
1195
+ r.name.padEnd(widths.name),
1196
+ r.kind.padEnd(widths.kind),
1197
+ r.state.padEnd(widths.state),
1198
+ r.since.padEnd(widths.since),
1199
+ r.last,
1200
+ ];
1201
+ if (i === 0)
1202
+ return dim(cells.join(' '));
1203
+ return [cells[0], cells[1], stateColour(r.state)(cells[2]), cells[3], cells[4]].join(' ');
1204
+ });
1205
+ }
1206
+ /** Finds the monitor an argument names: its id first, then its exact name. */
1207
+ export function findMonitors(monitors, ref) {
1208
+ const byId = monitors.find((m) => m.id === ref);
1209
+ return byId ? [byId] : monitors.filter((m) => m.name === ref);
1210
+ }
1211
+ /** The one monitor an argument names; no match or several is an error that says so. */
1212
+ export function pickMonitor(monitors, ref, team) {
1213
+ const matches = findMonitors(monitors, ref);
1214
+ if (matches.length === 0)
1215
+ throw new UsageError(`There is no monitor "${ref}" in the team "${team}".`);
1216
+ if (matches.length > 1) {
1217
+ throw new UsageError([
1218
+ `${matches.length} monitors are named "${ref}": use an id.`,
1219
+ ...matches.map((m) => ` ${m.id} ${m.kind}`),
1220
+ ].join('\n'));
1221
+ }
1222
+ return matches[0];
1223
+ }
1224
+ /** Pauses or resumes; a monitor already in the wanted state is returned without a request. */
1225
+ export async function changeEnabled(api, monitor, enabled) {
1226
+ return monitor.enabled === enabled ? monitor : api.setMonitorEnabled(monitor.id, enabled);
1227
+ }
1228
+ async function monitors(action, ref, options) {
1229
+ const list = !action || action === 'ls' || action === 'list';
1230
+ if (!list && action !== 'pause' && action !== 'resume')
1231
+ throw new UsageError(`Unknown action "${action}": pause or resume.`);
1232
+ if (!list && !ref)
1233
+ throw new UsageError(`Which monitor? codeqlick monitors ${action} <id|name>`);
1234
+ const { api } = await signedIn();
1235
+ const team = await teamOf(api, options);
1236
+ const { items } = await api.monitors(team);
1237
+ if (list) {
1238
+ if (options.json)
1239
+ return console.log(JSON.stringify({ items }, null, 2));
1240
+ if (items.length === 0)
1241
+ return console.log(dim('No monitors yet'));
1242
+ for (const line of monitorTable(items))
1243
+ console.log(line);
1244
+ return;
1245
+ }
1246
+ const monitor = pickMonitor(items, ref, team);
1247
+ const enable = action === 'resume';
1248
+ const updated = await changeEnabled(api, monitor, enable);
1249
+ if (options.json)
1250
+ return console.log(JSON.stringify(updated, null, 2));
1251
+ console.log(`${green('✓')} ${enable ? 'Resumed' : 'Paused'} ${bold(monitor.name)}`);
1252
+ }
1253
+ /** A value typed on the command line: JSON when it parses, otherwise the text itself. */
1254
+ export function parseValue(text) {
1255
+ try {
1256
+ return JSON.parse(text);
1257
+ }
1258
+ catch {
1259
+ return text;
1260
+ }
1261
+ }
1262
+ const KV_KEY = /^[A-Za-z0-9._:-]{1,256}$/;
1263
+ async function kv(action, key, value, options) {
1264
+ const { api } = await signedIn();
1265
+ const project = await target(api, options);
1266
+ if (!action || action === 'ls' || action === 'list') {
1267
+ const prefix = action ? key : undefined;
1268
+ let cursor;
1269
+ const items = [];
1270
+ let usage;
1271
+ do {
1272
+ const page = await api.kvList(project.id, prefix, cursor);
1273
+ items.push(...page.items);
1274
+ usage = page.usage;
1275
+ cursor = page.cursor ?? undefined;
1276
+ } while (cursor && items.length < 1000);
1277
+ if (options.json)
1278
+ return (console.log(JSON.stringify({ items, usage }, null, 2)), 0);
1279
+ if (items.length === 0)
1280
+ console.log(dim('No keys yet: codeqlick kv set <key> <value>'));
1281
+ for (const item of items) {
1282
+ const expires = item.expiresAt
1283
+ ? dim(` expires ${new Date(item.expiresAt).toLocaleString()}`)
1284
+ : '';
1285
+ console.log(`${bold(item.key)} ${dim(`${item.size} B`)}${expires}`);
1286
+ }
1287
+ if (usage)
1288
+ console.log(dim(`${usage.keys} of ${usage.maxKeys} keys`));
1289
+ return 0;
1290
+ }
1291
+ if (!key || !KV_KEY.test(key)) {
1292
+ throw new UsageError(`Which key? codeqlick kv ${action} <key> (letters, digits, ".", "_", "-", ":")`);
1293
+ }
1294
+ switch (action) {
1295
+ case 'get': {
1296
+ const entry = await api.kvGet(project.id, key);
1297
+ console.log(options.json
1298
+ ? JSON.stringify(entry, null, 2)
1299
+ : typeof entry.value === 'string'
1300
+ ? entry.value
1301
+ : JSON.stringify(entry.value, null, 2));
1302
+ return 0;
1303
+ }
1304
+ case 'set': {
1305
+ if (value === undefined)
1306
+ throw new UsageError('What value? codeqlick kv set <key> <value>');
1307
+ const raw = value === '-' ? await readStdin() : value;
1308
+ const ttl = options.ttl === undefined ? undefined : Number(options.ttl);
1309
+ if (ttl !== undefined && (!Number.isInteger(ttl) || ttl < 1)) {
1310
+ throw new UsageError('--ttl is a whole number of seconds.');
1311
+ }
1312
+ const entry = await api.kvSet(project.id, key, parseValue(raw), ttl);
1313
+ if (options.json)
1314
+ console.log(JSON.stringify(entry, null, 2));
1315
+ else
1316
+ console.log(`${green('✓')} Saved ${bold(key)} (${entry.size} B)`);
1317
+ return 0;
1318
+ }
1319
+ case 'rm':
1320
+ case 'remove':
1321
+ await api.kvDelete(project.id, key);
1322
+ console.log(`${green('✓')} Deleted ${key}`);
1323
+ return 0;
1324
+ case 'incr': {
1325
+ const by = options.by === undefined ? 1 : Number(options.by);
1326
+ if (!Number.isInteger(by))
1327
+ throw new UsageError('--by is a whole number.');
1328
+ const result = await api.kvIncr(project.id, key, by);
1329
+ console.log(options.json ? JSON.stringify(result, null, 2) : String(result.value));
1330
+ return 0;
1331
+ }
1332
+ default:
1333
+ throw new UsageError(`Unknown action "${action}": ls, get, set, rm or incr.`);
1334
+ }
1335
+ }
1336
+ // ── Password protection ───────────────────────────────────────────────────────────────────────
1337
+ const PROTECT_MODES = {
1338
+ off: 'OFF',
1339
+ previews: 'PREVIEWS',
1340
+ all: 'ALL',
1341
+ };
1342
+ /** `protect <action>`'s mode: off, previews or all (any case); null when it's none of them. */
1343
+ export function parseProtectMode(action) {
1344
+ const key = action.toLowerCase();
1345
+ return Object.hasOwn(PROTECT_MODES, key) ? (PROTECT_MODES[key] ?? null) : null;
1346
+ }
1347
+ /** `--days`: 1, 7 or 30; undefined keeps the current days; null when it's anything else. */
1348
+ export function parseProtectDays(text) {
1349
+ if (text === undefined)
1350
+ return undefined;
1351
+ const days = Number(text.trim());
1352
+ return days === 1 || days === 7 || days === 30 ? days : null;
1353
+ }
1354
+ /**
1355
+ * The note for printed addresses that ask visitors for the password, or null when none does:
1356
+ * a deployment's address is protected with PREVIEWS and ALL, production only with ALL.
1357
+ */
1358
+ export function protectionNote(mode, printed) {
1359
+ const preview = printed.preview && mode !== 'OFF';
1360
+ const production = printed.production && mode === 'ALL';
1361
+ if (!preview && !production)
1362
+ return null;
1363
+ const what = printed.preview && printed.production
1364
+ ? production
1365
+ ? 'Both addresses ask'
1366
+ : "The deployment's address asks (the published one doesn't)"
1367
+ : 'The address asks';
1368
+ return `${what} visitors for the password (codeqlick protect).`;
1369
+ }
1370
+ /** Prints the note on standard error, so `--url-only` stays one line on standard output. */
1371
+ function warnProtected(mode, printed) {
1372
+ const note = protectionNote(mode ?? 'OFF', printed);
1373
+ if (note)
1374
+ console.error(note);
1375
+ }
1376
+ /** One line about the bypass token: its prefix and last use, or that none is set. */
1377
+ export function bypassSummary(bypass) {
1378
+ if (!bypass)
1379
+ return 'none (create one with: codeqlick protect bypass)';
1380
+ const used = bypass.lastUsedAt
1381
+ ? `last used ${new Date(bypass.lastUsedAt).toLocaleString()}`
1382
+ : 'never used';
1383
+ return `${bypass.prefix}… (${used})`;
1384
+ }
1385
+ function showProtection(project, protection) {
1386
+ if (protection.mode === 'OFF') {
1387
+ console.log(`${bold(project.slug)} ${dim('no password: every address is public')}`);
1388
+ console.log(dim(' Turn it on with: codeqlick protect previews|all'));
1389
+ if (protection.bypass)
1390
+ console.log(` ${dim('bypass'.padEnd(9))}${bypassSummary(protection.bypass)}`);
1391
+ return;
1392
+ }
1393
+ const where = protection.mode === 'ALL'
1394
+ ? "every address (the deployments', production and your domains)"
1395
+ : "the deployments' addresses (production stays public)";
1396
+ console.log(`${bold(project.slug)} ${pink('password')} on ${where}`);
1397
+ const rows = [
1398
+ ['access', `${protection.days} ${protection.days === 1 ? 'day' : 'days'} once entered`],
1399
+ ['password', protection.hasPassword ? 'set' : 'none'],
1400
+ ['bypass', bypassSummary(protection.bypass)],
1401
+ ];
1402
+ if (protection.updatedAt)
1403
+ rows.push(['changed', new Date(protection.updatedAt).toLocaleString()]);
1404
+ for (const [name, value] of rows)
1405
+ console.log(` ${dim(name.padEnd(9))}${value}`);
1406
+ }
1407
+ /** The new password: asked twice without echo in a terminal, else standard input; '' keeps it. */
1408
+ async function newPassword(hasPassword) {
1409
+ const keep = hasPassword ? ', empty keeps the current one' : '';
1410
+ let password;
1411
+ if (process.stdin.isTTY) {
1412
+ password = await askSecret(`Password (8-128 characters${keep}, hidden): `);
1413
+ if (password && (await askSecret('Again: ')) !== password) {
1414
+ throw new UsageError("The passwords don't match.");
1415
+ }
1416
+ }
1417
+ else
1418
+ password = await readStdin();
1419
+ if (!password) {
1420
+ if (!hasPassword)
1421
+ throw new UsageError('Turning protection on needs a password.');
1422
+ return undefined;
1423
+ }
1424
+ if (password.length < 8 || password.length > 128) {
1425
+ throw new UsageError('The password has 8 to 128 characters.');
1426
+ }
1427
+ return password;
1428
+ }
1429
+ /**
1430
+ * `protect bypass`: makes or replaces the bypass token. Only the token goes to standard output
1431
+ * (so it pipes into a CI secret); everything else goes to standard error. `--revoke` removes it.
1432
+ */
1433
+ async function protectBypass(options) {
1434
+ const { api } = await signedIn();
1435
+ const project = await target(api, options);
1436
+ if (options.revoke) {
1437
+ await api.revokeBypass(project.id);
1438
+ if (options.json)
1439
+ return console.log(JSON.stringify({}, null, 2));
1440
+ console.error(`${green('✓')} The bypass token of ${bold(project.slug)} is revoked.`);
1441
+ return;
1442
+ }
1443
+ const created = await api.createBypass(project.id);
1444
+ if (options.json) {
1445
+ return console.log(JSON.stringify({ token: created.token, prefix: created.prefix, createdAt: created.createdAt }, null, 2));
1446
+ }
1447
+ console.log(created.token);
1448
+ console.error([
1449
+ `${green('✓')} New bypass token for ${bold(project.slug)} (${created.prefix}…). It is shown only now; any previous token stopped working.`,
1450
+ dim(' Send it as a header to reach protected addresses without the password:'),
1451
+ dim(' X-Codeqlick-Bypass: <token>'),
1452
+ dim(' Store it as a secret: codeqlick protect bypass | gh secret set CQ_BYPASS'),
1453
+ ].join('\n'));
1454
+ }
1455
+ async function protect(action, options) {
1456
+ if (action?.toLowerCase() === 'bypass')
1457
+ return protectBypass(options);
1458
+ if (options.revoke)
1459
+ throw new UsageError('--revoke goes with "protect bypass".');
1460
+ const mode = action === undefined ? undefined : parseProtectMode(action);
1461
+ if (mode === null)
1462
+ throw new UsageError(`Unknown action "${action}": previews, all or off.`);
1463
+ const days = parseProtectDays(options.days);
1464
+ if (days === null)
1465
+ throw new UsageError('--days is 1, 7 or 30.');
1466
+ const { api } = await signedIn();
1467
+ const project = await target(api, options);
1468
+ const current = await api.protection(project.id);
1469
+ if (mode === undefined) {
1470
+ if (options.json)
1471
+ console.log(JSON.stringify(current, null, 2));
1472
+ else
1473
+ showProtection(project, current);
1474
+ return;
1475
+ }
1476
+ const password = mode === 'OFF' ? undefined : await newPassword(current.hasPassword);
1477
+ const saved = await api.setProtection(project.id, {
1478
+ mode,
1479
+ ...(password === undefined ? {} : { password }),
1480
+ ...(days === undefined ? {} : { days }),
1481
+ });
1482
+ if (options.json)
1483
+ return console.log(JSON.stringify(saved, null, 2));
1484
+ console.log(`${green('✓')} ${mode === 'OFF' ? 'Password protection is off' : 'Saved'}${password ? ' (a new password: visitors enter it again)' : ''}.`);
1485
+ showProtection(project, saved);
1486
+ }
327
1487
  export async function main(argv) {
328
1488
  const { values, positionals } = parseArgs({
329
1489
  args: argv,
@@ -334,6 +1494,27 @@ export async function main(argv) {
334
1494
  prod: { type: 'boolean' },
335
1495
  message: { type: 'string', short: 'm' },
336
1496
  token: { type: 'string' },
1497
+ 'url-only': { type: 'boolean' },
1498
+ 'min-score': { type: 'string' },
1499
+ 'fail-on': { type: 'string' },
1500
+ json: { type: 'boolean' },
1501
+ revoke: { type: 'boolean' },
1502
+ branch: { type: 'string' },
1503
+ 'no-cache': { type: 'boolean' },
1504
+ root: { type: 'string' },
1505
+ install: { type: 'string' },
1506
+ build: { type: 'string' },
1507
+ output: { type: 'string' },
1508
+ node: { type: 'string' },
1509
+ production: { type: 'boolean' },
1510
+ preview: { type: 'boolean' },
1511
+ overwrite: { type: 'boolean' },
1512
+ period: { type: 'string' },
1513
+ ttl: { type: 'string' },
1514
+ by: { type: 'string' },
1515
+ days: { type: 'string' },
1516
+ out: { type: 'string', short: 'o' },
1517
+ force: { type: 'boolean' },
337
1518
  help: { type: 'boolean', short: 'h' },
338
1519
  version: { type: 'boolean', short: 'v' },
339
1520
  },
@@ -375,24 +1556,64 @@ export async function main(argv) {
375
1556
  case 'rollback':
376
1557
  await rollback(options);
377
1558
  break;
1559
+ case 'download':
1560
+ await download(rest[0], options);
1561
+ break;
1562
+ case 'unlock':
1563
+ await unlock(options);
1564
+ break;
1565
+ case 'files':
1566
+ await files(rest[0], options);
1567
+ break;
1568
+ case 'diff':
1569
+ await diff(rest[0], rest[1], options);
1570
+ break;
378
1571
  case 'domains':
379
1572
  await domains(rest[0], rest[1], options);
380
1573
  break;
1574
+ case 'config':
1575
+ return await configCommand(rest[0], options);
381
1576
  case 'open':
382
1577
  await openSite(options);
383
1578
  break;
1579
+ case 'audit':
1580
+ return await audit(rest[0], options);
1581
+ case 'git':
1582
+ await git(rest[0], rest[1], options);
1583
+ break;
1584
+ case 'env':
1585
+ await env(rest[0], rest[1], rest[2], options);
1586
+ break;
1587
+ case 'hooks':
1588
+ await hooks(rest[0], rest[1], options);
1589
+ break;
1590
+ case 'builds':
1591
+ return await builds(rest[0], rest[1], options);
1592
+ case 'logs':
1593
+ return await logs(rest[0], options);
1594
+ case 'analytics':
1595
+ await analytics(options);
1596
+ break;
1597
+ case 'kv':
1598
+ return await kv(rest[0], rest[1], rest[2], options);
1599
+ case 'monitors':
1600
+ await monitors(rest[0], rest[1], options);
1601
+ break;
1602
+ case 'protect':
1603
+ await protect(rest[0], options);
1604
+ break;
384
1605
  default:
385
1606
  throw new UsageError(`Unknown command "${command}". Run codeqlick --help.`);
386
1607
  }
387
1608
  return 0;
388
1609
  }
389
1610
  catch (error) {
390
- if (error instanceof UsageError)
1611
+ if (error instanceof UsageError || error instanceof ProjectFileError)
391
1612
  console.error(error.message);
392
1613
  else if (error instanceof ApiError) {
393
1614
  console.error(error.status === 401
394
1615
  ? 'Not signed in, or the token is invalid: run `codeqlick login`.'
395
- : error.message);
1616
+ : formatApiError(error));
396
1617
  }
397
1618
  else
398
1619
  console.error(error.message);