@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/dist/index.js ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import { Refused } from './commands/context.js';
3
+ import { login, logout, whoami } from './commands/login.js';
4
+ import { check } from './commands/theme/check.js';
5
+ import { dev } from './commands/theme/dev.js';
6
+ import { init } from './commands/theme/init.js';
7
+ import { list } from './commands/theme/list.js';
8
+ import { open } from './commands/theme/open.js';
9
+ import { publish } from './commands/theme/publish.js';
10
+ import { pull } from './commands/theme/pull.js';
11
+ import { push } from './commands/theme/push.js';
12
+ import { ApiFailed } from './lib/api.js';
13
+ import { has, parse, USAGE } from './lib/args.js';
14
+ import { problemLines } from './lib/problems.js';
15
+ const VERSION = '0.1.0';
16
+ const COMMANDS = {
17
+ login,
18
+ logout,
19
+ whoami,
20
+ 'theme init': init,
21
+ 'theme list': list,
22
+ 'theme pull': pull,
23
+ 'theme check': check,
24
+ 'theme push': push,
25
+ 'theme dev': dev,
26
+ 'theme publish': publish,
27
+ 'theme open': open,
28
+ };
29
+ /** Run the CLI with the given arguments against the given world; answers the exit code. */
30
+ export async function main(argv, io) {
31
+ if (argv.includes('--version') || argv.includes('-v')) {
32
+ io.out(VERSION);
33
+ return 0;
34
+ }
35
+ const parsed = parse(argv);
36
+ if ('error' in parsed) {
37
+ io.err(parsed.error);
38
+ io.err(USAGE);
39
+ return 2;
40
+ }
41
+ const name = parsed.command.join(' ');
42
+ const command = COMMANDS[name];
43
+ if (command === undefined || has(parsed, 'help')) {
44
+ io.out(USAGE);
45
+ return command === undefined && name !== '' && !has(parsed, 'help')
46
+ ? 2
47
+ : 0;
48
+ }
49
+ try {
50
+ return await command(parsed, io);
51
+ }
52
+ catch (error) {
53
+ if (error instanceof Refused) {
54
+ io.err(error.message);
55
+ return 1;
56
+ }
57
+ if (error instanceof ApiFailed) {
58
+ io.err(error.message);
59
+ for (const line of problemLines(error.errors)) {
60
+ io.err(line);
61
+ }
62
+ if (error.status === 401) {
63
+ io.err('Run cabin login.');
64
+ }
65
+ return 1;
66
+ }
67
+ io.err(error instanceof Error ? error.message : String(error));
68
+ return 1;
69
+ }
70
+ }
71
+ const runAsScript = process.argv[1] !== undefined &&
72
+ /index\.js$/.test(process.argv[1]) &&
73
+ import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/'));
74
+ if (runAsScript) {
75
+ const { world } = await import('./io/world.js');
76
+ process.exitCode = await main(process.argv.slice(2), world());
77
+ }
package/dist/io/fs.js ADDED
@@ -0,0 +1,55 @@
1
+ import { mkdir, readdir, readFile, rm, stat, writeFile, } from 'node:fs/promises';
2
+ import { dirname, join, relative } from 'node:path';
3
+ import { isSkipped, toThemePath } from '../lib/theme-files.js';
4
+ /** Read a text file, or null when it isn't there. */
5
+ export async function readText(path) {
6
+ try {
7
+ return await readFile(path, 'utf8');
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ }
13
+ export async function writeText(path, contents, mode) {
14
+ await mkdir(dirname(path), { recursive: true });
15
+ await writeFile(path, contents, mode === undefined ? { encoding: 'utf8' } : { encoding: 'utf8', mode });
16
+ }
17
+ export async function exists(path) {
18
+ try {
19
+ await stat(path);
20
+ return true;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ }
26
+ export async function remove(path) {
27
+ await rm(path, { force: true });
28
+ }
29
+ /**
30
+ * Every text file under a folder, as [relative path, contents], leaving
31
+ * the folders that are never synced.
32
+ */
33
+ export async function walk(root) {
34
+ const found = [];
35
+ async function visit(folder) {
36
+ const entries = await readdir(folder, { withFileTypes: true });
37
+ for (const entry of entries) {
38
+ const path = join(folder, entry.name);
39
+ const rel = toThemePath(relative(root, path));
40
+ if (isSkipped(rel)) {
41
+ continue;
42
+ }
43
+ if (entry.isDirectory()) {
44
+ await visit(path);
45
+ }
46
+ else if (entry.isFile()) {
47
+ found.push([rel, await readFile(path, 'utf8')]);
48
+ }
49
+ }
50
+ }
51
+ if (await exists(root)) {
52
+ await visit(root);
53
+ }
54
+ return found;
55
+ }
package/dist/io/io.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,62 @@
1
+ import { spawn as nodeSpawn } from 'node:child_process';
2
+ import { homedir } from 'node:os';
3
+ import { createInterface } from 'node:readline/promises';
4
+ /** The real world, for `cabin` run from a terminal. */
5
+ export function world() {
6
+ let stop = () => { };
7
+ const stopped = new Promise((resolve) => {
8
+ stop = resolve;
9
+ });
10
+ for (const signal of ['SIGINT', 'SIGTERM']) {
11
+ process.once(signal, () => stop());
12
+ }
13
+ return {
14
+ cwd: process.cwd(),
15
+ home: homedir(),
16
+ env: process.env,
17
+ isTTY: process.stdout.isTTY === true,
18
+ out: (line) => process.stdout.write(`${line}\n`),
19
+ err: (line) => process.stderr.write(`${line}\n`),
20
+ fetch: globalThis.fetch,
21
+ prompt: async (question) => {
22
+ const rl = createInterface({
23
+ input: process.stdin,
24
+ output: process.stdout,
25
+ });
26
+ try {
27
+ return (await rl.question(question)).trim();
28
+ }
29
+ finally {
30
+ rl.close();
31
+ }
32
+ },
33
+ spawn: (command, args, cwd) => nodeSpawn(command, args, {
34
+ cwd,
35
+ stdio: 'inherit',
36
+ shell: process.platform === 'win32',
37
+ }),
38
+ run: (command, args, cwd) => new Promise((resolve) => {
39
+ const child = nodeSpawn(command, args, {
40
+ cwd,
41
+ stdio: 'inherit',
42
+ shell: process.platform === 'win32',
43
+ });
44
+ child.on('exit', (code) => resolve(code ?? 1));
45
+ child.on('error', () => resolve(1));
46
+ }),
47
+ open: async (url) => {
48
+ const [command, args] = process.platform === 'darwin'
49
+ ? ['open', [url]]
50
+ : process.platform === 'win32'
51
+ ? ['cmd', ['/c', 'start', '', url]]
52
+ : ['xdg-open', [url]];
53
+ nodeSpawn(command, args, {
54
+ stdio: 'ignore',
55
+ detached: true,
56
+ }).unref();
57
+ },
58
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
59
+ now: () => Date.now(),
60
+ stopped,
61
+ };
62
+ }
@@ -0,0 +1,116 @@
1
+ /** What the server refused, in its one shape. */
2
+ export class ApiFailed extends Error {
3
+ status;
4
+ code;
5
+ errors;
6
+ body;
7
+ constructor(status, code, message, errors = {}, body = null) {
8
+ super(message);
9
+ this.status = status;
10
+ this.code = code;
11
+ this.errors = errors;
12
+ this.body = body;
13
+ }
14
+ }
15
+ /** Read a failure from what the server answered, whatever it was. */
16
+ export function failureOf(status, body) {
17
+ const error = body?.error;
18
+ if (typeof error === 'object' && error !== null) {
19
+ const errors = typeof error.errors === 'object' && error.errors !== null
20
+ ? error.errors
21
+ : {};
22
+ return new ApiFailed(status, typeof error.code === 'string' ? error.code : 'http_error', typeof error.message === 'string'
23
+ ? error.message
24
+ : `The server answered ${status}.`, errors, error);
25
+ }
26
+ if (status === 0) {
27
+ return new ApiFailed(0, 'unreachable', "The server couldn't be reached.");
28
+ }
29
+ return new ApiFailed(status, 'http_error', `The server answered ${status}.`);
30
+ }
31
+ /**
32
+ * The content API as the CLI calls it: one method per endpoint, each
33
+ * answering the `data` of a 2xx and throwing an `ApiFailed` otherwise.
34
+ */
35
+ export class ApiClient {
36
+ host;
37
+ token;
38
+ fetchFn;
39
+ constructor(host, token, fetchFn) {
40
+ this.host = host;
41
+ this.token = token;
42
+ this.fetchFn = fetchFn;
43
+ }
44
+ token_() {
45
+ return this.call('GET', '/v1/token');
46
+ }
47
+ themes() {
48
+ return this.call('GET', '/v1/themes');
49
+ }
50
+ sources() {
51
+ return this.call('GET', '/v1/themes/sources');
52
+ }
53
+ theme(key) {
54
+ return this.call('GET', `/v1/themes/${key}`);
55
+ }
56
+ create(key, name, from) {
57
+ return this.call('POST', '/v1/themes', { key, name, from });
58
+ }
59
+ save(key, files, note, baseVersion) {
60
+ return this.call('PUT', `/v1/themes/${key}`, {
61
+ files,
62
+ note,
63
+ base_version: baseVersion,
64
+ });
65
+ }
66
+ check(key, files) {
67
+ return this.call('POST', `/v1/themes/${key}/check`, { files });
68
+ }
69
+ draft(key, files, path, token) {
70
+ return this.call('POST', `/v1/themes/${key}/drafts`, {
71
+ files,
72
+ path,
73
+ token,
74
+ });
75
+ }
76
+ choose(key) {
77
+ return this.call('POST', `/v1/themes/${key}/choose`);
78
+ }
79
+ version(key, id) {
80
+ return this.call('GET', `/v1/themes/${key}/versions/${id}`);
81
+ }
82
+ async call(method, path, body) {
83
+ let response;
84
+ try {
85
+ const init = {
86
+ method,
87
+ headers: {
88
+ Authorization: `Bearer ${this.token}`,
89
+ Accept: 'application/json',
90
+ ...(body === undefined
91
+ ? {}
92
+ : { 'Content-Type': 'application/json' }),
93
+ },
94
+ };
95
+ if (body !== undefined) {
96
+ init.body = JSON.stringify(body);
97
+ }
98
+ response = await this.fetchFn(`${this.host}${path}`, init);
99
+ }
100
+ catch {
101
+ throw failureOf(0, null);
102
+ }
103
+ const text = await response.text();
104
+ let parsed = null;
105
+ try {
106
+ parsed = text === '' ? null : JSON.parse(text);
107
+ }
108
+ catch {
109
+ parsed = null;
110
+ }
111
+ if (!response.ok) {
112
+ throw failureOf(response.status, parsed);
113
+ }
114
+ return parsed.data;
115
+ }
116
+ }
@@ -0,0 +1,76 @@
1
+ import { parseArgs } from 'node:util';
2
+ const OPTIONS = {
3
+ host: { type: 'string' },
4
+ token: { type: 'string' },
5
+ site: { type: 'string' },
6
+ theme: { type: 'string' },
7
+ from: { type: 'string' },
8
+ name: { type: 'string' },
9
+ key: { type: 'string' },
10
+ note: { type: 'string' },
11
+ path: { type: 'string' },
12
+ version: { type: 'string' },
13
+ 'no-tailwind': { type: 'boolean' },
14
+ 'no-build': { type: 'boolean' },
15
+ force: { type: 'boolean' },
16
+ check: { type: 'boolean' },
17
+ all: { type: 'boolean' },
18
+ help: { type: 'boolean', short: 'h' },
19
+ };
20
+ /** Read the command words and flags from argv. */
21
+ export function parse(argv) {
22
+ try {
23
+ const { values, positionals } = parseArgs({
24
+ args: argv,
25
+ options: OPTIONS,
26
+ allowPositionals: true,
27
+ strict: true,
28
+ });
29
+ const words = [];
30
+ const rest = [];
31
+ for (const positional of positionals) {
32
+ if (rest.length === 0 &&
33
+ words.length < 2 &&
34
+ /^[a-z]+$/.test(positional) &&
35
+ (words.length === 0 || words[0] === 'theme')) {
36
+ words.push(positional);
37
+ }
38
+ else {
39
+ rest.push(positional);
40
+ }
41
+ }
42
+ return {
43
+ command: words,
44
+ flags: values,
45
+ positionals: rest,
46
+ };
47
+ }
48
+ catch (error) {
49
+ return {
50
+ error: error instanceof Error ? error.message : String(error),
51
+ };
52
+ }
53
+ }
54
+ export function flag(parsed, name) {
55
+ const value = parsed.flags[name];
56
+ return typeof value === 'string' && value !== '' ? value : null;
57
+ }
58
+ export function has(parsed, name) {
59
+ return parsed.flags[name] === true;
60
+ }
61
+ export const USAGE = `cabin — develop a Cabin site theme locally
62
+
63
+ cabin login [--host URL] [--token cabin_…]
64
+ cabin logout [--host URL] [--site handle]
65
+ cabin whoami
66
+
67
+ cabin theme init <dir> [--from blank|birch] [--name NAME] [--key KEY] [--no-tailwind] [--host URL] [--site handle]
68
+ cabin theme list
69
+ cabin theme pull [--theme KEY] [--version ID] [--all]
70
+ cabin theme check [--no-build]
71
+ cabin theme push [--note NOTE] [--force] [--check] [--no-build]
72
+ cabin theme dev [--path /] [--no-build]
73
+ cabin theme publish
74
+ cabin theme open [--site]
75
+
76
+ Exit codes: 0 done, 1 refused or problems found, 2 usage.`;
@@ -0,0 +1,73 @@
1
+ export const CONFIG_FILE = 'cabin.json';
2
+ export const STATE_FILE = '.cabin/state.json';
3
+ /** A host as the config keeps it: scheme and host, no path, no trailing slash. */
4
+ export function normalizeHost(host) {
5
+ const trimmed = host.trim();
6
+ if (trimmed === '') {
7
+ return null;
8
+ }
9
+ try {
10
+ const url = new URL(/^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`);
11
+ return `${url.protocol}//${url.host}`;
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ /** Read a project config, or say what is wrong with it. */
18
+ export function parseConfig(json) {
19
+ let parsed;
20
+ try {
21
+ parsed = JSON.parse(json);
22
+ }
23
+ catch {
24
+ return { error: `${CONFIG_FILE} isn't JSON.` };
25
+ }
26
+ if (typeof parsed !== 'object' || parsed === null) {
27
+ return {
28
+ error: `${CONFIG_FILE} should hold an object with host, site and theme.`,
29
+ };
30
+ }
31
+ const config = parsed;
32
+ const host = typeof config.host === 'string' ? normalizeHost(config.host) : null;
33
+ if (host === null) {
34
+ return {
35
+ error: `${CONFIG_FILE} needs a host, such as https://app.cabincms.com.`,
36
+ };
37
+ }
38
+ if (typeof config.site !== 'string' || config.site === '') {
39
+ return {
40
+ error: `${CONFIG_FILE} needs the site's handle under "site".`,
41
+ };
42
+ }
43
+ if (typeof config.theme !== 'string' || config.theme === '') {
44
+ return { error: `${CONFIG_FILE} needs the theme's key under "theme".` };
45
+ }
46
+ return { host, site: config.site, theme: config.theme };
47
+ }
48
+ export function serializeConfig(config) {
49
+ return `${JSON.stringify(config, null, 4)}\n`;
50
+ }
51
+ /** Read the remembered state; anything unreadable reads as nothing remembered. */
52
+ export function parseState(json) {
53
+ const none = { versionId: null, draftToken: null };
54
+ if (json === null) {
55
+ return none;
56
+ }
57
+ try {
58
+ const parsed = JSON.parse(json);
59
+ return {
60
+ versionId: typeof parsed.versionId === 'number' ? parsed.versionId : null,
61
+ draftToken: typeof parsed.draftToken === 'string' &&
62
+ /^[A-Za-z0-9]{32}$/.test(parsed.draftToken)
63
+ ? parsed.draftToken
64
+ : null,
65
+ };
66
+ }
67
+ catch {
68
+ return none;
69
+ }
70
+ }
71
+ export function serializeState(state) {
72
+ return `${JSON.stringify(state, null, 4)}\n`;
73
+ }
@@ -0,0 +1,56 @@
1
+ /** Where the credentials file lives: the environment decides, else the home folder. */
2
+ export function credentialsDir(env, home) {
3
+ if (env.CABIN_CONFIG_DIR) {
4
+ return env.CABIN_CONFIG_DIR;
5
+ }
6
+ if (env.XDG_CONFIG_HOME) {
7
+ return `${env.XDG_CONFIG_HOME}/cabin`;
8
+ }
9
+ return `${home}/.config/cabin`;
10
+ }
11
+ export function parseCredentials(json) {
12
+ if (json === null) {
13
+ return { hosts: {} };
14
+ }
15
+ try {
16
+ const parsed = JSON.parse(json);
17
+ return {
18
+ hosts: typeof parsed.hosts === 'object' && parsed.hosts !== null
19
+ ? parsed.hosts
20
+ : {},
21
+ };
22
+ }
23
+ catch {
24
+ return { hosts: {} };
25
+ }
26
+ }
27
+ export function serializeCredentials(credentials) {
28
+ return `${JSON.stringify(credentials, null, 4)}\n`;
29
+ }
30
+ export function pick(credentials, host, site) {
31
+ return credentials.hosts[host]?.[site] ?? null;
32
+ }
33
+ export function put(credentials, host, site, credential) {
34
+ return {
35
+ hosts: {
36
+ ...credentials.hosts,
37
+ [host]: { ...(credentials.hosts[host] ?? {}), [site]: credential },
38
+ },
39
+ };
40
+ }
41
+ export function drop(credentials, host, site) {
42
+ const forHost = { ...(credentials.hosts[host] ?? {}) };
43
+ delete forHost[site];
44
+ const hosts = { ...credentials.hosts };
45
+ if (Object.keys(forHost).length === 0) {
46
+ delete hosts[host];
47
+ }
48
+ else {
49
+ hosts[host] = forHost;
50
+ }
51
+ return { hosts };
52
+ }
53
+ /** Whether a string looks like one of Cabin's tokens. */
54
+ export function looksLikeToken(token) {
55
+ return /^cabin_[A-Za-z0-9]{40}$/.test(token.trim());
56
+ }
@@ -0,0 +1,33 @@
1
+ import { styleText } from 'node:util';
2
+ /** Colour a line when the output is a terminal that wants it. */
3
+ export function paint(text, color, wants) {
4
+ if (!wants) {
5
+ return text;
6
+ }
7
+ return styleText(color === 'dim' ? 'dim' : color, text);
8
+ }
9
+ /** Whether to colour output: a terminal, and nothing saying not to. */
10
+ export function wantsColor(isTTY, env) {
11
+ return isTTY && !env.NO_COLOR && env.TERM !== 'dumb';
12
+ }
13
+ /** The line that says a sync landed. */
14
+ export function syncedLine(at, count) {
15
+ const time = at.toTimeString().slice(0, 8);
16
+ return `synced ${time} (${count} ${count === 1 ? 'file' : 'files'})`;
17
+ }
18
+ /** A list of themes as `theme list` prints it. */
19
+ export function themeTable(rows) {
20
+ if (rows.length === 0) {
21
+ return [
22
+ "No themes of this site's own yet. Make one with cabin theme init.",
23
+ ];
24
+ }
25
+ const width = Math.max(...rows.map((r) => r.key.length));
26
+ return rows.map((row) => {
27
+ const star = row.chosen ? '*' : ' ';
28
+ const version = row.version === null ? 'no version' : `v${row.version}`;
29
+ const by = row.by === null ? '' : ` by ${row.by}`;
30
+ const at = row.at === null ? '' : ` ${row.at.slice(0, 10)}`;
31
+ return `${star} ${row.key.padEnd(width)} ${row.name} ${version}${by}${at}`;
32
+ });
33
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Problems as the server keys them, said one to a line the way the admin's
3
+ * Theme files screen says them: `templates/home.twig:12 message`, and
4
+ * `theme: message` for a problem with the whole set.
5
+ */
6
+ export function problemLines(errors) {
7
+ const lines = [];
8
+ for (const [key, messages] of Object.entries(errors)) {
9
+ for (const message of messages) {
10
+ lines.push(problemLine(key, message));
11
+ }
12
+ }
13
+ return lines;
14
+ }
15
+ export function problemLine(key, message) {
16
+ if (key === 'files') {
17
+ return `theme: ${message}`;
18
+ }
19
+ if (key.startsWith('files.')) {
20
+ const path = key.slice(6);
21
+ const line = /^Line (\d+): (.*)$/s.exec(message);
22
+ return line ? `${path}:${line[1]} ${line[2]}` : `${path} ${message}`;
23
+ }
24
+ return `${key}: ${message}`;
25
+ }
@@ -0,0 +1,72 @@
1
+ /** What the Tailwind scaffold puts in the theme's `package.json`. */
2
+ export function packageJson(key) {
3
+ return `${JSON.stringify({
4
+ name: `${key}-theme`,
5
+ private: true,
6
+ type: 'module',
7
+ scripts: {
8
+ dev: 'tailwindcss -i src/theme.css -o theme.css --watch',
9
+ build: 'tailwindcss -i src/theme.css -o theme.css --minify',
10
+ },
11
+ devDependencies: {
12
+ '@tailwindcss/cli': '^4.1.0',
13
+ tailwindcss: '^4.1.0',
14
+ },
15
+ }, null, 4)}\n`;
16
+ }
17
+ /**
18
+ * The stylesheet's source with Tailwind: its theme and utilities, not its
19
+ * preflight, so the stylesheet as pulled keeps its look, inside the base
20
+ * layer so utilities written in templates win.
21
+ */
22
+ export function tailwindSource(pulledCss) {
23
+ return [
24
+ '/* theme.css is built from this file: `cabin theme dev` and `cabin theme push`',
25
+ " run the scripts in package.json, which write it. Tailwind's theme and",
26
+ " utilities are included; its preflight isn't, so the styles below stay as",
27
+ " they were. Cabin sets the site's colours and fonts as CSS variables:",
28
+ ' --cabin-accent, --cabin-background, --cabin-text, --cabin-font-body, ...',
29
+ " The built file has to pass Cabin's stylesheet rules: no @import, no url()",
30
+ ' to another host, no data: URLs, and at most 256 KB. */',
31
+ '@layer theme, base, components, utilities;',
32
+ '@import "tailwindcss/theme.css" layer(theme);',
33
+ '@import "tailwindcss/utilities.css" layer(utilities);',
34
+ '@source "../templates";',
35
+ '',
36
+ '@layer base {',
37
+ pulledCss.trimEnd(),
38
+ '}',
39
+ '',
40
+ ].join('\n');
41
+ }
42
+ /**
43
+ * The files a new theme's folder gets: what the site answered, then
44
+ * `cabin.json`, `.gitignore`, and, with Tailwind, `package.json` and the
45
+ * stylesheet's source. `theme.css` as pulled stays, so the folder is a
46
+ * whole theme before the first build.
47
+ */
48
+ export function scaffold(config, files, options) {
49
+ const out = Object.entries(files).map(([path, contents]) => ({
50
+ path,
51
+ contents,
52
+ }));
53
+ out.push({
54
+ path: 'cabin.json',
55
+ contents: `${JSON.stringify(config, null, 4)}\n`,
56
+ });
57
+ if (options.tailwind) {
58
+ out.push({ path: 'package.json', contents: packageJson(config.theme) });
59
+ out.push({
60
+ path: 'src/theme.css',
61
+ contents: tailwindSource(files['theme.css'] ?? ''),
62
+ });
63
+ out.push({
64
+ path: '.gitignore',
65
+ contents: 'node_modules\n.cabin\ntheme.css\n',
66
+ });
67
+ }
68
+ else {
69
+ out.push({ path: '.gitignore', contents: '.cabin\n' });
70
+ }
71
+ return out;
72
+ }
@@ -0,0 +1,36 @@
1
+ /** Which package manager runs a folder's scripts, from what the folder holds. */
2
+ export function detectPackageManager(folderHas, userAgent = '') {
3
+ if (folderHas('pnpm-lock.yaml')) {
4
+ return 'pnpm';
5
+ }
6
+ if (folderHas('yarn.lock')) {
7
+ return 'yarn';
8
+ }
9
+ if (folderHas('bun.lock') || folderHas('bun.lockb')) {
10
+ return 'bun';
11
+ }
12
+ if (folderHas('package-lock.json')) {
13
+ return 'npm';
14
+ }
15
+ const [name] = userAgent.split('/');
16
+ return name === 'pnpm' || name === 'yarn' || name === 'bun' ? name : 'npm';
17
+ }
18
+ /** Whether a folder's package.json has a script, from its contents. */
19
+ export function hasScript(packageJson, name) {
20
+ if (packageJson === null) {
21
+ return false;
22
+ }
23
+ try {
24
+ const parsed = JSON.parse(packageJson);
25
+ return typeof parsed.scripts?.[name] === 'string';
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ /** The command and arguments that run a script. */
32
+ export function runScript(manager, script) {
33
+ return manager === 'npm'
34
+ ? ['npm', ['run', script]]
35
+ : [manager, ['run', script]];
36
+ }