@foliwake/cli 0.8.0 → 0.10.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.
@@ -4,8 +4,27 @@ import { Errors, Flags } from '@oclif/core';
4
4
  import { CoreCommand } from '../../core-command.js';
5
5
  import { addLines } from '../../render/add.js';
6
6
  import { probeLines } from '../../render/probe.js';
7
- import { DEFAULT_DRIVE_KEY, DRIVE_PLUGIN, entryOf } from '../../source-entry.js';
7
+ import { entryOf } from '../../source-entry.js';
8
+ import { entryFlags } from '../../source-flags.js';
8
9
  const usable = (probe) => Object.keys(probe.fields).length === 0;
10
+ const WHOLE_SITE = /"([a-z0-9-]+)" owns the whole site/;
11
+ /** The source that owns the whole site, when that is why the candidate was refused. */
12
+ export const wholeSiteOwner = (probe) => Object.values(probe.fields)
13
+ .map((message) => WHOLE_SITE.exec(message)?.[1])
14
+ .find((owner) => Boolean(owner)) ?? null;
15
+ /**
16
+ * When another source owns the whole site (`/`, as the project's `content` source of a new site), how to make
17
+ * room: that source keeps the home page and the prefixes its pages use; the new source then owns its own.
18
+ */
19
+ export function ownershipHints(owner, index, site) {
20
+ return [
21
+ '',
22
+ `Source "${owner}" owns the whole site (/), so no other source can own pages beside it. Narrow it to the home`,
23
+ 'page and the prefixes its pages use (`source check --source <id> --listing` shows them), then add this',
24
+ 'source again, e.g.:',
25
+ ` foliwake site set --site ${site} sources.${index}.owns '["=/", "/blocks"]'`,
26
+ ];
27
+ }
9
28
  async function readRules(file) {
10
29
  if (file === undefined)
11
30
  return undefined;
@@ -25,38 +44,15 @@ export default class SourceAdd extends CoreCommand {
25
44
  '<%= config.bin %> source add --site docs --plugin git-markdown --id docs --owns /docs ' +
26
45
  '--repository https://github.com/acme/docs',
27
46
  '<%= config.bin %> source add --site news --plugin drupal --id news --owns /articles ' +
28
- '--base-url https://cms.example.org --language en',
47
+ '--base-url https://cms.example.org --language en --list-title "News"',
48
+ '<%= config.bin %> source add --site docs --plugin google-docs --id guides --owns /guides ' +
49
+ '--page https://docs.google.com/document/d/1AbC…/edit=/guides/intro',
29
50
  ];
30
51
  static flags = {
31
52
  ...CoreCommand.siteFlags,
32
- plugin: Flags.string({ description: 'the connector', default: DRIVE_PLUGIN }),
33
- id: Flags.string({ description: 'the new source id (lower case, digits, "-")', required: true }),
34
- 'display-name': Flags.string({ description: 'the name the dashboard shows' }),
35
- owns: Flags.string({
36
- description: 'a path the source owns, such as /lessons or "=/" (repeatable)',
37
- multiple: true,
38
- required: true,
39
- }),
40
- mappings: Flags.string({
41
- description: 'a JSON file with path mapping rules (default: each file names its address)',
42
- }),
43
- folder: Flags.string({ description: 'Google Drive: the folder link or ID' }),
44
- subfolder: Flags.string({ description: 'Google Drive or Git: the folder inside that holds the pages' }),
45
- identity: Flags.string({
46
- description: 'Google Drive: file-id (default; renames keep the page) or front-matter',
47
- options: ['file-id', 'front-matter'],
48
- }),
49
- key: Flags.string({
50
- description: `Google Drive: the credential name of the service-account key (default ${DEFAULT_DRIVE_KEY})`,
51
- }),
52
- repository: Flags.string({ description: 'Git: the https address of the repository' }),
53
- branch: Flags.string({ description: 'Git: the branch (default main)' }),
54
- token: Flags.string({ description: 'Git: the credential name of a read-only token (private repository)' }),
55
- 'base-url': Flags.string({ description: 'Drupal: the site address' }),
56
- language: Flags.string({ description: 'Drupal: a language code, the default first (repeatable)', multiple: true }),
57
- 'basic-user': Flags.string({ description: 'Drupal: the credential name of a read-only user name (HTTP Basic)' }),
58
- 'basic-password': Flags.string({ description: 'Drupal: the credential name of its password' }),
53
+ ...entryFlags({ required: true }),
59
54
  'check-only': Flags.boolean({ description: 'check and print, save nothing' }),
55
+ force: Flags.boolean({ description: 'save even when the connection check fails' }),
60
56
  yes: Flags.boolean({ description: 'save without asking (scripts)' }),
61
57
  };
62
58
  async run() {
@@ -67,8 +63,12 @@ export default class SourceAdd extends CoreCommand {
67
63
  throw new Errors.CLIError(built.problem, { exit: 2 });
68
64
  const probe = await this.core.sources.probe({ site, candidate: built.value, listing: {} });
69
65
  this.print(probeLines(probe));
66
+ if (!usable(probe))
67
+ await this.explainOwnership(probe, site);
70
68
  if (!usable(probe) || flags['check-only'])
71
69
  return this.finishCheck(probe);
70
+ if (probe.connection?.ok === false && !flags.force)
71
+ return this.refuseFailed(probe);
72
72
  if (!(await this.confirmed(flags.yes, probe)))
73
73
  return { probe, saved: null };
74
74
  const saved = await this.core.sources.add({
@@ -84,6 +84,19 @@ export default class SourceAdd extends CoreCommand {
84
84
  for (const line of lines)
85
85
  this.log(line);
86
86
  }
87
+ async explainOwnership(probe, site) {
88
+ const owner = wholeSiteOwner(probe);
89
+ if (owner === null)
90
+ return;
91
+ const { sources } = await this.core.sources.list({ site });
92
+ this.print(ownershipHints(owner, Math.max(0, sources.findIndex((source) => source.id === owner)), site));
93
+ }
94
+ /** A source whose connection check failed is not saved unless --force. */
95
+ refuseFailed(probe) {
96
+ this.logToStderr('The connection check failed; nothing was saved. Fix it and run again, or pass --force.');
97
+ process.exitCode = 1;
98
+ return { probe, saved: null };
99
+ }
87
100
  finishCheck(probe) {
88
101
  if (!usable(probe) || probe.connection?.ok === false)
89
102
  process.exitCode = 1;
@@ -4,6 +4,25 @@ export default class SourceCheck extends CoreCommand {
4
4
  static examples: string[];
5
5
  static flags: {
6
6
  input: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ plugin: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
8
+ id: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'display-name': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ owns: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ mappings: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ folder: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ subfolder: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ identity: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
+ key: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ repository: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ branch: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
18
+ token: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
19
+ 'base-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
20
+ language: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
21
+ 'basic-user': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
22
+ 'basic-password': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
23
+ 'list-title': import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
24
+ page: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
25
+ 'allow-private-host': import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
26
  source: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
27
  listing: import("@oclif/core/interfaces").BooleanFlag<boolean>;
9
28
  max: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -11,6 +30,8 @@ export default class SourceCheck extends CoreCommand {
11
30
  config: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
31
  };
13
32
  run(): Promise<unknown>;
33
+ /** A source that is not saved, described by the same flags as `source add`; nothing is saved. */
34
+ private probeCandidate;
14
35
  private probeInput;
15
36
  private probeOne;
16
37
  private enabledSources;
@@ -1,12 +1,26 @@
1
- import { Flags } from '@oclif/core';
1
+ import { readFile } from 'node:fs/promises';
2
+ import { Errors, Flags } from '@oclif/core';
2
3
  import { CoreCommand } from '../../core-command.js';
3
4
  import { probeLines } from '../../render/probe.js';
5
+ import { entryOf } from '../../source-entry.js';
6
+ import { entryFlags } from '../../source-flags.js';
7
+ async function readRules(file) {
8
+ try {
9
+ return JSON.parse(await readFile(file, 'utf8'));
10
+ }
11
+ catch {
12
+ throw new Errors.CLIError(`--mappings: ${file} is not a readable JSON file of rules.`, { exit: 2 });
13
+ }
14
+ }
4
15
  export default class SourceCheck extends CoreCommand {
5
16
  static description = 'Checks content sources without changing anything: settings, credentials, the connection and, ' +
6
- 'with --listing, the files and the page addresses they would get (core sources.probe)';
17
+ 'with --listing, the files and the page addresses they would get; a saved source (--source) or a new one ' +
18
+ 'described with the flags of `source add` (--id …) (core sources.probe)';
7
19
  static examples = [
8
20
  '<%= config.bin %> source check --site my-site',
9
21
  '<%= config.bin %> source check --site my-site --source lessons --listing',
22
+ '<%= config.bin %> source check --site news --plugin drupal --id news --owns /articles ' +
23
+ '--base-url https://cms.example.org --language en',
10
24
  `<%= config.bin %> source check --site my-site --input '{"site":"my-site","candidate":{…}}'`,
11
25
  ];
12
26
  static flags = {
@@ -16,6 +30,7 @@ export default class SourceCheck extends CoreCommand {
16
30
  description: 'also list the files and their page addresses (slower: reads the whole source)',
17
31
  }),
18
32
  max: Flags.integer({ min: 1, max: 5000, description: 'at most this many files in the listing (default 500)' }),
33
+ ...entryFlags({ required: false }),
19
34
  ...CoreCommand.inputFlag,
20
35
  };
21
36
  async run() {
@@ -24,6 +39,8 @@ export default class SourceCheck extends CoreCommand {
24
39
  const listing = flags.listing ? { listing: flags.max === undefined ? {} : { max: flags.max } } : {};
25
40
  if (flags.input !== undefined)
26
41
  return this.probeInput(flags.input, site);
42
+ if (flags.id !== undefined)
43
+ return this.probeCandidate(flags, site, listing);
27
44
  const ids = flags.source === undefined ? await this.enabledSources(site) : [flags.source];
28
45
  const answers = [];
29
46
  for (const source of ids)
@@ -32,6 +49,19 @@ export default class SourceCheck extends CoreCommand {
32
49
  process.exitCode = 1;
33
50
  return answers;
34
51
  }
52
+ /** A source that is not saved, described by the same flags as `source add`; nothing is saved. */
53
+ async probeCandidate(flags, site, listing) {
54
+ if (flags.source !== undefined)
55
+ this.error('Give --source (a saved source) or --id (a new one), not both.', { exit: 2 });
56
+ const rules = flags.mappings === undefined ? undefined : await readRules(flags.mappings);
57
+ const built = entryOf(flags, rules);
58
+ if (!built.ok)
59
+ throw new Errors.CLIError(built.problem, { exit: 2 });
60
+ const answer = await this.probeOne({ site, candidate: built.value, ...listing });
61
+ if (answer.connection?.ok === false || Object.keys(answer.fields).length)
62
+ process.exitCode = 1;
63
+ return answer;
64
+ }
35
65
  async probeInput(raw, site) {
36
66
  const answer = await this.probeOne(await this.resolveInput(raw, () => ({ site })));
37
67
  if (answer.connection?.ok === false || Object.keys(answer.fields).length)
@@ -0,0 +1,30 @@
1
+ import type { CoreCaller } from './core-types.js';
2
+ /** A refusal with a text for people; nothing was sent or changed. */
3
+ export declare class ConnectRefused extends Error {
4
+ }
5
+ /** An organisation the account may create sites in. */
6
+ export interface CreatableOrg {
7
+ id: string;
8
+ name: string;
9
+ }
10
+ /** Asks which organisation (in a terminal); null when no answer was given. */
11
+ export type OrgPicker = (orgs: CreatableOrg[]) => Promise<string | null>;
12
+ /** `--repository none`: create the site without a repository. */
13
+ export declare const NO_REPOSITORY = "none";
14
+ /** The installation may create sites in every organisation; others where they are admin over all sites. */
15
+ export declare function creatableOrgs(core: CoreCaller): Promise<CreatableOrg[]>;
16
+ /** The organisation of a new site: `org`, the only one (said), the one picked, or a refusal. */
17
+ export declare function chooseOrg(core: CoreCaller, request: {
18
+ org?: string | undefined;
19
+ pickOrg?: OrgPicker | undefined;
20
+ }, say: (text: string) => void): Promise<string>;
21
+ /**
22
+ * A Git remote as the https:// address a server fetches (it fetches over HTTPS only): scp form and ssh://
23
+ * become https://, credentials, ports and `.git` are dropped. Null for a local path or another scheme.
24
+ */
25
+ export declare function httpsRepository(remote: string): string | null;
26
+ /** The repository of a new site: `--repository` (`none`: null), else the folder's `origin` (said), else null. */
27
+ export declare function chooseRepository(request: {
28
+ cwd: string;
29
+ repository?: string | null | undefined;
30
+ }, say: (text: string) => void): Promise<string | null>;
@@ -0,0 +1,100 @@
1
+ // What `site create`, `connect --create` and `create --create-site` decide before a site is created
2
+ // (connect.ts): the organisation, never silently (`--org`; the only one the account may create sites in, said;
3
+ // several: asked in a terminal, else refused with the list), and the repository the server will fetch from
4
+ // (`--repository`; by default the folder's Git `origin` as an https:// address; `none`: no repository yet).
5
+ import { execFile } from 'node:child_process';
6
+ import { realpath } from 'node:fs/promises';
7
+ import { promisify } from 'node:util';
8
+ /** A refusal with a text for people; nothing was sent or changed. */
9
+ export class ConnectRefused extends Error {
10
+ }
11
+ /** `--repository none`: create the site without a repository. */
12
+ export const NO_REPOSITORY = 'none';
13
+ const run = promisify(execFile);
14
+ /** The installation may create sites in every organisation; others where they are admin over all sites. */
15
+ export async function creatableOrgs(core) {
16
+ const grant = await core.whoami();
17
+ const orgs = await core.org.list();
18
+ const admin = (org) => org.membership?.role === 'admin' && org.membership.sites === null;
19
+ return orgs.filter((org) => grant.installation || admin(org)).map(({ id, name }) => ({ id, name }));
20
+ }
21
+ function severalOrgs(orgs) {
22
+ const lines = orgs.map((org) => ` ${org.id}${org.name && org.name !== org.id ? ` (${org.name})` : ''}`);
23
+ const head = `You may create sites in ${orgs.length} organisations; say which one with --org <id>:`;
24
+ return new ConnectRefused([head, ...lines].join('\n'));
25
+ }
26
+ /** The organisation of a new site: `org`, the only one (said), the one picked, or a refusal. */
27
+ export async function chooseOrg(core, request, say) {
28
+ if (request.org)
29
+ return request.org;
30
+ const orgs = await creatableOrgs(core);
31
+ if (orgs.length === 0) {
32
+ throw new ConnectRefused('This account may not create sites: that needs the admin role in an organisation.');
33
+ }
34
+ if (orgs.length === 1) {
35
+ say(`Organisation: ${orgs[0].id} (the only one where you may create sites).`);
36
+ return orgs[0].id;
37
+ }
38
+ if (!request.pickOrg)
39
+ throw severalOrgs(orgs);
40
+ const chosen = await request.pickOrg(orgs);
41
+ if (!chosen)
42
+ throw new ConnectRefused('No organisation was chosen; nothing was done.');
43
+ return chosen;
44
+ }
45
+ const SCP = /^(?:[^@/\s]+@)?([a-z0-9-]+(?:\.[a-z0-9-]+)+):(?!\/\/)([^\s:]+)$/i;
46
+ function httpsOf(host, repoPath) {
47
+ const clean = repoPath.replace(/^\/+/, '').replace(/\/+$/, '').replace(/\.git$/, '');
48
+ if (!clean || clean.split('/').some((part) => !part || part === '.' || part === '..'))
49
+ return null;
50
+ return `https://${host.toLowerCase()}/${clean}`;
51
+ }
52
+ /**
53
+ * A Git remote as the https:// address a server fetches (it fetches over HTTPS only): scp form and ssh://
54
+ * become https://, credentials, ports and `.git` are dropped. Null for a local path or another scheme.
55
+ */
56
+ export function httpsRepository(remote) {
57
+ const text = remote.trim();
58
+ const scp = SCP.exec(text);
59
+ if (scp)
60
+ return httpsOf(scp[1], scp[2]);
61
+ let url;
62
+ try {
63
+ url = new URL(text);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (!['https:', 'http:', 'ssh:', 'git+ssh:', 'git:'].includes(url.protocol) || !url.hostname.includes('.')) {
69
+ return null;
70
+ }
71
+ return httpsOf(url.hostname, decodeURIComponent(url.pathname));
72
+ }
73
+ /** The `origin` of the folder's own Git repository, or null (no repository, not its root, no origin). */
74
+ async function folderOrigin(cwd) {
75
+ const git = async (args) => (await run('git', args, { cwd, env: { ...process.env } })).stdout.trim();
76
+ try {
77
+ if ((await realpath(await git(['rev-parse', '--show-toplevel']))) !== (await realpath(cwd)))
78
+ return null;
79
+ return await git(['remote', 'get-url', 'origin']);
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /** The repository of a new site: `--repository` (`none`: null), else the folder's `origin` (said), else null. */
86
+ export async function chooseRepository(request, say) {
87
+ if (request.repository === NO_REPOSITORY)
88
+ return null;
89
+ if (request.repository !== undefined)
90
+ return request.repository;
91
+ const origin = await folderOrigin(request.cwd);
92
+ const https = origin === null ? null : httpsRepository(origin);
93
+ if (https === null) {
94
+ const why = origin === null ? "this folder's Git repository has no origin" : 'its origin is no repository address';
95
+ say(`Repository: none (${why}); add it later, or pass --repository <https address>.`);
96
+ return null;
97
+ }
98
+ say(`Repository: ${https} (this folder's origin; --repository names another, --repository none sets none).`);
99
+ return https;
100
+ }
@@ -13,4 +13,4 @@ export declare const isTerminal: (streams: TerminalStreams) => boolean;
13
13
  /** `pick` and `confirmRelink` for a connect request in a terminal; nothing otherwise. */
14
14
  export declare function terminalQuestions(streams: TerminalStreams, { ask }: {
15
15
  ask: boolean;
16
- }): Pick<ConnectRequest, 'pick' | 'confirmRelink'>;
16
+ }): Pick<ConnectRequest, 'pick' | 'confirmRelink' | 'pickOrg'>;
@@ -10,6 +10,13 @@ export function terminalQuestions(streams, { ask }) {
10
10
  const { askServer } = await import('./lib/prompts.js');
11
11
  return askServer(io, servers, (typed) => typed, { message: 'Which Foliwake server?', allowOther: false });
12
12
  },
13
+ pickOrg: async (orgs) => {
14
+ const { isCancel, select } = await import('@clack/prompts');
15
+ const hint = (org) => (org.name === org.id ? undefined : org.name);
16
+ const options = orgs.map((org) => ({ value: org.id, label: org.id, hint: hint(org) }));
17
+ const answer = await select({ ...io, message: 'In which organisation?', options });
18
+ return isCancel(answer) ? null : String(answer);
19
+ },
13
20
  confirmRelink: async (from, to) => {
14
21
  const { confirm, isCancel } = await import('@clack/prompts');
15
22
  const { describeLink } = await import('./connect.js');
package/dist/connect.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type OrgPicker } from './connect-choices.js';
1
2
  import type { CoreCaller, Operation, SiteCreateResult } from './core-types.js';
2
3
  /** At most 512 KiB of bundle (the API's body is 1 MB, base64); the same limit as core's. */
3
4
  export declare const MAX_BUNDLE_BYTES: number;
@@ -12,7 +13,11 @@ export interface ConnectRequest {
12
13
  /** In a terminal: asks whether to replace a link of the folder to another server or site. */
13
14
  confirmRelink?: RelinkConfirm | undefined;
14
15
  site: string;
16
+ /** The organisation; default: the only one the account may create sites in (several: `pickOrg`, else refused). */
15
17
  org?: string | undefined;
18
+ /** In a terminal: asks which organisation when the account may create sites in several. */
19
+ pickOrg?: OrgPicker | undefined;
20
+ /** The repository; undefined: the folder's Git `origin` as https://; `none` or null: none. */
16
21
  repository?: string | null | undefined;
17
22
  /** false: create the site without code; release 1 waits for the first `code prepare`. */
18
23
  code: boolean;
@@ -30,8 +35,7 @@ export interface ConnectOutcome {
30
35
  operation: Operation | null;
31
36
  result: SiteCreateResult | null;
32
37
  }
33
- export declare class ConnectRefused extends Error {
34
- }
38
+ export { ConnectRefused } from './connect-choices.js';
35
39
  /** The project's commit as a bundle, or why there is none (then the site is created without code). */
36
40
  /** `codeOnly`: changes in content/ do not count as dirty (pages are pushed as they are). */
37
41
  export declare function projectCommit(cwd: string, env: NodeJS.ProcessEnv, { codeOnly }?: {
@@ -72,8 +76,10 @@ export type ServerPicker = (servers: KnownServer[]) => Promise<string | null>;
72
76
  * never silently the last login.
73
77
  */
74
78
  export declare function chooseServer(request: Pick<ConnectRequest, 'server' | 'env'>, pick?: ServerPicker): Promise<string>;
75
- export declare function nextSteps(result: SiteCreateResult, { repository }: {
79
+ /** The next steps, for what `site create` does not set up itself. */
80
+ export declare function nextSteps(result: SiteCreateResult, { repository, server }: {
76
81
  repository: string | null;
82
+ server: string;
77
83
  }): string[];
78
84
  /** The signed-in caller of the server a request names. */
79
85
  export declare function signedInTo(request: Pick<ConnectRequest, 'server' | 'env' | 'pick'>, io: ConnectIO): Promise<{
package/dist/connect.js CHANGED
@@ -11,6 +11,7 @@ import { mkdir, mkdtemp, readFile, realpath, rm, stat, unlink, writeFile } from
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { promisify } from 'node:util';
14
+ import { ConnectRefused, chooseOrg, chooseRepository } from './connect-choices.js';
14
15
  import { setting } from './settings.js';
15
16
  import { COMMAND } from './settings.js';
16
17
  import { CLOUD, CLOUD_NOTE, CLOUD_TITLE, cloudOrigin, issuerOf, nameOrigin, readProfiles, serverDisplay, serverName, serverOrigin, signInMoved, } from './remote/servers.js';
@@ -21,8 +22,7 @@ export const MAX_BUNDLE_BYTES = 512 * 1024;
21
22
  /** core's rule on the server, checked before anything is sent. */
22
23
  const CREATED_SITE_ID = /^(?=.{1,12}$)[a-z](?:-?[a-z0-9])*$/;
23
24
  const CONNECT_WAIT_MS = 10 * 60 * 1000;
24
- export class ConnectRefused extends Error {
25
- }
25
+ export { ConnectRefused } from './connect-choices.js';
26
26
  async function git(cwd, args) {
27
27
  return (await run('git', args, { cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 16 << 20 })).stdout.trim();
28
28
  }
@@ -145,43 +145,48 @@ export async function chooseServer(request, pick) {
145
145
  ...signed.map((server) => ` ${serverLabel(server)}`),
146
146
  ].join('\n'));
147
147
  }
148
- /** How commits reach the server: it fetches them, CI names them with a key. */
149
- function codeOnServer(site) {
148
+ /** How commits reach the server: it fetches them from the repository; a private one needs a read token. */
149
+ function codeOnServer(site, repository) {
150
+ const where = repository
151
+ ? ` 2. Code: the server fetches the commits CI names from ${repository} over HTTPS. A public repository needs`
152
+ : " 2. Code: the server fetches the commits CI names from the site's repository over HTTPS (none is set: the" +
153
+ ` installation's owner sets it, \`${C} site set code.repository <https address> --site ${site}\`). ` +
154
+ 'A public one needs';
150
155
  return [
151
- " 2. Code on the server: it fetches the commit a deploy names from the site's repository. A private one needs",
152
- ` a read token: \`foliwake credential set ${codeTokenName(site)} --from-stdin\`; the workflow a CI key:`,
153
- ` \`foliwake account keys create --site ${site} --label <pipeline>\`.`,
156
+ where,
157
+ ` nothing more; a private one a read token: \`${C} credential set ${codeTokenName(site)} --from-stdin\`.`,
154
158
  ];
155
159
  }
156
- /** The next steps, for what v1 does not set up itself. */
157
- /** The repository variables of the workflows: the site id and the addresses the server gave the site. */
158
- function workflowVariables(site, result) {
160
+ /** The repository variables of the workflows: the server, the site id and the addresses the server gave it. */
161
+ function workflowVariables(server, site, result) {
159
162
  const preview = result.addresses.preview ? `, FOLIWAKE_PREVIEW_URL=${result.addresses.preview}` : '';
160
163
  const live = result.addresses.live ? `, FOLIWAKE_PRODUCTION_URL=${result.addresses.live}` : '';
161
- return `FOLIWAKE_SITE_ID=${site}${preview}${live}`;
164
+ return `FOLIWAKE_SERVER=${server}, FOLIWAKE_SITE_ID=${site}${preview}${live}`;
162
165
  }
163
- export function nextSteps(result, { repository }) {
166
+ function workflowSteps(server, site, result) {
167
+ return [
168
+ ` 3. Workflows (.github/workflows, inert until enabled): a CI key, \`${C} account keys create --site ${site} ` +
169
+ `--label github-actions --server ${server}\`, as the secret FOLIWAKE_TOKEN of the GitHub environments ` +
170
+ '`branch-previews` and `production`;',
171
+ ` repository variables ${workflowVariables(server, site, result)}; then BRANCH_PREVIEWS_ENABLED=true and ` +
172
+ 'FRONTEND_PRODUCTION_DEPLOY_ENABLED=true (README.md, "Connect to Foliwake").',
173
+ ];
174
+ }
175
+ /** The next steps, for what `site create` does not set up itself. */
176
+ export function nextSteps(result, { repository, server }) {
164
177
  const site = result.site;
165
- const lines = [
178
+ const pages = result.releaseOne.state === 'done' ? 'are on the server' : 'reach the server with the first code';
179
+ return [
166
180
  'Next steps (nothing of this was done for you):',
167
- ` 1. GitHub: create the repository and push this project, e.g. \`gh repo create <owner>/${site} --private ` +
168
- `--source . --push\` (or \`git remote add origin <url>\` and \`git push -u origin ` +
169
- `main\`).${repository ? '' : ` Then tell the server's operator the repository URL.`}`,
170
- ...codeOnServer(site),
171
- ` 3. Workflows (.github/workflows, inert until enabled): repository variables ${workflowVariables(site, result)}` +
172
- '; secrets BRANCH_PREVIEW_SSH_KEY, BRANCH_PREVIEW_KNOWN_HOSTS, BRANCH_PREVIEW_SSH_TARGET in the environment ' +
173
- '`branch-previews` and PRODUCTION_DEPLOY_SSH_KEY, PRODUCTION_DEPLOY_KNOWN_HOSTS, PRODUCTION_DEPLOY_SSH_TARGET ' +
174
- "in `production` (the keys and targets come from the server's operator); then BRANCH_PREVIEWS_ENABLED=true " +
175
- 'and FRONTEND_PRODUCTION_DEPLOY_ENABLED=true.',
176
- ` 4. Preview and publish: the pages of content/ ` +
177
- `${result.releaseOne.state === 'done' ? 'are on the server' : 'reach the server with the first code'}; build ` +
178
- `the preview in the admin (Publish → Preview), review it, then publish.`,
179
- ' 5. Content sources: the site reads content/ of this project. Google Drive, Git Markdown or Drupal are added ' +
180
- 'later by an admin (admin → Content sources); nothing was connected.',
181
- ' The new site is served at once on a server that keeps its sites in a database; one that lists them in its ' +
182
- 'file serves it after its listeners restart.',
181
+ ` 1. GitHub: push this project, e.g. \`gh repo create <owner>/${site} --public --source . --push\` (or ` +
182
+ '`git remote add origin <url>` and `git push -u origin main`); a private repository needs the read token of 2.',
183
+ ...codeOnServer(site, repository),
184
+ ...workflowSteps(server, site, result),
185
+ ` 4. Preview and publish: the pages of content/ ${pages}; \`${C} preview\` in this folder builds the ` +
186
+ 'preview, review it, then publish (`foliwake publish` or the dashboard).',
187
+ ` 5. Content sources: the site reads content/ of this project. Others (Google Drive, Git Markdown, Drupal) ` +
188
+ `are added by an admin: \`${C} source add\`.`,
183
189
  ];
184
- return lines;
185
190
  }
186
191
  /** The signed-in caller of the server a request names. */
187
192
  export async function signedInTo(request, io) {
@@ -360,6 +365,8 @@ export async function createSite(request, io) {
360
365
  throw new ConnectRefused(`The site id "${site}" cannot be used on a server: at most 12 lowercase letters, digits and single inner ` +
361
366
  `hyphens, starting with a letter.`);
362
367
  await checkRelink(request.cwd, { server, site }, request, io);
368
+ const org = await chooseOrg(signed.core, request, (text) => io.out(text));
369
+ const repository = await chooseRepository(request, (text) => io.out(text));
363
370
  let code = null;
364
371
  if (request.code) {
365
372
  const commit = await projectCommit(request.cwd, request.env);
@@ -375,8 +382,8 @@ export async function createSite(request, io) {
375
382
  io.out(`Creating site ${site} on ${serverDisplay(server, request.env)}…`);
376
383
  const accepted = await core.sites.create({
377
384
  site,
378
- ...(request.org ? { org: request.org } : {}),
379
- repository: request.repository ?? null,
385
+ org,
386
+ repository,
380
387
  code,
381
388
  expect: { absent: true },
382
389
  idempotencyKey: `connect-${randomBytes(12).toString('hex')}`,
@@ -406,7 +413,7 @@ export async function createSite(request, io) {
406
413
  if (result.addresses.branchPattern)
407
414
  io.out(`Branches: ${result.addresses.branchPattern}`);
408
415
  io.out();
409
- for (const line of nextSteps(result, { repository: request.repository ?? null }))
416
+ for (const line of nextSteps(result, { repository, server }))
410
417
  io.out(line);
411
418
  return { exit: 0, server, operation, result };
412
419
  }
@@ -124,7 +124,8 @@ export class CoreCommand extends Command {
124
124
  this.error(`--${name} ${NEEDS_ENGINE}`, { exit: 2 });
125
125
  }
126
126
  const { chooseTarget } = await import('./local-target.js');
127
- const choice = await this.guarded(() => chooseTarget({ server: text('server'), config: text('config') }));
127
+ const target = { server: text('server'), config: text('config'), content: text('content') };
128
+ const choice = await this.guarded(() => chooseTarget(target));
128
129
  if (choice === 'local' && engine) {
129
130
  const content = text('content');
130
131
  const { default: path } = await import('node:path');
@@ -13,6 +13,9 @@ export interface ConnectStep {
13
13
  /** An origin, from --server. */
14
14
  server: string | undefined;
15
15
  relink: boolean;
16
+ /** A new site's organisation and repository (`--org`, `--repository`; see connect-choices.ts). */
17
+ org?: string | undefined;
18
+ repository?: string | undefined;
16
19
  prompts: PromptStreams;
17
20
  signIn: (origin: string) => Promise<boolean>;
18
21
  /** Told the server and site the folder was linked to (`connect --json`). */
@@ -11,7 +11,7 @@ import { cloudConfigured, serverOrigin } from './remote/servers.js';
11
11
  import { COMMAND, setting } from './settings.js';
12
12
  function relinkOf(step) {
13
13
  const ask = terminalQuestions({ input: process.stdin, output: process.stdout }, { ask: step.interactive });
14
- return { relink: step.relink, confirmRelink: ask.confirmRelink };
14
+ return { relink: step.relink, confirmRelink: ask.confirmRelink, pickOrg: ask.pickOrg };
15
15
  }
16
16
  function runner(step, io, site) {
17
17
  const base = { cwd: step.target, env: process.env, ...relinkOf(step) };
@@ -23,7 +23,7 @@ function runner(step, io, site) {
23
23
  step.onLinked?.({ server: linked.server, site: step.linkSite, created: false });
24
24
  return linked.exit;
25
25
  }
26
- const created = await createSite({ ...base, site, server: on, code: true }, io);
26
+ const created = await createSite({ ...base, site, server: on, code: true, org: step.org, repository: step.repository }, io);
27
27
  if (created.exit === 0)
28
28
  step.onLinked?.({ server: created.server, site, created: true });
29
29
  return created.exit;
@@ -2,5 +2,7 @@ import { type Target } from './remote/servers.js';
2
2
  export interface TargetFlags {
3
3
  server: string | undefined;
4
4
  config: string | undefined;
5
+ /** `--content`: a folder on this computer, so the folder's configuration even in a linked folder. */
6
+ content?: string | undefined;
5
7
  }
6
- export declare function chooseTarget({ server, config }: TargetFlags, env?: NodeJS.ProcessEnv, cwd?: string): Target | 'local' | null;
8
+ export declare function chooseTarget({ server, config, content }: TargetFlags, env?: NodeJS.ProcessEnv, cwd?: string): Target | 'local' | null;
@@ -1,14 +1,14 @@
1
1
  // Where a core command's calls go: a server, or with the engine's runtime registered, this computer.
2
- // --server, then --config (local), then $FOLIWAKE_CONFIG (local) unless $FOLIWAKE_SERVER is set, then the
3
- // folder's .foliwake/connection.json, then $FOLIWAKE_SERVER, then ./foliwake.config.json in this folder
4
- // (local), then the last `login`, else local.
2
+ // --server, then --config (local), then $FOLIWAKE_CONFIG (local) unless $FOLIWAKE_SERVER is set, then
3
+ // --content with ./foliwake.config.json in this folder (local), then the folder's .foliwake/connection.json,
4
+ // then $FOLIWAKE_SERVER, then ./foliwake.config.json in this folder (local), then the last `login`, else local.
5
5
  // An explicit $FOLIWAKE_SERVER wins over $FOLIWAKE_CONFIG: the engine's Docker image sets FOLIWAKE_CONFIG for
6
6
  // its own commands, and a CI job or an operator naming a server must reach it (flags still win over both).
7
7
  // Without the engine nothing is local: null when nothing names a server.
8
8
  import { localRuntime } from './local-runtime.js';
9
9
  import { ServerAddressError, resolveTarget } from './remote/servers.js';
10
10
  import { setting } from './settings.js';
11
- export function chooseTarget({ server, config }, env = process.env, cwd = process.cwd()) {
11
+ export function chooseTarget({ server, config, content }, env = process.env, cwd = process.cwd()) {
12
12
  const engine = localRuntime();
13
13
  if (!engine)
14
14
  return resolveTarget({ server }, env, cwd);
@@ -17,6 +17,9 @@ export function chooseTarget({ server, config }, env = process.env, cwd = proces
17
17
  }
18
18
  if (server === undefined && (config !== undefined || configFromEnv(env)))
19
19
  return 'local';
20
+ // `page check --content ./x` in a linked folder: the local files, with this folder's configuration.
21
+ if (server === undefined && content !== undefined && engine.folderConfig(cwd))
22
+ return 'local';
20
23
  const target = resolveTarget({ server }, env, cwd);
21
24
  if (target && target.from !== 'login')
22
25
  return target;
@@ -25,8 +25,16 @@ export interface EntryFlags {
25
25
  language?: string[] | undefined;
26
26
  'basic-user'?: string | undefined;
27
27
  'basic-password'?: string | undefined;
28
+ 'list-title'?: string[] | undefined;
29
+ page?: string[] | undefined;
30
+ 'allow-private-host'?: string[] | undefined;
28
31
  }
29
32
  type Entry = Record<string, unknown>;
33
+ /** A Google document link (`/document/d/<id>/…`, its `tab=` if any) or a bare ID. */
34
+ export declare function googleDocument(text: string): Parsed<{
35
+ documentId: string;
36
+ tabId?: string;
37
+ }>;
30
38
  /** The entry of the flags, or the first problem. `mappings`: the rules of `--mappings`, as written. */
31
39
  export declare function entryOf(flags: EntryFlags, mappings: unknown): Parsed<Entry>;
32
40
  export {};