@politelabs/cabin-cli 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Polite Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # Cabin CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Develop a [Cabin](https://cabincms.com) site theme in a folder on your own machine, with your editor, git and a build tool, and sync it with the site as Shopify's CLI syncs a theme with a store. Rendering never leaves the server: `cabin theme dev` keeps a draft of your folder on the site and the page you have open draws itself again on every change.
4
+
5
+ ```
6
+ npm install --global @politelabs/cabin-cli
7
+ ```
8
+
9
+ Node 22.12 or newer. Nothing else is installed with it.
10
+
11
+ ## Signing in
12
+
13
+ A token is made on the site, under Site settings › API tokens: a *management* token, which acts as you. A self-hosted install can make one with `php artisan cabin:tokens:make`.
14
+
15
+ ```
16
+ cabin login --host https://app.cabincms.com
17
+ ```
18
+
19
+ The token is kept in `~/.config/cabin/credentials.json`, by host and site, never in the theme's folder.
20
+
21
+ ## A theme
22
+
23
+ ```
24
+ cabin theme init riverside --from birch # a copy of Birch; --from blank for the least that compiles
25
+ cd riverside
26
+ pnpm install # Tailwind, unless --no-tailwind
27
+ cabin theme dev # watches the folder, prints the preview link
28
+ cabin theme push --note "Tighter header" # saves a version
29
+ cabin theme publish # draws the site with it
30
+ ```
31
+
32
+ `cabin theme init` makes the theme on the site and writes `cabin.json` (the host, the site's handle and the theme's key), which is committed; `.cabin/` holds what the CLI remembers and isn't.
33
+
34
+ A theme is `theme.json`, `theme.css`, templates under `templates/` and patterns under `patterns/`. With Tailwind, `src/theme.css` is the source and `theme.css` is built from it by the `dev` and `build` scripts in the folder's `package.json`; `cabin theme dev` runs `dev` beside the watcher, and `push` runs `build` first. A folder with no scripts is synced as it is.
35
+
36
+ | Command | What it does |
37
+ | --- | --- |
38
+ | `cabin login [--host] [--token]` | Keep a token for a host and site. `logout` forgets it; `whoami` says who it is. |
39
+ | `cabin theme init <dir> [--from blank\|birch] [--name] [--key] [--no-tailwind]` | Make a theme on the site and write it into a folder. |
40
+ | `cabin theme list` | The site's themes, with a star on the one the site is drawn with. |
41
+ | `cabin theme pull [--theme key] [--version id] [--all]` | Take the current (or a named) version's files. `theme.css` is skipped when `src/theme.css` exists, unless `--all`. |
42
+ | `cabin theme check [--no-build]` | Run every check a save runs, writing nothing. |
43
+ | `cabin theme push [--note] [--force] [--check] [--no-build]` | Save a version. Refused when someone saved since you pulled; `--force` saves over it. |
44
+ | `cabin theme dev [--path /] [--no-build]` | Keep a draft on the site as the folder changes, with a link that reloads itself. |
45
+ | `cabin theme publish` | Draw the site with the theme. |
46
+ | `cabin theme open [--site]` | Open the Theme files screen, or the site. |
47
+
48
+ Problems are printed as `templates/home.twig:12 The raw filter isn't needed…`, the way the admin's Theme files screen says them. The built stylesheet is held to the same rules: no `@import`, no address on another host, at most 256 KB.
49
+
50
+ ## Developing the CLI
51
+
52
+ ```
53
+ pnpm install
54
+ pnpm test # units, and every command against a stub of the API
55
+ pnpm build # dist/index.js
56
+ node dist/index.js --help
57
+ ```
58
+
59
+ `CABIN_TEST_HOST` and `CABIN_TEST_TOKEN` run a smoke test against a real Cabin. The CLI follows the content API's contract, `docs/api/openapi.yaml` in the Cabin repository.
@@ -0,0 +1,46 @@
1
+ import { join } from 'node:path';
2
+ import { readText, writeText } from '../io/fs.js';
3
+ import { ApiClient } from '../lib/api.js';
4
+ import { flag } from '../lib/args.js';
5
+ import { CONFIG_FILE, normalizeHost, parseConfig, parseState, STATE_FILE, serializeState, } from '../lib/config.js';
6
+ import { credentialsDir, parseCredentials, pick } from '../lib/credentials.js';
7
+ export class Refused extends Error {
8
+ }
9
+ /** Read `cabin.json` from the working directory, or refuse. */
10
+ export async function project(io) {
11
+ const json = await readText(join(io.cwd, CONFIG_FILE));
12
+ if (json === null) {
13
+ throw new Refused(`There's no ${CONFIG_FILE} here. Run cabin theme init to start a theme, or cd into one.`);
14
+ }
15
+ const config = parseConfig(json);
16
+ if ('error' in config) {
17
+ throw new Refused(config.error);
18
+ }
19
+ const token = await tokenFor(io, config.host, config.site);
20
+ const state = parseState(await readText(join(io.cwd, STATE_FILE)));
21
+ return {
22
+ config,
23
+ state,
24
+ api: new ApiClient(config.host, token, io.fetch),
25
+ root: io.cwd,
26
+ saveState: (next) => writeText(join(io.cwd, STATE_FILE), serializeState(next)),
27
+ };
28
+ }
29
+ /** The token kept for a host and site, or refuse with what to do. */
30
+ export async function tokenFor(io, host, site) {
31
+ const envToken = io.env.CABIN_TOKEN;
32
+ if (envToken) {
33
+ return envToken;
34
+ }
35
+ const credentials = parseCredentials(await readText(join(credentialsDir(io.env, io.home), 'credentials.json')));
36
+ const kept = pick(credentials, host, site);
37
+ if (kept === null) {
38
+ throw new Refused(`No token is kept for ${site} on ${host}. Run cabin login --host ${host}.`);
39
+ }
40
+ return kept.token;
41
+ }
42
+ /** The host a command names, from its flag or the environment. */
43
+ export function hostFrom(parsed, io) {
44
+ const given = flag(parsed, 'host') ?? io.env.CABIN_HOST ?? null;
45
+ return given === null ? null : normalizeHost(given);
46
+ }
@@ -0,0 +1,85 @@
1
+ import { join } from 'node:path';
2
+ import { readText, writeText } from '../io/fs.js';
3
+ import { ApiClient, ApiFailed } from '../lib/api.js';
4
+ import { flag } from '../lib/args.js';
5
+ import { CONFIG_FILE, normalizeHost, parseConfig } from '../lib/config.js';
6
+ import { credentialsDir, drop, looksLikeToken, parseCredentials, put, serializeCredentials, } from '../lib/credentials.js';
7
+ import { hostFrom, Refused, tokenFor } from './context.js';
8
+ async function hostOrAsk(parsed, io) {
9
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
10
+ const host = hostFrom(parsed, io) ??
11
+ ('error' in fromProject ? null : fromProject.host);
12
+ if (host !== null) {
13
+ return host;
14
+ }
15
+ const typed = normalizeHost(await io.prompt("The site's admin address (such as https://app.cabincms.com): "));
16
+ if (typed === null) {
17
+ throw new Refused("Give the admin's address, such as https://app.cabincms.com.");
18
+ }
19
+ return typed;
20
+ }
21
+ /** Keep a token for a host and the site it names. */
22
+ export async function login(parsed, io) {
23
+ const host = await hostOrAsk(parsed, io);
24
+ let token = flag(parsed, 'token') ?? io.env.CABIN_TOKEN ?? '';
25
+ if (token === '') {
26
+ token = (await io.prompt('Paste a management token from Site settings › API tokens: ', true)).trim();
27
+ }
28
+ if (!looksLikeToken(token)) {
29
+ throw new Refused("That doesn't look like one of Cabin's tokens: they start with cabin_ and are 46 characters long.");
30
+ }
31
+ let info;
32
+ try {
33
+ info = await new ApiClient(host, token, io.fetch).token_();
34
+ }
35
+ catch (error) {
36
+ if (error instanceof ApiFailed && error.status === 401) {
37
+ throw new Refused(`That token isn't accepted by ${host}.`);
38
+ }
39
+ throw error;
40
+ }
41
+ if (info.kind !== 'management') {
42
+ io.err(`This is a ${info.kind} token. The theme commands need a management token, which acts as you.`);
43
+ }
44
+ const file = join(credentialsDir(io.env, io.home), 'credentials.json');
45
+ const all = put(parseCredentials(await readText(file)), host, info.site.handle, {
46
+ token,
47
+ name: info.user?.name ?? info.name,
48
+ savedAt: new Date(io.now()).toISOString(),
49
+ });
50
+ await writeText(file, serializeCredentials(all), 0o600);
51
+ io.out(`Signed in to ${info.site.name} (${info.site.handle}) on ${host}${info.user ? ` as ${info.user.name}` : ''}.`);
52
+ return 0;
53
+ }
54
+ /** Forget a token. */
55
+ export async function logout(parsed, io) {
56
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
57
+ const host = hostFrom(parsed, io) ??
58
+ ('error' in fromProject ? null : fromProject.host);
59
+ const site = flag(parsed, 'site') ??
60
+ ('error' in fromProject ? null : fromProject.site);
61
+ if (host === null || site === null) {
62
+ throw new Refused("Say which to forget: cabin logout --host URL --site handle, or run it inside a theme's folder.");
63
+ }
64
+ const file = join(credentialsDir(io.env, io.home), 'credentials.json');
65
+ await writeText(file, serializeCredentials(drop(parseCredentials(await readText(file)), host, site)), 0o600);
66
+ io.out(`Forgot the token for ${site} on ${host}.`);
67
+ return 0;
68
+ }
69
+ /** Say who the kept token is. */
70
+ export async function whoami(parsed, io) {
71
+ const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
72
+ const host = hostFrom(parsed, io) ??
73
+ ('error' in fromProject ? null : fromProject.host);
74
+ const site = flag(parsed, 'site') ??
75
+ ('error' in fromProject ? null : fromProject.site);
76
+ if (host === null || site === null) {
77
+ throw new Refused("Say which: cabin whoami --host URL --site handle, or run it inside a theme's folder.");
78
+ }
79
+ const info = await new ApiClient(host, await tokenFor(io, host, site), io.fetch).token_();
80
+ io.out(`${info.site.name} (${info.site.handle}) on ${host}${info.site.url ? `, at ${info.site.url}` : ''}`);
81
+ io.out(info.user
82
+ ? `${info.user.name} <${info.user.email}>, through the ${info.kind} token "${info.name}"`
83
+ : `The ${info.kind} token "${info.name}"`);
84
+ return 0;
85
+ }
@@ -0,0 +1,24 @@
1
+ import { ApiFailed } from '../../lib/api.js';
2
+ import { has } from '../../lib/args.js';
3
+ import { problemLines } from '../../lib/problems.js';
4
+ import { project } from '../context.js';
5
+ import { buildFirst, filesIn } from './sync.js';
6
+ /** Run every check a save runs, writing nothing. */
7
+ export async function check(parsed, io) {
8
+ const { api, config, root } = await project(io);
9
+ await buildFirst(root, io, has(parsed, 'no-build'));
10
+ try {
11
+ const answer = await api.check(config.theme, await filesIn(root));
12
+ io.out(`No problems in ${answer.files} ${answer.files === 1 ? 'file' : 'files'} of "${answer.name}".`);
13
+ return 0;
14
+ }
15
+ catch (error) {
16
+ if (error instanceof ApiFailed && error.status === 422) {
17
+ for (const line of problemLines(error.errors)) {
18
+ io.err(line);
19
+ }
20
+ return 1;
21
+ }
22
+ throw error;
23
+ }
24
+ }
@@ -0,0 +1,122 @@
1
+ import { watch } from 'node:fs';
2
+ import { ApiFailed } from '../../lib/api.js';
3
+ import { flag, has } from '../../lib/args.js';
4
+ import { paint, syncedLine, wantsColor } from '../../lib/output.js';
5
+ import { problemLines } from '../../lib/problems.js';
6
+ import { isSkipped, isThemePath, toThemePath } from '../../lib/theme-files.js';
7
+ import { backoff, Debounce } from '../../lib/watch.js';
8
+ import { project } from '../context.js';
9
+ import { filesIn, scriptIn } from './sync.js';
10
+ /**
11
+ * Keep a draft of the folder on the site as it changes: the theme's `dev`
12
+ * script runs beside the watcher, every burst of changes is sent as one
13
+ * sync under the same draft token, and the page open on the link draws
14
+ * itself again. Ctrl-C ends both.
15
+ */
16
+ export async function dev(parsed, io) {
17
+ const { api, config, state, root, saveState } = await project(io);
18
+ const path = flag(parsed, 'path') ?? '/';
19
+ const color = wantsColor(io.isTTY, io.env);
20
+ let token = state.draftToken;
21
+ let failures = 0;
22
+ let stopped = false;
23
+ const child = has(parsed, 'no-build') ? null : await startScript(root, io);
24
+ const send = async (first) => {
25
+ try {
26
+ const draft = await api.draft(config.theme, await filesIn(root), path, token);
27
+ const renewed = token !== null && token !== draft.token;
28
+ token = draft.token;
29
+ await saveState({ ...state, draftToken: token });
30
+ failures = 0;
31
+ if (first || renewed) {
32
+ io.out(`Preview: ${paint(draft.url, 'cyan', color)}`);
33
+ io.out('The page draws itself again on every change. Ctrl-C stops.');
34
+ }
35
+ else if (draft.made) {
36
+ io.out('The draft had ended while idle; the same link works again.');
37
+ }
38
+ io.out(syncedLine(new Date(io.now()), Object.keys(await filesIn(root)).length));
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof ApiFailed && error.status === 422) {
43
+ for (const line of problemLines(error.errors)) {
44
+ io.err(paint(line, 'yellow', color));
45
+ }
46
+ return true;
47
+ }
48
+ if (error instanceof ApiFailed &&
49
+ (error.status === 401 || error.status === 403)) {
50
+ io.err(error.status === 401
51
+ ? 'The token was refused. Run cabin login.'
52
+ : `This token can't manage themes on ${config.site}.`);
53
+ stopped = true;
54
+ return false;
55
+ }
56
+ if (error instanceof ApiFailed && error.status === 0) {
57
+ failures += 1;
58
+ const wait = backoff(failures);
59
+ io.err(`Can't reach ${config.host}; trying again in ${Math.round(wait / 1000)} s.`);
60
+ await io.sleep(wait);
61
+ return false;
62
+ }
63
+ throw error;
64
+ }
65
+ };
66
+ let ok = await send(true);
67
+ while (!ok && !stopped) {
68
+ ok = await send(true);
69
+ }
70
+ if (stopped) {
71
+ child?.kill('SIGTERM');
72
+ return 1;
73
+ }
74
+ const debounce = new Debounce();
75
+ let dirty = false;
76
+ const watcher = watch(root, { recursive: true }, (_event, filename) => {
77
+ const relative = toThemePath(String(filename ?? ''));
78
+ if (relative === '' || isSkipped(relative) || !isThemePath(relative)) {
79
+ return;
80
+ }
81
+ debounce.push(io.now());
82
+ dirty = true;
83
+ });
84
+ const loop = (async () => {
85
+ while (!stopped) {
86
+ const due = debounce.due(io.now());
87
+ if (dirty && due !== null && due <= 0 && debounce.fire(io.now())) {
88
+ dirty = false;
89
+ let sent = await send(false);
90
+ while (!sent && !stopped) {
91
+ sent = await send(false);
92
+ }
93
+ }
94
+ await io.sleep(due === null ? 100 : Math.max(20, Math.min(due, 100)));
95
+ }
96
+ })();
97
+ await io.stopped;
98
+ stopped = true;
99
+ watcher.close();
100
+ await loop;
101
+ if (child !== null) {
102
+ child.kill('SIGTERM');
103
+ await Promise.race([
104
+ new Promise((resolve) => child.once('exit', () => resolve())),
105
+ io.sleep(2000),
106
+ ]);
107
+ if (child.exitCode === null) {
108
+ child.kill('SIGKILL');
109
+ }
110
+ }
111
+ io.out('Stopped. The draft stays on the site until it goes quiet for an hour; the next cabin theme dev brings the same link back.');
112
+ return 0;
113
+ }
114
+ async function startScript(root, io) {
115
+ const script = await scriptIn(root, 'dev', io);
116
+ if (script === null) {
117
+ return null;
118
+ }
119
+ const [command, args] = script;
120
+ io.out(`Running ${command} ${args.join(' ')} beside the watcher…`);
121
+ return io.spawn(command, args, root);
122
+ }
@@ -0,0 +1,80 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { exists, writeText } from '../../io/fs.js';
3
+ import { ApiClient, ApiFailed } from '../../lib/api.js';
4
+ import { flag, has } from '../../lib/args.js';
5
+ import { CONFIG_FILE, serializeState } from '../../lib/config.js';
6
+ import { problemLines } from '../../lib/problems.js';
7
+ import { scaffold } from '../../lib/scaffold.js';
8
+ import { hostFrom, Refused, tokenFor } from '../context.js';
9
+ /** A key from a name: lowercase letters, digits and hyphens, starting with a letter. */
10
+ export function keyFrom(name) {
11
+ const key = name
12
+ .toLowerCase()
13
+ .normalize('NFKD')
14
+ .replace(/[^a-z0-9]+/g, '-')
15
+ .replace(/^-+|-+$/g, '')
16
+ .slice(0, 63);
17
+ return /^[a-z]/.test(key) ? key : `theme-${key}`.replace(/-+$/, '');
18
+ }
19
+ /** Make a theme on the site and write it into a folder. */
20
+ export async function init(parsed, io) {
21
+ const dir = parsed.positionals[0];
22
+ if (dir === undefined) {
23
+ throw new Refused('Say where to put the theme: cabin theme init <dir>.');
24
+ }
25
+ const root = resolve(io.cwd, dir);
26
+ if (await exists(join(root, CONFIG_FILE))) {
27
+ throw new Refused(`${dir} already holds a theme (${CONFIG_FILE}). Use cabin theme pull there instead.`);
28
+ }
29
+ const host = hostFrom(parsed, io);
30
+ const site = flag(parsed, 'site') ?? io.env.CABIN_SITE ?? null;
31
+ if (host === null || site === null) {
32
+ throw new Refused('Say which site: cabin theme init <dir> --host URL --site handle (or CABIN_HOST and CABIN_SITE).');
33
+ }
34
+ const api = new ApiClient(host, await tokenFor(io, host, site), io.fetch);
35
+ const name = flag(parsed, 'name') ??
36
+ dir.split(/[\\/]/).filter(Boolean).at(-1) ??
37
+ 'Theme';
38
+ const key = flag(parsed, 'key') ?? keyFrom(name);
39
+ const from = flag(parsed, 'from') ?? 'blank';
40
+ const sources = await api.sources();
41
+ if (!sources.some((source) => source.key === from)) {
42
+ throw new Refused(`There's nothing to start from called "${from}". Try: ${sources.map((s) => s.key).join(', ')}.`);
43
+ }
44
+ let theme;
45
+ try {
46
+ theme = await api.create(key, name, from);
47
+ }
48
+ catch (error) {
49
+ if (error instanceof ApiFailed && error.status === 422) {
50
+ for (const line of problemLines(error.errors)) {
51
+ io.err(line);
52
+ }
53
+ if ('key' in error.errors) {
54
+ io.err('Pick another key with --key.');
55
+ }
56
+ return 1;
57
+ }
58
+ throw error;
59
+ }
60
+ const tailwind = !has(parsed, 'no-tailwind');
61
+ for (const file of scaffold({ host, site, theme: theme.key }, theme.files, {
62
+ tailwind,
63
+ })) {
64
+ await writeText(join(root, file.path), file.contents);
65
+ }
66
+ await writeText(join(root, '.cabin', 'state.json'), serializeState({
67
+ versionId: theme.version?.id ?? null,
68
+ draftToken: null,
69
+ }));
70
+ io.out(`Made the theme "${theme.name}" (${theme.key}) on ${site}, from ${from}, in ${dir}.`);
71
+ io.out('');
72
+ io.out('Next:');
73
+ io.out(` cd ${dir}`);
74
+ if (tailwind) {
75
+ io.out(' pnpm install # or npm install: Tailwind, for src/theme.css');
76
+ }
77
+ io.out(' cabin theme dev # keeps a draft on the site as you work, and prints its link');
78
+ io.out(' cabin theme push # saves a version');
79
+ return 0;
80
+ }
@@ -0,0 +1,27 @@
1
+ import { themeTable } from '../../lib/output.js';
2
+ import { project } from '../context.js';
3
+ /** The site's themes. */
4
+ export async function list(_parsed, io) {
5
+ const { api, config } = await project(io);
6
+ const answer = await api.themes();
7
+ for (const line of themeTable(answer.themes.map((theme) => ({
8
+ key: theme.key,
9
+ name: theme.name,
10
+ chosen: theme.chosen,
11
+ version: theme.version?.number ?? null,
12
+ by: theme.version?.by ?? null,
13
+ at: theme.version?.createdAt ?? null,
14
+ })))) {
15
+ io.out(line);
16
+ }
17
+ if (answer.chosen !== null && !answer.chosen.startsWith('site:')) {
18
+ io.out(`The site is drawn with the install's theme "${answer.chosen}".`);
19
+ }
20
+ else if (answer.chosen === null) {
21
+ io.out('The site is on its own frontend.');
22
+ }
23
+ if (!answer.themes.some((theme) => theme.key === config.theme)) {
24
+ io.err(`This folder's theme, "${config.theme}", isn't on the site any more.`);
25
+ }
26
+ return 0;
27
+ }
@@ -0,0 +1,19 @@
1
+ import { has } from '../../lib/args.js';
2
+ import { project, Refused } from '../context.js';
3
+ /** Open the Theme files screen, or the site, in the browser. */
4
+ export async function open(parsed, io) {
5
+ const { api, config } = await project(io);
6
+ if (has(parsed, 'site')) {
7
+ const theme = await api.theme(config.theme);
8
+ if (theme.siteUrl === null) {
9
+ throw new Refused('This site has no address yet. Add a domain in Site settings, under General.');
10
+ }
11
+ await io.open(theme.siteUrl);
12
+ io.out(theme.siteUrl);
13
+ return 0;
14
+ }
15
+ const url = `${config.host}/sites/${config.site}/themes/${config.theme}/edit`;
16
+ await io.open(url);
17
+ io.out(url);
18
+ return 0;
19
+ }
@@ -0,0 +1,13 @@
1
+ import { standing } from '../../lib/versions.js';
2
+ import { project } from '../context.js';
3
+ /** Draw the site with the theme. */
4
+ export async function publish(_parsed, io) {
5
+ const { api, config, state } = await project(io);
6
+ const theme = await api.theme(config.theme);
7
+ if (standing(state.versionId, theme.version?.id ?? null) === 'behind') {
8
+ io.err(`The site's version ${theme.version?.number ?? '?'} isn't the one you last pushed. Pull or push first if that matters.`);
9
+ }
10
+ const answer = await api.choose(config.theme);
11
+ io.out(`Visitors now see "${answer.name}"${answer.version === null ? '' : ` (version ${answer.version})`}.`);
12
+ return 0;
13
+ }
@@ -0,0 +1,48 @@
1
+ import { join } from 'node:path';
2
+ import { exists, remove, walk, writeText } from '../../io/fs.js';
3
+ import { flag, has } from '../../lib/args.js';
4
+ import { isGenerated, isThemePath } from '../../lib/theme-files.js';
5
+ import { project, Refused } from '../context.js';
6
+ import { hasSource } from './sync.js';
7
+ /** Take the theme's files from the site into the folder. */
8
+ export async function pull(parsed, io) {
9
+ const { api, config, state, root, saveState } = await project(io);
10
+ const key = flag(parsed, 'theme') ?? config.theme;
11
+ const versionId = flag(parsed, 'version');
12
+ const all = has(parsed, 'all');
13
+ if (versionId !== null && !/^\d+$/.test(versionId)) {
14
+ throw new Refused("--version takes a version's id, as cabin theme list and the Theme files screen show it.");
15
+ }
16
+ const taken = versionId === null
17
+ ? await api.theme(key)
18
+ : await api.version(key, Number(versionId));
19
+ const files = taken.files;
20
+ const version = 'version' in taken ? taken.version : taken;
21
+ const generated = await hasSource(root);
22
+ let written = 0;
23
+ let skipped = null;
24
+ for (const [path, contents] of Object.entries(files)) {
25
+ if (!all && isGenerated(path, () => generated)) {
26
+ skipped = path;
27
+ continue;
28
+ }
29
+ await writeText(join(root, path), contents);
30
+ written += 1;
31
+ }
32
+ // What the site no longer has goes too, among the theme's own files.
33
+ let removed = 0;
34
+ for (const [relative] of await walk(root)) {
35
+ if (isThemePath(relative) &&
36
+ !(relative in files) &&
37
+ (await exists(join(root, relative)))) {
38
+ await remove(join(root, relative));
39
+ removed += 1;
40
+ }
41
+ }
42
+ await saveState({ ...state, versionId: version?.id ?? state.versionId });
43
+ io.out(`Pulled ${written} ${written === 1 ? 'file' : 'files'} of "${key}"${version ? ` at version ${version.number}` : ''}${removed > 0 ? `, and removed ${removed} the site no longer has` : ''}.`);
44
+ if (skipped !== null) {
45
+ io.out(`${skipped} is built from src/${skipped} here, so it was skipped. Use --all to take the site's.`);
46
+ }
47
+ return 0;
48
+ }
@@ -0,0 +1,35 @@
1
+ import { ApiFailed } from '../../lib/api.js';
2
+ import { flag, has } from '../../lib/args.js';
3
+ import { problemLines } from '../../lib/problems.js';
4
+ import { conflictLine, currentOf } from '../../lib/versions.js';
5
+ import { project } from '../context.js';
6
+ import { check } from './check.js';
7
+ import { buildFirst, filesIn } from './sync.js';
8
+ /** Save the folder's files as a version. */
9
+ export async function push(parsed, io) {
10
+ if (has(parsed, 'check')) {
11
+ return check(parsed, io);
12
+ }
13
+ const { api, config, state, root, saveState } = await project(io);
14
+ await buildFirst(root, io, has(parsed, 'no-build'));
15
+ const base = has(parsed, 'force') ? null : state.versionId;
16
+ try {
17
+ const theme = await api.save(config.theme, await filesIn(root), flag(parsed, 'note'), base);
18
+ await saveState({ ...state, versionId: theme.version?.id ?? null });
19
+ io.out(`Pushed as version ${theme.version?.number ?? '?'} of "${theme.name}".${theme.chosen ? ' The site shows it now.' : ''}`);
20
+ return 0;
21
+ }
22
+ catch (error) {
23
+ if (error instanceof ApiFailed && error.status === 409) {
24
+ io.err(conflictLine(currentOf(error.body)));
25
+ return 1;
26
+ }
27
+ if (error instanceof ApiFailed && error.status === 422) {
28
+ for (const line of problemLines(error.errors)) {
29
+ io.err(line);
30
+ }
31
+ return 1;
32
+ }
33
+ throw error;
34
+ }
35
+ }
@@ -0,0 +1,37 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { exists, readText, walk } from '../../io/fs.js';
4
+ import { detectPackageManager, hasScript, runScript, } from '../../lib/scripts.js';
5
+ import { collect } from '../../lib/theme-files.js';
6
+ import { Refused } from '../context.js';
7
+ /** The theme files a folder holds now. */
8
+ export async function filesIn(root) {
9
+ return collect(await walk(root));
10
+ }
11
+ /** Whether a folder has a script by name, and how to run it. */
12
+ export async function scriptIn(root, name, io) {
13
+ if (!hasScript(await readText(join(root, 'package.json')), name)) {
14
+ return null;
15
+ }
16
+ const manager = detectPackageManager((p) => existsSync(join(root, p)), io.env.npm_config_user_agent ?? '');
17
+ return runScript(manager, name);
18
+ }
19
+ /** Run the folder's `build` script when it has one, unless told not to. */
20
+ export async function buildFirst(root, io, skip) {
21
+ if (skip) {
22
+ return;
23
+ }
24
+ const script = await scriptIn(root, 'build', io);
25
+ if (script === null) {
26
+ return;
27
+ }
28
+ const [command, args] = script;
29
+ io.out(`Running ${command} ${args.join(' ')}…`);
30
+ const code = await io.run(command, args, root);
31
+ if (code !== 0) {
32
+ throw new Refused('The build failed; nothing was sent.');
33
+ }
34
+ }
35
+ export async function hasSource(root) {
36
+ return exists(join(root, 'src', 'theme.css'));
37
+ }