@mycatalog/cli 0.0.0-stage → 0.1.1

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,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) MyCatalog
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.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @mycatalog/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
+ `mycatalog` is a Node.js 22+ command line tool for developing MyCatalog themes.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install --global @mycatalog/cli
9
+ mycatalog login
10
+ ```
11
+
12
+ Login uses the OAuth device flow. It displays a code and verification page, then asks before opening the browser. Use
13
+ `--open` to open the page immediately. Local development may use `--api-url http://localhost:3000
14
+ --insecure-localhost`; plain HTTP is limited to loopback hosts.
15
+
16
+ ## Commands
17
+
18
+ - `mycatalog login [--api-url URL] [--insecure-localhost] [--open]` — authenticate with the device flow.
19
+ - `mycatalog logout` — revoke the active token and remove local credentials.
20
+ - `mycatalog whoami` — show the authenticated account.
21
+ - `mycatalog theme init [directory]` — create folders, an example section, a locale, project config, and ignore file.
22
+ - `mycatalog theme list` — list your themes.
23
+ - `mycatalog theme push [--version ID] [--yes]` — show an upload summary, then upload files to a draft version.
24
+ - `mycatalog theme pull [--version ID] [--force]` — download sections, snippets, and downloadable assets safely.
25
+ - `mycatalog theme dev [--store ID]` — push once, print the store preview URL, then push on file changes.
26
+ - `mycatalog theme preview --store ID` — print a preview URL for a store you own.
27
+ - `mycatalog theme check` — run local folder, JSON, markup, CSS animation, and size checks.
28
+ - `mycatalog --help`, `mycatalog theme --help`, `mycatalog --version` — show usage or version.
29
+
30
+ Set `themeId`, `versionId`, and optionally `storeId` in the project's `mycatalog.json`. The file contains identifiers
31
+ only and cannot change the API host that receives credentials. Global `--json` enables machine-readable output;
32
+ `--verbose` is reserved for safe diagnostics.
33
+
34
+ ## Security
35
+
36
+ Credentials are stored in macOS Keychain or Linux Secret Service when available. Otherwise, they are stored in
37
+ `~/.config/mycatalog/tokens.json`, outside the project, with a 0600 file and 0700 directory. The CLI refuses fallback
38
+ credentials with wider permissions. Tokens are never command-line arguments or output. HTTPS is required except
39
+ explicitly enabled loopback development. Pull and push paths are limited to supported theme folders, extensions,
40
+ and size limits; dotfiles, ignored files, and symlinks are excluded. Server text is stripped of terminal controls.
41
+ The CLI has no telemetry and does not install or execute updates.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { login, logout } from "./core/auth.js";
4
+ import { Api } from "./core/api.js";
5
+ import * as theme from "./commands/theme/index.js";
6
+ import { print, redact } from "./core/output.js";
7
+ import { checkForUpdate } from "./core/update.js";
8
+ const VERSION = "0.1.1";
9
+ const HELP = `mycatalog <command>
10
+
11
+ Commands:
12
+ login [--api-url URL] [--insecure-localhost] [--open]
13
+ logout
14
+ whoami
15
+ theme init [directory]
16
+ theme list
17
+ theme push [--version ID] [--yes]
18
+ theme pull [--version ID] [--force]
19
+ theme dev [--store ID]
20
+ theme preview --store ID
21
+ theme check
22
+
23
+ Global options: --help --version --json --verbose`;
24
+ const THEME_HELP = `mycatalog theme <command>
25
+
26
+ Commands:
27
+ init [directory]
28
+ list
29
+ push [--version ID] [--yes]
30
+ pull [--version ID] [--force]
31
+ dev [--store ID]
32
+ preview --store ID
33
+ check`;
34
+ async function main() {
35
+ const args = process.argv.slice(2);
36
+ if (args[0] === "theme" && args.includes("--help")) {
37
+ console.log(THEME_HELP);
38
+ return;
39
+ }
40
+ if (!args.length || args.includes("--help")) {
41
+ console.log(HELP);
42
+ return;
43
+ }
44
+ if (args.includes("--version")) {
45
+ console.log(VERSION);
46
+ return;
47
+ }
48
+ const { values, positionals } = parseArgs({
49
+ args,
50
+ allowPositionals: true,
51
+ strict: false,
52
+ options: {
53
+ "api-url": { type: "string" },
54
+ "insecure-localhost": { type: "boolean" },
55
+ open: { type: "boolean" },
56
+ yes: { type: "boolean" },
57
+ force: { type: "boolean" },
58
+ version: { type: "string" },
59
+ store: { type: "string" },
60
+ json: { type: "boolean" },
61
+ verbose: { type: "boolean" },
62
+ },
63
+ });
64
+ const [command, subcommand, ...rest] = positionals;
65
+ const json = values.json === true;
66
+ if (command === "login") {
67
+ await login(typeof values["api-url"] === "string" ? values["api-url"] : undefined, values["insecure-localhost"] === true, values.open === true);
68
+ return;
69
+ }
70
+ if (command === "logout") {
71
+ await logout();
72
+ return;
73
+ }
74
+ if (command === "whoami") {
75
+ print(await (await Api.fromStore()).request("/api/cli/me"), json);
76
+ return;
77
+ }
78
+ if (command === "theme") {
79
+ if (subcommand === "init") {
80
+ await theme.init(rest[0]);
81
+ return;
82
+ }
83
+ if (subcommand === "check") {
84
+ await theme.check();
85
+ return;
86
+ }
87
+ if (subcommand === "push") {
88
+ await theme.push(typeof values.version === "string" ? values.version : undefined, values.yes === true);
89
+ return;
90
+ }
91
+ if (subcommand === "pull") {
92
+ await theme.pull(typeof values.version === "string" ? values.version : undefined, values.force === true);
93
+ return;
94
+ }
95
+ if (subcommand === "list") {
96
+ await theme.list();
97
+ return;
98
+ }
99
+ if (subcommand === "preview") {
100
+ await theme.preview(typeof values.store === "string" ? values.store : undefined);
101
+ return;
102
+ }
103
+ if (subcommand === "dev") {
104
+ await theme.dev(typeof values.store === "string" ? values.store : undefined);
105
+ return;
106
+ }
107
+ }
108
+ throw new Error(`Unknown command: ${command || ""} ${subcommand || ""}`);
109
+ }
110
+ main()
111
+ .then(() => (process.argv.includes("--json") ? undefined : checkForUpdate(VERSION)))
112
+ .catch((error) => {
113
+ const message = error instanceof Error ? error.message : error;
114
+ console.error(redact(message));
115
+ process.exitCode = 1;
116
+ });
@@ -0,0 +1,22 @@
1
+ /** Create a minimal theme folder and identifier-only project configuration. */
2
+ export declare function init(directory?: string): Promise<void>;
3
+ /** Check required folders, JSON, forbidden markup, animation prefixes, and byte limits locally. */
4
+ export declare function check(): Promise<void>;
5
+ /** Upload validated theme files to a draft version after showing the full upload summary. */
6
+ export declare function push(version?: string, yes?: boolean, only?: Set<string>): Promise<void>;
7
+ /** locales/<code>.json and locales/<code>.default.json → the platform's { default, locales } shape. */
8
+ export declare function localeBundle(files: {
9
+ path: string;
10
+ bytes: Buffer;
11
+ }[]): {
12
+ default: string;
13
+ locales: Record<string, unknown>;
14
+ };
15
+ /** List themes returned by the developer API. */
16
+ export declare function list(): Promise<void>;
17
+ /** Pull safe theme section files and preserve local edits unless --force is supplied. */
18
+ export declare function pull(version?: string, force?: boolean): Promise<void>;
19
+ /** Print a preview URL for the configured draft and an explicitly selected owned store. */
20
+ export declare function preview(store?: string): Promise<void>;
21
+ /** Push once and debounce subsequent file changes into draft uploads. */
22
+ export declare function dev(store?: string): Promise<void>;
@@ -0,0 +1,316 @@
1
+ import { constants } from "node:fs";
2
+ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { stdin, stdout } from "node:process";
6
+ import { Api } from "../../core/api.js";
7
+ import { loadConfig } from "../../core/config.js";
8
+ import { assertSafeTarget, DIRS, ignored, safeRelative, validateUpload } from "../../core/paths.js";
9
+ import { clean, print } from "../../core/output.js";
10
+ const API = "/api/developer/themes";
11
+ const FORBIDDEN = /<(?:script|form|input)\b|\bon\w+\s*=|\bstyle\s*=/i;
12
+ async function projectFiles(root = process.cwd()) {
13
+ const patterns = [];
14
+ for (const file of [".gitignore", ".mycatalogignore"]) {
15
+ try {
16
+ patterns.push(...(await readFile(join(root, file), "utf8")).split(/\r?\n/));
17
+ }
18
+ catch {
19
+ // Ignore files are optional.
20
+ }
21
+ }
22
+ const files = [];
23
+ for (const directory of DIRS) {
24
+ for (const entry of await readdir(join(root, directory), { withFileTypes: true }).catch(() => [])) {
25
+ const path = `${directory}/${entry.name}`;
26
+ if (!entry.isFile() || ignored(path, patterns)) {
27
+ continue;
28
+ }
29
+ const safe = safeRelative(path);
30
+ const bytes = await readFile(join(root, safe));
31
+ validateUpload(safe, bytes.length);
32
+ files.push({ path: safe, bytes });
33
+ }
34
+ }
35
+ return files;
36
+ }
37
+ function requireIds(config) {
38
+ if (!config.themeId || !config.versionId) {
39
+ throw new Error("Set themeId and versionId in mycatalog.json");
40
+ }
41
+ return { themeId: config.themeId, versionId: config.versionId };
42
+ }
43
+ function versionPath(themeId, versionId) {
44
+ return `${API}/${encodeURIComponent(themeId)}/versions/${encodeURIComponent(versionId)}`;
45
+ }
46
+ /** Create a minimal theme folder and identifier-only project configuration. */
47
+ export async function init(directory = ".") {
48
+ const root = resolve(directory);
49
+ for (const folder of DIRS) {
50
+ await mkdir(join(root, folder), { recursive: true });
51
+ }
52
+ await writeFile(join(root, "sections/example.liquid"), `<section><h2>{{ section.settings.heading }}</h2></section>\n{% schema %}\n` +
53
+ `{"name":"Example","settings":[{"id":"heading","type":"text","label":"Heading","default":"Hello"}]}\n{% endschema %}\n`);
54
+ await writeFile(join(root, "locales/en.default.json"), '{"general":{"hello":"Hello"}}\n');
55
+ await writeFile(join(root, "mycatalog.json"), '{\n "themeId": "",\n "versionId": "",\n "storeId": ""\n}\n');
56
+ await writeFile(join(root, ".mycatalogignore"), "# files not uploaded\n");
57
+ console.log(`Initialized theme in ${clean(root)}`);
58
+ }
59
+ /** Check required folders, JSON, forbidden markup, animation prefixes, and byte limits locally. */
60
+ export async function check() {
61
+ const errors = [];
62
+ for (const directory of DIRS) {
63
+ try {
64
+ if (!(await stat(directory)).isDirectory()) {
65
+ errors.push(`Missing folder ${directory}/`);
66
+ }
67
+ }
68
+ catch {
69
+ errors.push(`Missing folder ${directory}/`);
70
+ }
71
+ }
72
+ for (const file of await projectFiles()) {
73
+ const text = file.bytes.toString("utf8");
74
+ if (file.path.endsWith(".json")) {
75
+ try {
76
+ JSON.parse(text);
77
+ }
78
+ catch {
79
+ errors.push(`${file.path}: invalid JSON`);
80
+ }
81
+ }
82
+ if (FORBIDDEN.test(text)) {
83
+ errors.push(`${file.path}: forbidden markup`);
84
+ }
85
+ if (file.path.endsWith(".css") && /@keyframes\s+(?!theme-)[\w-]+/i.test(text)) {
86
+ errors.push(`${file.path}: @keyframes names must start with theme-`);
87
+ }
88
+ }
89
+ if (errors.length) {
90
+ throw new Error(errors.join("\n"));
91
+ }
92
+ console.log("Theme checks passed.");
93
+ }
94
+ async function confirmPush() {
95
+ if (!stdin.isTTY || !stdout.isTTY) {
96
+ return false;
97
+ }
98
+ const readline = createInterface({ input: stdin, output: stdout });
99
+ try {
100
+ return /^y(es)?$/i.test((await readline.question("Continue? [y/N] ")).trim());
101
+ }
102
+ finally {
103
+ readline.close();
104
+ }
105
+ }
106
+ /** Upload validated theme files to a draft version after showing the full upload summary. */
107
+ export async function push(version, yes = false, only) {
108
+ const ids = requireIds(await loadConfig());
109
+ const api = await Api.fromStore();
110
+ const all = await projectFiles();
111
+ // A changed section .css re-uploads its .liquid; any locale change re-sends all locales (one request).
112
+ const wanted = (path) => !only || only.has(path) ||
113
+ (path.endsWith(".liquid") && only.has(path.replace(/\.liquid$/, ".css"))) ||
114
+ (path.startsWith("locales/") && [...only].some((p) => p.startsWith("locales/")));
115
+ const files = all.filter((file) => wanted(file.path));
116
+ if (!files.length)
117
+ return;
118
+ const selectedVersion = version || ids.versionId;
119
+ console.log(`Uploading ${files.length} files to theme ${ids.themeId}, version ${selectedVersion}:\n` +
120
+ files.map((file) => ` ${file.path} (${file.bytes.length} bytes)`).join("\n"));
121
+ if (!yes && !await confirmPush()) {
122
+ return;
123
+ }
124
+ const base = versionPath(ids.themeId, selectedVersion);
125
+ for (const file of files) {
126
+ if (file.path.startsWith("sections/")) {
127
+ await pushSection(api, base, file, files);
128
+ }
129
+ else if (file.path.startsWith("snippets/")) {
130
+ await api.request(`${base}/snippets`, {
131
+ method: "PUT",
132
+ headers: { "content-type": "application/json" },
133
+ body: JSON.stringify({
134
+ name: file.path.slice("snippets/".length).replace(/\.liquid$/, ""),
135
+ source: file.bytes.toString("utf8"),
136
+ }),
137
+ });
138
+ }
139
+ else if (file.path.startsWith("assets/")) {
140
+ const form = new FormData();
141
+ form.set("file", new Blob([new Uint8Array(file.bytes)]), file.path.slice("assets/".length));
142
+ await api.request(`${base}/assets`, { method: "POST", body: form });
143
+ }
144
+ }
145
+ const localeFiles = all.filter((file) => file.path.startsWith("locales/"));
146
+ if (files.some((file) => file.path.startsWith("locales/"))) {
147
+ await api.request(`${base}/locales`, {
148
+ method: "PUT",
149
+ headers: { "content-type": "application/json" },
150
+ body: JSON.stringify({ locales: localeBundle(localeFiles) }),
151
+ });
152
+ }
153
+ console.log(`Uploaded ${files.length} files.`);
154
+ }
155
+ /** locales/<code>.json and locales/<code>.default.json → the platform's { default, locales } shape. */
156
+ export function localeBundle(files) {
157
+ const locales = {};
158
+ let fallback;
159
+ for (const file of files) {
160
+ const match = /^locales\/(.+?)(\.default)?\.json$/.exec(file.path);
161
+ if (!match)
162
+ continue;
163
+ try {
164
+ locales[match[1]] = JSON.parse(file.bytes.toString("utf8"));
165
+ }
166
+ catch {
167
+ throw new Error(`${file.path} is not valid JSON`);
168
+ }
169
+ if (match[2])
170
+ fallback = match[1];
171
+ }
172
+ const codes = Object.keys(locales);
173
+ return { default: fallback ?? (codes.includes("en") ? "en" : codes[0]), locales };
174
+ }
175
+ async function pushSection(api, base, file, files) {
176
+ const name = file.path.slice("sections/".length);
177
+ if (!name.endsWith(".liquid")) {
178
+ return;
179
+ }
180
+ const source = file.bytes.toString("utf8");
181
+ const schemaMatch = /{%[-]?\s*schema\s*[-]?%}([\s\S]*?){%[-]?\s*endschema\s*[-]?%}/.exec(source);
182
+ let template = source;
183
+ let schema;
184
+ if (schemaMatch) {
185
+ template = (source.slice(0, schemaMatch.index) + source.slice(schemaMatch.index + schemaMatch[0].length)).trim() + "\n";
186
+ schema = JSON.parse(schemaMatch[1]);
187
+ }
188
+ else {
189
+ const sidecar = files.find((candidate) => candidate.path === `sections/${name.replace(/\.liquid$/, ".schema.json")}`);
190
+ if (!sidecar) {
191
+ throw new Error(`Missing schema for sections/${name}`);
192
+ }
193
+ schema = JSON.parse(sidecar.bytes.toString("utf8"));
194
+ }
195
+ const cssFile = files.find((candidate) => candidate.path === `sections/${name.replace(/\.liquid$/, ".css")}`);
196
+ await api.request(`${base}/sections/${encodeURIComponent(name.replace(/\.liquid$/, ""))}`, {
197
+ method: "PUT",
198
+ headers: { "content-type": "application/json" },
199
+ body: JSON.stringify({ template, schema, css: cssFile?.bytes.toString("utf8") ?? null }),
200
+ });
201
+ }
202
+ /** List themes returned by the developer API. */
203
+ export async function list() {
204
+ print(await (await Api.fromStore()).request(API));
205
+ }
206
+ /** Pull safe theme section files and preserve local edits unless --force is supplied. */
207
+ export async function pull(version, force = false) {
208
+ const ids = requireIds(await loadConfig());
209
+ const api = await Api.fromStore();
210
+ const selectedVersion = version || ids.versionId;
211
+ const base = versionPath(ids.themeId, selectedVersion);
212
+ const root = process.cwd();
213
+ const response = await api.request(`${base}/sections`);
214
+ for (const section of response.sections || []) {
215
+ const path = `sections/${section.handle}.liquid`;
216
+ const target = await assertSafeTarget(root, path);
217
+ const data = await api.request(`${base}/sections/${encodeURIComponent(section.handle)}`);
218
+ const stored = data.section;
219
+ let content = stored?.template || "";
220
+ if (stored?.schema) {
221
+ content += `\n{% schema %}\n${JSON.stringify(stored.schema, null, 2)}\n{% endschema %}\n`;
222
+ }
223
+ await writePulledFile(root, path, content, force);
224
+ if (stored?.css) {
225
+ await writePulledFile(root, `sections/${section.handle}.css`, stored.css, force);
226
+ }
227
+ }
228
+ const snippetList = await api.request(`${base}/snippets`);
229
+ for (const snippet of snippetList.snippets || []) {
230
+ const result = await api.request(`${base}/snippets?name=${encodeURIComponent(snippet.name)}`);
231
+ await writePulledFile(root, `snippets/${snippet.name}.liquid`, result.source, force);
232
+ }
233
+ const assetList = await api.request(`${base}/assets`);
234
+ for (const asset of assetList.assets || []) {
235
+ if (assetList.base) {
236
+ await assertSafeTarget(root, `assets/${asset.name}`);
237
+ const response = await fetch(`${assetList.base}/${encodeURIComponent(asset.name)}`, { signal: AbortSignal.timeout(30_000) });
238
+ if (!response.ok) {
239
+ throw new Error(`Could not download asset ${asset.name} (${response.status})`);
240
+ }
241
+ const bytes = Buffer.from(await response.arrayBuffer());
242
+ if (bytes.length > 2 * 1024 * 1024)
243
+ throw new Error(`Asset ${asset.name} is over 2 MB`);
244
+ await writePulledFile(root, `assets/${asset.name}`, bytes, force);
245
+ }
246
+ }
247
+ }
248
+ async function writePulledFile(root, path, contents, force) {
249
+ const target = await assertSafeTarget(root, path);
250
+ try {
251
+ const local = await readFile(target);
252
+ if (!force && !local.equals(Buffer.isBuffer(contents) ? contents : Buffer.from(contents))) {
253
+ throw new Error(`Refusing to overwrite changed ${path}; use --force`);
254
+ }
255
+ if (!force) {
256
+ return;
257
+ }
258
+ }
259
+ catch (error) {
260
+ if (error.code !== "ENOENT") {
261
+ throw error;
262
+ }
263
+ }
264
+ // O_NOFOLLOW: refuse a symlink swapped in after assertSafeTarget.
265
+ await writeFile(target, contents, {
266
+ flag: constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
267
+ mode: 0o644,
268
+ });
269
+ }
270
+ /** Print a preview URL for the configured draft and an explicitly selected owned store. */
271
+ export async function preview(store) {
272
+ const config = await loadConfig();
273
+ const ids = requireIds(config);
274
+ const storeId = store || config.storeId;
275
+ if (!storeId) {
276
+ throw new Error("Provide --store or set storeId in mycatalog.json");
277
+ }
278
+ const response = await (await Api.fromStore()).request(`${versionPath(ids.themeId, ids.versionId)}/preview`, {
279
+ method: "POST",
280
+ headers: { "content-type": "application/json" },
281
+ body: JSON.stringify({ storeId }),
282
+ });
283
+ if (typeof response.url !== "string") {
284
+ throw new Error("Preview response did not include a URL");
285
+ }
286
+ console.log(clean(response.url));
287
+ }
288
+ /** Push once and debounce subsequent file changes into draft uploads. */
289
+ export async function dev(store) {
290
+ await push(undefined, true);
291
+ await preview(store);
292
+ const { watch } = await import("node:fs");
293
+ let timer;
294
+ const changed = new Set();
295
+ watch(process.cwd(), { recursive: true }, (_event, name) => {
296
+ if (!name) {
297
+ return;
298
+ }
299
+ try {
300
+ safeRelative(String(name));
301
+ }
302
+ catch {
303
+ return;
304
+ }
305
+ changed.add(String(name).split("\\").join("/"));
306
+ clearTimeout(timer);
307
+ timer = setTimeout(() => {
308
+ const batch = new Set(changed);
309
+ changed.clear();
310
+ void push(undefined, true, batch).catch((error) => {
311
+ console.error(clean(error instanceof Error ? error.message : error));
312
+ });
313
+ }, 400);
314
+ });
315
+ console.log("Watching theme files. Press Ctrl+C to stop.");
316
+ }
@@ -0,0 +1,19 @@
1
+ import { type Tokens } from "./store.js";
2
+ /** Validate API hosts before credentials can be sent to them. */
3
+ export declare function apiBase(input?: string, insecureLocalhost?: boolean): string;
4
+ type RequestOptions = RequestInit & {
5
+ retryAuth?: boolean;
6
+ };
7
+ export declare class Api {
8
+ private tokens;
9
+ private base;
10
+ constructor(tokens: Tokens | null, base: string);
11
+ /** Load the fixed API host and credentials from the user credential store. */
12
+ static fromStore(): Promise<Api>;
13
+ /** Make authenticated requests with bounded retries and one refresh attempt. */
14
+ request(path: string, options?: RequestOptions): Promise<any>;
15
+ /** Rotate and persist credentials after an unauthorized request. */
16
+ refresh(): Promise<void>;
17
+ get baseUrl(): string;
18
+ }
19
+ export {};
@@ -0,0 +1,105 @@
1
+ import { loadTokens, saveTokens } from "./store.js";
2
+ import { clean, redact } from "./output.js";
3
+ /** Validate API hosts before credentials can be sent to them. */
4
+ export function apiBase(input, insecureLocalhost = false) {
5
+ const url = new URL(input || process.env.MYCATALOG_API_URL || "https://app.mycatalog.io");
6
+ const loopback = ["localhost", "127.0.0.1", "::1"].includes(url.hostname);
7
+ if (url.protocol !== "https:" && !(insecureLocalhost && url.protocol === "http:" && loopback)) {
8
+ throw new Error("API URL must use HTTPS (localhost requires --insecure-localhost)");
9
+ }
10
+ if (url.username || url.password || url.search || url.hash) {
11
+ throw new Error("API URL cannot contain credentials, query, or fragment");
12
+ }
13
+ return url.origin;
14
+ }
15
+ export class Api {
16
+ tokens;
17
+ base;
18
+ constructor(tokens, base) {
19
+ this.tokens = tokens;
20
+ this.base = base;
21
+ }
22
+ /** Load the fixed API host and credentials from the user credential store. */
23
+ static async fromStore() {
24
+ const tokens = await loadTokens();
25
+ if (!tokens) {
26
+ throw new Error("Not logged in. Run mycatalog login.");
27
+ }
28
+ return new Api(tokens, apiBase(tokens.api_url, tokens.api_url.startsWith("http://")));
29
+ }
30
+ /** Make authenticated requests with bounded retries and one refresh attempt. */
31
+ async request(path, options = {}) {
32
+ const { retryAuth = true, ...init } = options;
33
+ let response;
34
+ for (let attempt = 0;; attempt += 1) {
35
+ const headers = new Headers(init.headers);
36
+ headers.set("accept", "application/json");
37
+ if (this.tokens) {
38
+ headers.set("authorization", `Bearer ${this.tokens.access_token}`);
39
+ }
40
+ response = await fetch(new URL(path, this.base), {
41
+ ...init,
42
+ headers,
43
+ redirect: "error",
44
+ signal: AbortSignal.timeout(30_000),
45
+ });
46
+ if ((response.status === 429 || response.status >= 500) && attempt < 3) {
47
+ const retryAfter = Number(response.headers.get("retry-after"));
48
+ const delay = Number.isFinite(retryAfter) && retryAfter > 0
49
+ ? Math.min(5_000, retryAfter * 1_000)
50
+ : Math.min(5_000, 250 * 2 ** attempt);
51
+ await new Promise((resolve) => setTimeout(resolve, delay));
52
+ continue;
53
+ }
54
+ break;
55
+ }
56
+ if (response.status === 401 && this.tokens && retryAuth) {
57
+ await this.refresh();
58
+ return this.request(path, { ...init, retryAuth: false });
59
+ }
60
+ if (!response.ok) {
61
+ let message = `Request failed (${response.status})`;
62
+ try {
63
+ const body = await response.json();
64
+ if (typeof body.error === "string") {
65
+ message = clean(body.error);
66
+ }
67
+ }
68
+ catch {
69
+ // Keep the generic status message for non-JSON errors.
70
+ }
71
+ throw new Error(redact(message));
72
+ }
73
+ if (response.status === 204) {
74
+ return null;
75
+ }
76
+ return response.json();
77
+ }
78
+ /** Rotate and persist credentials after an unauthorized request. */
79
+ async refresh() {
80
+ if (!this.tokens) {
81
+ throw new Error("Not logged in");
82
+ }
83
+ const response = await fetch(new URL("/api/cli/token/refresh", this.base), {
84
+ method: "POST",
85
+ headers: { "content-type": "application/json" },
86
+ body: JSON.stringify({ refresh_token: this.tokens.refresh_token }),
87
+ redirect: "error",
88
+ signal: AbortSignal.timeout(30_000),
89
+ });
90
+ if (!response.ok) {
91
+ throw new Error("Session expired; run mycatalog login again");
92
+ }
93
+ const body = await response.json();
94
+ this.tokens = {
95
+ ...this.tokens,
96
+ access_token: body.access_token,
97
+ refresh_token: body.refresh_token,
98
+ expires_at: Date.now() + body.expires_in * 1_000,
99
+ };
100
+ await saveTokens(this.tokens);
101
+ }
102
+ get baseUrl() {
103
+ return this.base;
104
+ }
105
+ }
@@ -0,0 +1,4 @@
1
+ /** Run RFC 8628 device login and keep access and refresh credentials out of output. */
2
+ export declare function login(url?: string, insecure?: boolean, open?: boolean): Promise<void>;
3
+ /** Revoke the active server token and remove all local copies. */
4
+ export declare function logout(): Promise<void>;
@@ -0,0 +1,108 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { stdin, stdout } from "node:process";
3
+ import { spawn } from "node:child_process";
4
+ import { apiBase } from "./api.js";
5
+ import { deleteTokens, loadTokens, saveTokens } from "./store.js";
6
+ import { clean } from "./output.js";
7
+ /** Run RFC 8628 device login and keep access and refresh credentials out of output. */
8
+ export async function login(url, insecure = false, open = false) {
9
+ const base = apiBase(url, insecure);
10
+ const response = await fetch(new URL("/api/cli/device/code", base), {
11
+ method: "POST",
12
+ headers: { "content-type": "application/json" },
13
+ body: JSON.stringify({ client_id: "mycatalog-cli", scope: "themes:write" }),
14
+ redirect: "error",
15
+ signal: AbortSignal.timeout(30_000),
16
+ });
17
+ if (!response.ok) {
18
+ throw new Error("Device login could not be started");
19
+ }
20
+ const device = await response.json();
21
+ const verificationUrl = device.verification_uri_complete || device.verification_uri;
22
+ console.log(`Code: ${clean(device.user_code)}\nOpen: ${clean(verificationUrl)}`);
23
+ if (open || await confirmOpen()) {
24
+ openBrowser(verificationUrl);
25
+ }
26
+ let interval = Math.max(1, Number(device.interval) || 5);
27
+ const expiresAt = Date.now() + Number(device.expires_in) * 1_000;
28
+ while (Date.now() < expiresAt) {
29
+ await new Promise((resolve) => setTimeout(resolve, interval * 1_000));
30
+ const tokenResponse = await fetch(new URL("/api/cli/device/token", base), {
31
+ method: "POST",
32
+ headers: { "content-type": "application/json" },
33
+ body: JSON.stringify({
34
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
35
+ device_code: device.device_code,
36
+ client_id: "mycatalog-cli",
37
+ }),
38
+ redirect: "error",
39
+ signal: AbortSignal.timeout(30_000),
40
+ });
41
+ if (tokenResponse.ok) {
42
+ const tokens = await tokenResponse.json();
43
+ await saveTokens({
44
+ access_token: tokens.access_token,
45
+ refresh_token: tokens.refresh_token,
46
+ api_url: base,
47
+ expires_at: Date.now() + tokens.expires_in * 1_000,
48
+ });
49
+ console.log("Logged in.");
50
+ return;
51
+ }
52
+ const body = await tokenResponse.json().catch(() => ({}));
53
+ if (body.error === "authorization_pending") {
54
+ continue;
55
+ }
56
+ if (body.error === "slow_down") {
57
+ interval += 5;
58
+ continue;
59
+ }
60
+ if (body.error === "expired_token") {
61
+ throw new Error("Device code expired; run login again");
62
+ }
63
+ if (body.error === "access_denied") {
64
+ throw new Error("Login was denied");
65
+ }
66
+ throw new Error("Device login failed");
67
+ }
68
+ throw new Error("Device code expired; run login again");
69
+ }
70
+ async function confirmOpen() {
71
+ if (!stdin.isTTY || !stdout.isTTY) {
72
+ return false;
73
+ }
74
+ const readline = createInterface({ input: stdin, output: stdout });
75
+ try {
76
+ const answer = await readline.question("Open this page in your browser? [y/N] ");
77
+ return /^y(es)?$/i.test(answer.trim());
78
+ }
79
+ finally {
80
+ readline.close();
81
+ }
82
+ }
83
+ function openBrowser(url) {
84
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
85
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
86
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
87
+ }
88
+ /** Revoke the active server token and remove all local copies. */
89
+ export async function logout() {
90
+ const tokens = await loadTokens();
91
+ try {
92
+ if (tokens) {
93
+ const response = await fetch(new URL("/api/cli/token/revoke", tokens.api_url), {
94
+ method: "POST",
95
+ headers: { authorization: `Bearer ${tokens.access_token}` },
96
+ redirect: "error",
97
+ signal: AbortSignal.timeout(30_000),
98
+ });
99
+ if (!response.ok && response.status !== 401) {
100
+ throw new Error("Token revocation failed");
101
+ }
102
+ }
103
+ }
104
+ finally {
105
+ await deleteTokens();
106
+ }
107
+ console.log("Logged out.");
108
+ }
@@ -0,0 +1,9 @@
1
+ export type ProjectConfig = {
2
+ themeId?: string;
3
+ versionId?: string;
4
+ storeId?: string;
5
+ };
6
+ /** Load identifiers only; project config never controls the credential destination host. */
7
+ export declare function loadConfig(root?: string): Promise<ProjectConfig>;
8
+ /** Save project identifiers with restrictive permissions; never persist credentials here. */
9
+ export declare function saveConfig(value: ProjectConfig, root?: string): Promise<void>;
@@ -0,0 +1,36 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ const validId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
4
+ /** Load identifiers only; project config never controls the credential destination host. */
5
+ export async function loadConfig(root = process.cwd()) {
6
+ let raw;
7
+ try {
8
+ raw = JSON.parse(await readFile(resolve(root, "mycatalog.json"), "utf8"));
9
+ }
10
+ catch (error) {
11
+ if (error.code === "ENOENT") {
12
+ return {};
13
+ }
14
+ throw new Error("Could not read mycatalog.json");
15
+ }
16
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
17
+ throw new Error("Invalid mycatalog.json");
18
+ }
19
+ const input = raw;
20
+ const config = {};
21
+ for (const key of ["themeId", "versionId", "storeId"]) {
22
+ if (input[key] !== undefined) {
23
+ if (!validId(input[key])) {
24
+ throw new Error(`Invalid ${key} in mycatalog.json`);
25
+ }
26
+ config[key] = input[key];
27
+ }
28
+ }
29
+ return config;
30
+ }
31
+ /** Save project identifiers with restrictive permissions; never persist credentials here. */
32
+ export async function saveConfig(value, root = process.cwd()) {
33
+ await writeFile(resolve(root, "mycatalog.json"), `${JSON.stringify(value, null, 2)}\n`, {
34
+ mode: 0o600,
35
+ });
36
+ }
@@ -0,0 +1,6 @@
1
+ /** Remove terminal control bytes before displaying text supplied by the service. */
2
+ export declare function clean(value: unknown): string;
3
+ /** Redact token-shaped strings before errors or diagnostic output can expose them. */
4
+ export declare function redact(value: unknown): string;
5
+ /** Print JSON for automation or safe plain text for interactive use. */
6
+ export declare function print(value: unknown, json?: boolean): void;
@@ -0,0 +1,18 @@
1
+ /** Remove terminal control bytes before displaying text supplied by the service. */
2
+ export function clean(value) {
3
+ return String(value ?? "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "");
4
+ }
5
+ const TOKEN = new RegExp([
6
+ "\\bmc_[A-Za-z0-9_-]{12,}",
7
+ "\\b[A-Za-z0-9_-]{32,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}",
8
+ "\\b(?:access|refresh)[_-]?token[\"']?\\s*[:=]\\s*[\"']?",
9
+ ].map((part) => `(?:${part})`).join("|") + "[^\\s\"',}]*", "gi");
10
+ /** Redact token-shaped strings before errors or diagnostic output can expose them. */
11
+ export function redact(value) {
12
+ return clean(value).replace(TOKEN, "[REDACTED]");
13
+ }
14
+ /** Print JSON for automation or safe plain text for interactive use. */
15
+ export function print(value, json = false) {
16
+ const text = json ? JSON.stringify(value) : clean(typeof value === "string" ? value : JSON.stringify(value, null, 2));
17
+ console.log(redact(text));
18
+ }
@@ -0,0 +1,10 @@
1
+ export declare const DIRS: readonly ["sections", "snippets", "locales", "assets"];
2
+ export declare const limits: Record<string, number>;
3
+ /** Restrict local theme paths to supported, non-hidden files directly in allowed folders. */
4
+ export declare function safeRelative(path: string): string;
5
+ /** Check each existing path component with lstat before returning a pull destination. */
6
+ export declare function assertSafeTarget(root: string, relativePath: string): Promise<string>;
7
+ /** Match simple gitignore-style patterns used by .gitignore and .mycatalogignore. */
8
+ export declare function ignored(path: string, patterns: string[]): boolean;
9
+ /** Refuse unsupported files and enforce server-aligned byte limits before upload. */
10
+ export declare function validateUpload(path: string, size: number): void;
@@ -0,0 +1,88 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import { extname, join, resolve, sep } from "node:path";
3
+ export const DIRS = ["sections", "snippets", "locales", "assets"];
4
+ const allowed = {
5
+ sections: [".liquid", ".css", ".json"],
6
+ snippets: [".liquid"],
7
+ locales: [".json"],
8
+ assets: [".css", ".png", ".jpg", ".jpeg", ".webp", ".avif", ".gif", ".woff", ".woff2", ".ttf", ".otf", ".eot"],
9
+ };
10
+ export const limits = {
11
+ sections: 256 * 1024,
12
+ snippets: 64 * 1024,
13
+ locales: 256 * 1024,
14
+ assets: 2 * 1024 * 1024,
15
+ };
16
+ /** Restrict local theme paths to supported, non-hidden files directly in allowed folders. */
17
+ export function safeRelative(path) {
18
+ if (!path || path.includes("\0") || path.includes("\\") || path.startsWith("/")) {
19
+ throw new Error("Unsafe path");
20
+ }
21
+ if (/^[A-Za-z]:/.test(path)) {
22
+ throw new Error("Unsafe path");
23
+ }
24
+ const parts = path.split("/");
25
+ if (parts.some((part) => !part || part === "." || part === ".." || part.startsWith("."))) {
26
+ throw new Error("Unsafe path");
27
+ }
28
+ if (!DIRS.includes(parts[0]) || parts.length !== 2) {
29
+ throw new Error("Path must be directly under sections/, snippets/, locales/, or assets/");
30
+ }
31
+ const extension = extname(parts[1]).toLowerCase();
32
+ if (!allowed[parts[0]].includes(extension)) {
33
+ throw new Error("Unsupported theme file extension");
34
+ }
35
+ return parts.join("/");
36
+ }
37
+ /** Check each existing path component with lstat before returning a pull destination. */
38
+ export async function assertSafeTarget(root, relativePath) {
39
+ const safe = safeRelative(relativePath);
40
+ const base = await realpath(root);
41
+ const target = resolve(base, safe);
42
+ if (!target.startsWith(base + sep)) {
43
+ throw new Error("Path escapes project root");
44
+ }
45
+ let current = base;
46
+ for (const part of safe.split("/")) {
47
+ current = join(current, part);
48
+ try {
49
+ if ((await lstat(current)).isSymbolicLink()) {
50
+ throw new Error("Symlinks are not allowed");
51
+ }
52
+ }
53
+ catch (error) {
54
+ if (error.code !== "ENOENT") {
55
+ throw error;
56
+ }
57
+ }
58
+ }
59
+ return target;
60
+ }
61
+ /** Match simple gitignore-style patterns used by .gitignore and .mycatalogignore. */
62
+ export function ignored(path, patterns) {
63
+ let result = false;
64
+ for (const raw of patterns) {
65
+ const pattern = raw.trim();
66
+ if (!pattern || pattern.startsWith("#")) {
67
+ continue;
68
+ }
69
+ const negated = pattern.startsWith("!");
70
+ const value = (negated ? pattern.slice(1) : pattern).replace(/^\//, "").replace(/\/$/, "");
71
+ const escaped = value.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
72
+ const matched = value.includes("*")
73
+ ? new RegExp(`^${escaped.join(".*")}$`).test(path)
74
+ : path === value || path.startsWith(`${value}/`) || path.split("/").at(-1) === value;
75
+ if (matched) {
76
+ result = !negated;
77
+ }
78
+ }
79
+ return result;
80
+ }
81
+ /** Refuse unsupported files and enforce server-aligned byte limits before upload. */
82
+ export function validateUpload(path, size) {
83
+ const safe = safeRelative(path);
84
+ const directory = safe.split("/")[0];
85
+ if (size > limits[directory]) {
86
+ throw new Error(`File exceeds size limit: ${safe}`);
87
+ }
88
+ }
@@ -0,0 +1,12 @@
1
+ export type Tokens = {
2
+ access_token: string;
3
+ refresh_token: string;
4
+ api_url: string;
5
+ expires_at: number;
6
+ };
7
+ /** Save credentials to the OS store, falling back to a private file outside the project. */
8
+ export declare function saveTokens(tokens: Tokens): Promise<void>;
9
+ /** Load credentials and refuse fallback files or directories with permissive modes. */
10
+ export declare function loadTokens(): Promise<Tokens | null>;
11
+ /** Revoke local credential copies from the available OS store and fallback file. */
12
+ export declare function deleteTokens(): Promise<void>;
@@ -0,0 +1,159 @@
1
+ import { chmod, lstat, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ /**
6
+ * `MYCATALOG_TOKEN_STORE=file` forces the private 0600 file store: for machines without a working keychain and for
7
+ * tests, which must never write fake credentials into the user's real keychain.
8
+ */
9
+ function useOsStore() {
10
+ return process.env.MYCATALOG_TOKEN_STORE !== "file";
11
+ }
12
+ function paths() {
13
+ const directory = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "mycatalog");
14
+ return { directory, tokenFile: join(directory, "tokens.json") };
15
+ }
16
+ function run(bin, args, input) {
17
+ return new Promise((resolve, reject) => {
18
+ const child = spawn(bin, args, { stdio: "pipe" });
19
+ let output = "";
20
+ child.stdout.on("data", (data) => (output += data.toString()));
21
+ child.on("error", () => reject(new Error("Credential store unavailable")));
22
+ child.on("close", (code) => {
23
+ if (code === 0) {
24
+ resolve(output);
25
+ }
26
+ else {
27
+ reject(new Error("Credential store unavailable"));
28
+ }
29
+ });
30
+ child.stdin.end(input);
31
+ });
32
+ }
33
+ async function keychainRead() {
34
+ try {
35
+ const value = await run("security", [
36
+ "find-generic-password",
37
+ "-s",
38
+ "mycatalog-cli",
39
+ "-a",
40
+ process.env.USER || "user",
41
+ "-w",
42
+ ]);
43
+ return JSON.parse(value);
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ async function secretServiceRead() {
50
+ try {
51
+ const value = await run("secret-tool", [
52
+ "lookup",
53
+ "service",
54
+ "mycatalog-cli",
55
+ "account",
56
+ process.env.USER || "user",
57
+ ]);
58
+ return JSON.parse(value);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ /** Save credentials to the OS store, falling back to a private file outside the project. */
65
+ export async function saveTokens(tokens) {
66
+ if (useOsStore() && process.platform === "darwin") {
67
+ try {
68
+ await run("security", [
69
+ "add-generic-password",
70
+ "-U",
71
+ "-s",
72
+ "mycatalog-cli",
73
+ "-a",
74
+ process.env.USER || "user",
75
+ "-w",
76
+ JSON.stringify(tokens),
77
+ ]);
78
+ return;
79
+ }
80
+ catch {
81
+ // Fall through to the private file store if Keychain is unavailable.
82
+ }
83
+ }
84
+ if (useOsStore() && process.platform === "linux") {
85
+ try {
86
+ await run("secret-tool", ["store", "--label=MyCatalog CLI", "service", "mycatalog-cli", "account", process.env.USER || "user"], JSON.stringify(tokens));
87
+ return;
88
+ }
89
+ catch {
90
+ // Fall through to the private file store if Secret Service is unavailable.
91
+ }
92
+ }
93
+ const { directory, tokenFile } = paths();
94
+ await mkdir(directory, { recursive: true, mode: 0o700 });
95
+ await chmod(directory, 0o700);
96
+ await writeFile(tokenFile, JSON.stringify(tokens), { mode: 0o600 });
97
+ await chmod(tokenFile, 0o600);
98
+ }
99
+ /** Load credentials and refuse fallback files or directories with permissive modes. */
100
+ export async function loadTokens() {
101
+ if (useOsStore() && process.platform === "darwin") {
102
+ const value = await keychainRead();
103
+ if (value) {
104
+ return value;
105
+ }
106
+ }
107
+ if (useOsStore() && process.platform === "linux") {
108
+ const value = await secretServiceRead();
109
+ if (value) {
110
+ return value;
111
+ }
112
+ }
113
+ const { directory, tokenFile } = paths();
114
+ try {
115
+ const directoryInfo = await lstat(directory);
116
+ const fileInfo = await lstat(tokenFile);
117
+ if (directoryInfo.isSymbolicLink() || fileInfo.isSymbolicLink()) {
118
+ throw new Error("Token store cannot be a symlink");
119
+ }
120
+ if ((directoryInfo.mode & 0o077) !== 0 || (fileInfo.mode & 0o077) !== 0) {
121
+ throw new Error("Token file permissions are too wide; fix ~/.config/mycatalog permissions");
122
+ }
123
+ return JSON.parse(await readFile(tokenFile, "utf8"));
124
+ }
125
+ catch (error) {
126
+ if (error.code === "ENOENT") {
127
+ return null;
128
+ }
129
+ throw error;
130
+ }
131
+ }
132
+ /** Revoke local credential copies from the available OS store and fallback file. */
133
+ export async function deleteTokens() {
134
+ if (useOsStore() && process.platform === "darwin") {
135
+ try {
136
+ await run("security", ["delete-generic-password", "-s", "mycatalog-cli", "-a", process.env.USER || "user"]);
137
+ }
138
+ catch {
139
+ // The item may not exist.
140
+ }
141
+ }
142
+ if (useOsStore() && process.platform === "linux") {
143
+ try {
144
+ await run("secret-tool", ["clear", "service", "mycatalog-cli", "account", process.env.USER || "user"]);
145
+ }
146
+ catch {
147
+ // The item may not exist.
148
+ }
149
+ }
150
+ const { tokenFile } = paths();
151
+ try {
152
+ await unlink(tokenFile);
153
+ }
154
+ catch (error) {
155
+ if (error.code !== "ENOENT") {
156
+ throw error;
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,4 @@
1
+ /** True when `latest` is a strictly newer x.y.z than `current`. */
2
+ export declare function isNewer(latest: string, current: string): boolean;
3
+ /** Print a notice at most once a day. Only reads the registry; never installs or runs anything. */
4
+ export declare function checkForUpdate(current: string): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { clean } from "./output.js";
5
+ const DAY = 24 * 60 * 60 * 1000;
6
+ /** True when `latest` is a strictly newer x.y.z than `current`. */
7
+ export function isNewer(latest, current) {
8
+ const parse = (v) => /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : null;
9
+ const a = parse(latest);
10
+ const b = parse(current);
11
+ if (!a || !b)
12
+ return false;
13
+ for (let i = 0; i < 3; i += 1) {
14
+ if (a[i] !== b[i])
15
+ return a[i] > b[i];
16
+ }
17
+ return false;
18
+ }
19
+ /** Print a notice at most once a day. Only reads the registry; never installs or runs anything. */
20
+ export async function checkForUpdate(current) {
21
+ if (process.env.MYCATALOG_NO_UPDATE_CHECK === "1" || process.env.CI || !process.stderr.isTTY)
22
+ return;
23
+ const directory = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "mycatalog");
24
+ const stamp = join(directory, "update-check");
25
+ try {
26
+ const last = Number(await readFile(stamp, "utf8").catch(() => "0"));
27
+ if (Date.now() - last < DAY)
28
+ return;
29
+ await mkdir(directory, { recursive: true, mode: 0o700 });
30
+ await writeFile(stamp, String(Date.now()), { mode: 0o600 });
31
+ const response = await fetch("https://registry.npmjs.org/@mycatalog/cli/latest", {
32
+ redirect: "error",
33
+ signal: AbortSignal.timeout(3_000),
34
+ });
35
+ if (!response.ok)
36
+ return;
37
+ const { version } = (await response.json());
38
+ if (typeof version === "string" && isNewer(version, current)) {
39
+ console.error(clean(`Update available: ${current} → ${version}. Run: npm install -g @mycatalog/cli`));
40
+ }
41
+ }
42
+ catch {
43
+ // Best effort: an update check must never break a command.
44
+ }
45
+ }
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "@mycatalog/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "MyCatalog theme developer CLI",
5
+ "license": "MIT",
6
+ "repository": { "type": "git", "url": "git+https://github.com/mycatalog-io/cli.git" },
7
+ "homepage": "https://github.com/mycatalog-io/cli#readme",
8
+ "bugs": { "url": "https://github.com/mycatalog-io/cli/issues" },
9
+ "type": "module",
10
+ "bin": { "mycatalog": "dist/bin.js" },
11
+ "files": ["dist", "README.md", "LICENSE"],
12
+ "engines": { "node": ">=22" },
13
+ "publishConfig": { "access": "public", "provenance": true },
14
+ "scripts": { "build": "tsc", "typecheck": "tsc --noEmit", "test": "npm run build && node --test" },
15
+ "devDependencies": { "@types/node": "20.19.33", "typescript": "5.9.3" }
16
+ }