codepen-commander 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +179 -2
- package/api/client.js +364 -0
- package/api/errors.js +49 -0
- package/cli.js +125 -0
- package/commands/auth-context.js +139 -0
- package/commands/auth.js +593 -0
- package/commands/clone.js +371 -0
- package/commands/create-pen.js +249 -0
- package/commands/delete.js +98 -0
- package/commands/deploy.js +176 -0
- package/commands/domains.js +197 -0
- package/commands/fork.js +342 -0
- package/commands/list.js +103 -0
- package/commands/meta.js +164 -0
- package/commands/new.js +294 -0
- package/commands/open.js +174 -0
- package/commands/privacy.js +234 -0
- package/commands/pull.js +128 -0
- package/commands/push.js +294 -0
- package/commands/scaffold.js +127 -0
- package/commands/status.js +131 -0
- package/commands/unowned-pen.js +153 -0
- package/commands/versions.js +172 -0
- package/config/auth.js +470 -0
- package/config/project.js +365 -0
- package/package.json +21 -4
- package/sync/diff.js +105 -0
- package/sync/fs.js +253 -0
- package/sync/materialize.js +81 -0
- package/types.js +1 -0
- package/utils/browser.js +47 -0
- package/utils/format.js +107 -0
- package/utils/html.js +51 -0
- package/utils/json.js +122 -0
- package/utils/prompts.js +316 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isCodePenApiError } from '../api/errors.js';
|
|
4
|
+
import { hasProjectConfigInDir, normalizePenReference, PROJECT_CONFIG_FILENAME, } from '../config/project.js';
|
|
5
|
+
import { isDirectoryNonEmpty, normalizePenPath } from '../sync/fs.js';
|
|
6
|
+
import { CliError } from '../utils/json.js';
|
|
7
|
+
/**
|
|
8
|
+
* Ensures a local target directory either does not exist yet or is completely empty
|
|
9
|
+
* (and does not already contain `.cdpn.json`).
|
|
10
|
+
*/
|
|
11
|
+
export async function assertEmptyTargetDirectory(targetDir, folderDisplay, options) {
|
|
12
|
+
try {
|
|
13
|
+
const stat = await fs.lstat(targetDir);
|
|
14
|
+
if (!stat.isDirectory()) {
|
|
15
|
+
throw new CliError(409, `Target path ${folderDisplay} already exists and is not a directory.`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error.code === 'ENOENT') {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
if (await hasProjectConfigInDir(targetDir)) {
|
|
25
|
+
throw new CliError(409, `${folderDisplay} already contains ${PROJECT_CONFIG_FILENAME}. ${options.nonEmptyHint}`);
|
|
26
|
+
}
|
|
27
|
+
if (await isDirectoryNonEmpty(targetDir)) {
|
|
28
|
+
throw new CliError(409, `Folder ${folderDisplay} is not empty. \`cdpn ${options.commandName}\` requires a new or empty target folder.\n` +
|
|
29
|
+
options.nonEmptyHint);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Lists the authenticated account's CodePen Templates (`template=true`), newest updated first.
|
|
34
|
+
*/
|
|
35
|
+
export async function listAccountTemplates(client, maxItems = 50) {
|
|
36
|
+
const templates = [];
|
|
37
|
+
let page = await client.listPens({
|
|
38
|
+
template: true,
|
|
39
|
+
sort: 'updated',
|
|
40
|
+
direction: 'desc',
|
|
41
|
+
per_page: Math.min(maxItems, 100),
|
|
42
|
+
});
|
|
43
|
+
templates.push(...page.items);
|
|
44
|
+
while (templates.length < maxItems && page.links.next) {
|
|
45
|
+
page = await client.listPensPageByUrl(page.links.next);
|
|
46
|
+
templates.push(...page.items);
|
|
47
|
+
}
|
|
48
|
+
return templates.slice(0, maxItems);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Resolves a CodePen Template reference passed via `--template <id|url|title>`.
|
|
52
|
+
*/
|
|
53
|
+
export async function resolveTemplatePen(client, rawQuery, cachedTemplates) {
|
|
54
|
+
const query = rawQuery.trim();
|
|
55
|
+
if (!query) {
|
|
56
|
+
throw new CliError(400, '--template requires a CodePen template ID, URL, or title.');
|
|
57
|
+
}
|
|
58
|
+
if (/^https?:\/\//i.test(query)) {
|
|
59
|
+
const ref = normalizePenReference(query);
|
|
60
|
+
return client.getPen(ref.apiIdentifier);
|
|
61
|
+
}
|
|
62
|
+
const templates = cachedTemplates ?? (await listAccountTemplates(client));
|
|
63
|
+
const byId = templates.find((t) => t.id === query);
|
|
64
|
+
if (byId) {
|
|
65
|
+
return byId;
|
|
66
|
+
}
|
|
67
|
+
const lower = query.toLowerCase();
|
|
68
|
+
const byTitle = templates.filter((t) => (t.title || '').trim().toLowerCase() === lower);
|
|
69
|
+
if (byTitle.length === 1) {
|
|
70
|
+
return byTitle[0];
|
|
71
|
+
}
|
|
72
|
+
if (byTitle.length > 1) {
|
|
73
|
+
const choices = byTitle.map((t) => ` - ${t.title} (${t.id})`).join('\n');
|
|
74
|
+
throw new CliError(409, `Multiple CodePen templates match "${query}":\n${choices}\nPass the template ID or URL to pick one.`, { matches: byTitle.map((t) => ({ id: t.id, title: t.title })) });
|
|
75
|
+
}
|
|
76
|
+
// Fallback: if the value looks like a Pen ID (cpid or hashid), try fetching directly
|
|
77
|
+
if (/^[A-Za-z0-9_-]{3,64}$/.test(query)) {
|
|
78
|
+
try {
|
|
79
|
+
return await client.getPen(query);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (!isCodePenApiError(error) || error.status !== 404) {
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (templates.length === 0) {
|
|
88
|
+
throw new CliError(404, `No CodePen template found matching "${query}" (and your account has no Pens marked as templates yet).\n` +
|
|
89
|
+
'Mark any Pen as a template on CodePen or run `cdpn info --template true` in a synced Pen folder.');
|
|
90
|
+
}
|
|
91
|
+
const available = templates
|
|
92
|
+
.slice(0, 10)
|
|
93
|
+
.map((t) => ` - ${t.title || 'Untitled'} (${t.id})`)
|
|
94
|
+
.join('\n');
|
|
95
|
+
throw new CliError(404, `No CodePen template found matching "${query}".\nAvailable templates on this account:\n${available}`, { available_templates: templates.slice(0, 10).map((t) => ({ id: t.id, title: t.title })) });
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Downloads all text and binary files from a CodePen Template Pen so they can be
|
|
99
|
+
* used to create a brand-new independent CodePen 2.0 Pen.
|
|
100
|
+
*/
|
|
101
|
+
export async function fetchPenFilesAsUploadPayload(client, penId) {
|
|
102
|
+
const remoteFiles = await client.getPenFiles(penId);
|
|
103
|
+
const textFiles = [];
|
|
104
|
+
const binaryFiles = [];
|
|
105
|
+
for (const file of remoteFiles) {
|
|
106
|
+
const normalizedPath = normalizePenPath(file.path);
|
|
107
|
+
if (file.is_binary) {
|
|
108
|
+
if (file.bytes === 0) {
|
|
109
|
+
textFiles.push({ path: normalizedPath, content: '' });
|
|
110
|
+
}
|
|
111
|
+
else if (file.download_url) {
|
|
112
|
+
const buffer = await client.downloadFile(file.download_url);
|
|
113
|
+
binaryFiles.push({ path: normalizedPath, content: buffer });
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
throw new Error(`Cannot copy binary file ${normalizedPath} from Pen ${penId}: no download_url returned by CodePen.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
textFiles.push({
|
|
121
|
+
path: normalizedPath,
|
|
122
|
+
content: file.content ?? '',
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { textFiles, binaryFiles };
|
|
127
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { API_KEY_ENV_VAR } from '../config/auth.js';
|
|
3
|
+
import { requireProject } from '../config/project.js';
|
|
4
|
+
import { computeSyncDiff, detectLocalChangesFromBaseline, hasDiffChanges } from '../sync/diff.js';
|
|
5
|
+
import { scanLocalFiles } from '../sync/fs.js';
|
|
6
|
+
import { fmt, shortId } from '../utils/format.js';
|
|
7
|
+
import { printJsonResponse } from '../utils/json.js';
|
|
8
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
9
|
+
export function registerStatusCommand(program) {
|
|
10
|
+
program
|
|
11
|
+
.command('status')
|
|
12
|
+
.description('Compare local files with the online version on CodePen')
|
|
13
|
+
.option('--json', 'Output status as JSON')
|
|
14
|
+
.action(async (options, command) => {
|
|
15
|
+
const project = await requireProject();
|
|
16
|
+
const auth = await resolveCommandAuth({
|
|
17
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
18
|
+
project,
|
|
19
|
+
interactive: options.json ? false : undefined,
|
|
20
|
+
persistProfileToProject: !options.json,
|
|
21
|
+
});
|
|
22
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
23
|
+
const [pen, remoteFiles, localFiles] = await Promise.all([
|
|
24
|
+
client.getPen(project.config.pen_id),
|
|
25
|
+
client.getPenFiles(project.config.pen_id),
|
|
26
|
+
scanLocalFiles(project.rootDir),
|
|
27
|
+
]);
|
|
28
|
+
const diff = await computeSyncDiff({
|
|
29
|
+
localFiles,
|
|
30
|
+
remoteFiles,
|
|
31
|
+
baseline: project.config.files,
|
|
32
|
+
downloadFile: (url) => client.downloadFile(url),
|
|
33
|
+
});
|
|
34
|
+
const localHead = project.config.last_synced_version_id;
|
|
35
|
+
const remoteHead = pen.saved_version?.id ?? null;
|
|
36
|
+
const remoteMoved = Boolean(remoteHead && localHead && remoteHead !== localHead);
|
|
37
|
+
const localBaselineChanges = detectLocalChangesFromBaseline(localFiles, project.config.files);
|
|
38
|
+
if (options.json) {
|
|
39
|
+
const changeCount = diff.added.length + diff.modified.length + diff.deleted.length;
|
|
40
|
+
const message = changeCount === 0
|
|
41
|
+
? remoteMoved
|
|
42
|
+
? 'Local files match remote content, but version metadata is behind.'
|
|
43
|
+
: `Up to date with CodePen (${diff.unchanged.length} file(s)).`
|
|
44
|
+
: `Found ${changeCount} difference(s) between local folder and remote head.`;
|
|
45
|
+
printJsonResponse(200, message, {
|
|
46
|
+
pen_id: pen.id,
|
|
47
|
+
title: pen.title,
|
|
48
|
+
editor: pen.editor,
|
|
49
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
50
|
+
auth_source: auth.source,
|
|
51
|
+
url: project.config.url,
|
|
52
|
+
local_version_id: localHead,
|
|
53
|
+
remote_version_id: remoteHead,
|
|
54
|
+
remote_ahead: remoteMoved,
|
|
55
|
+
up_to_date: changeCount === 0 && !remoteMoved,
|
|
56
|
+
build_status: pen.saved_version?.build?.status ?? null,
|
|
57
|
+
deployment: pen.deployment,
|
|
58
|
+
changes: {
|
|
59
|
+
added: diff.added.map((i) => i.path),
|
|
60
|
+
modified: diff.modified.map((i) => i.path),
|
|
61
|
+
deleted: diff.deleted.map((i) => i.path),
|
|
62
|
+
unchanged: diff.unchanged.map((i) => i.path),
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
console.log(`${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id}, ${pen.editor})`)}`);
|
|
68
|
+
console.log(`Profile: ${auth.profile ? fmt.cyan(auth.profile) : fmt.dim(`env (${API_KEY_ENV_VAR})`)}`);
|
|
69
|
+
console.log(`URL: ${fmt.cyan(project.config.url)}`);
|
|
70
|
+
console.log(`Synced: ${fmt.dim(shortId(localHead))}`);
|
|
71
|
+
console.log(`Remote: ${fmt.dim(shortId(remoteHead))}` +
|
|
72
|
+
(remoteMoved ? ` ${fmt.yellow('(remote head has moved since last sync!)')}` : ''));
|
|
73
|
+
const buildStatus = pen.saved_version?.build?.status;
|
|
74
|
+
if (buildStatus) {
|
|
75
|
+
const colored = buildStatus === 'Success'
|
|
76
|
+
? fmt.green(buildStatus)
|
|
77
|
+
: buildStatus === 'Failed'
|
|
78
|
+
? fmt.red(buildStatus)
|
|
79
|
+
: fmt.yellow(buildStatus);
|
|
80
|
+
console.log(`Build: ${colored}`);
|
|
81
|
+
}
|
|
82
|
+
if (pen.deployment) {
|
|
83
|
+
const deployedIsHead = pen.deployment.version_id === remoteHead;
|
|
84
|
+
const deployNote = deployedIsHead
|
|
85
|
+
? fmt.green('up to date')
|
|
86
|
+
: fmt.yellow(`older version ${shortId(pen.deployment.version_id)}`);
|
|
87
|
+
console.log(`Deployed: ${fmt.cyan(pen.deployment.url)} ${fmt.dim(`(${deployNote})`)}`);
|
|
88
|
+
if (pen.deployment.custom_domains.length > 0) {
|
|
89
|
+
console.log(`Domains: ${pen.deployment.custom_domains.join(', ')}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
console.log(`Deployed: ${fmt.dim('not deployed')}`);
|
|
94
|
+
}
|
|
95
|
+
console.log('');
|
|
96
|
+
if (!hasDiffChanges(diff)) {
|
|
97
|
+
if (remoteMoved) {
|
|
98
|
+
console.log(`${fmt.yellow('!')} Local files match remote content, but version metadata is behind. Run \`cdpn pull\` to update ${fmt.dim('.cdpn.json')}.`);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
console.log(`${fmt.green('✓')} Up to date with CodePen (${diff.unchanged.length} file(s)).`);
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const localModifiedSet = new Set([
|
|
106
|
+
...localBaselineChanges.added,
|
|
107
|
+
...localBaselineChanges.modified,
|
|
108
|
+
...localBaselineChanges.deleted,
|
|
109
|
+
]);
|
|
110
|
+
console.log('Differences between local folder and remote head:');
|
|
111
|
+
for (const item of diff.added) {
|
|
112
|
+
const hint = remoteMoved && !localModifiedSet.has(item.path) ? fmt.dim(' (deleted remotely)') : '';
|
|
113
|
+
console.log(` ${fmt.green('+')} ${item.path}${hint}`);
|
|
114
|
+
}
|
|
115
|
+
for (const item of diff.modified) {
|
|
116
|
+
const hint = remoteMoved && !localModifiedSet.has(item.path) ? fmt.dim(' (changed remotely)') : '';
|
|
117
|
+
console.log(` ${fmt.yellow('~')} ${item.path}${hint}`);
|
|
118
|
+
}
|
|
119
|
+
for (const item of diff.deleted) {
|
|
120
|
+
const hint = remoteMoved && !localModifiedSet.has(item.path) ? fmt.dim(' (added remotely)') : '';
|
|
121
|
+
console.log(` ${fmt.red('-')} ${item.path}${hint}`);
|
|
122
|
+
}
|
|
123
|
+
console.log('');
|
|
124
|
+
if (remoteMoved) {
|
|
125
|
+
console.log(fmt.yellow('Remote has newer commits. Run `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite remote with local.'));
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
console.log(fmt.dim('Run `cdpn push` to upload these changes, or `cdpn pull` to discard local changes.'));
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { API_KEY_ENV_VAR, DEFAULT_PROFILE_NAME, findMatchingProfile, readAuthStore, } from '../config/auth.js';
|
|
2
|
+
import { extractCodePenOwnerFromUrl } from '../config/project.js';
|
|
3
|
+
import { openBrowser } from '../utils/browser.js';
|
|
4
|
+
import { fmt } from '../utils/format.js';
|
|
5
|
+
import { CliError } from '../utils/json.js';
|
|
6
|
+
/**
|
|
7
|
+
* Checks before interactive profile prompting or network calls whether a Pen URL clearly
|
|
8
|
+
* belongs to an account not present among the user's named stored profiles in `~/.cdpn`.
|
|
9
|
+
*
|
|
10
|
+
* Returns `null` whenever:
|
|
11
|
+
* - `--profile` or `CODEPEN_API_KEY` was explicitly provided (let the API verify),
|
|
12
|
+
* - the URL carries no owner segment (e.g. raw ID or preview URL),
|
|
13
|
+
* - fewer than 2 profiles are stored (single-profile setups don't prompt anyway, so trying
|
|
14
|
+
* the API preserves custom profile aliases and still handles 404 cleanly),
|
|
15
|
+
* - a generic `default` profile exists, or
|
|
16
|
+
* - one of the stored profile names matches the URL's owner.
|
|
17
|
+
*/
|
|
18
|
+
export async function findUnmatchedStoredOwner(options) {
|
|
19
|
+
if (options.explicitProfile)
|
|
20
|
+
return null;
|
|
21
|
+
const env = options.env ?? process.env;
|
|
22
|
+
if (env[API_KEY_ENV_VAR]?.trim())
|
|
23
|
+
return null;
|
|
24
|
+
if (!options.originalUrl)
|
|
25
|
+
return null;
|
|
26
|
+
const urlOwner = extractCodePenOwnerFromUrl(options.originalUrl);
|
|
27
|
+
if (!urlOwner)
|
|
28
|
+
return null;
|
|
29
|
+
const { store } = await readAuthStore({ homeDir: options.homeDir });
|
|
30
|
+
const availableProfiles = Object.keys(store.profiles).sort((a, b) => a.localeCompare(b));
|
|
31
|
+
if (availableProfiles.length < 2)
|
|
32
|
+
return null;
|
|
33
|
+
if (availableProfiles.includes(DEFAULT_PROFILE_NAME))
|
|
34
|
+
return null;
|
|
35
|
+
if (findMatchingProfile(availableProfiles, options.originalUrl) !== null) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
return { urlOwner, availableProfiles };
|
|
39
|
+
}
|
|
40
|
+
function toHttpsUrl(rawUrl) {
|
|
41
|
+
try {
|
|
42
|
+
const parsed = new URL(rawUrl);
|
|
43
|
+
if (parsed.protocol === 'http:') {
|
|
44
|
+
parsed.protocol = 'https:';
|
|
45
|
+
}
|
|
46
|
+
return parsed.toString();
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return rawUrl;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Explains CodePen API v2's owner-only scope for another user's Pen and, in interactive mode,
|
|
54
|
+
* offers to open the Pen in the browser so the user can fork it on codepen.io and paste the
|
|
55
|
+
* forked URL back to clone immediately.
|
|
56
|
+
*
|
|
57
|
+
* Returns the pasted forked Pen URL/ID if the user provides one, or `null` if they exit.
|
|
58
|
+
* In non-interactive mode (or when `allowBrowserFallback` is false), throws a clear Error.
|
|
59
|
+
*/
|
|
60
|
+
export async function handleUnownedPenAccess(options) {
|
|
61
|
+
const safeUrl = toHttpsUrl(options.penUrl);
|
|
62
|
+
const { action, urlOwner, availableProfiles, currentProfile, interactive } = options;
|
|
63
|
+
const allowBrowserFallback = options.allowBrowserFallback !== false;
|
|
64
|
+
const profileLine = availableProfiles && availableProfiles.length > 0
|
|
65
|
+
? `Stored profiles: ${availableProfiles.join(', ')} (pass --profile <name> if one of them is an alias for ${urlOwner}).`
|
|
66
|
+
: currentProfile
|
|
67
|
+
? `Active profile: ${currentProfile} (if another profile owns ${urlOwner}’s Pens, pass --profile <name>).`
|
|
68
|
+
: null;
|
|
69
|
+
if (!interactive || !allowBrowserFallback) {
|
|
70
|
+
const lines = [
|
|
71
|
+
`Cannot ${action} ${urlOwner}’s Pen via CodePen API v2.`,
|
|
72
|
+
`CodePen API v2 keys can only access and fork Pens owned by the key’s account (other users’ Pens return 404, even when public).`,
|
|
73
|
+
...(profileLine ? [profileLine] : []),
|
|
74
|
+
`Fork this Pen in your browser at ${safeUrl}, then run \`cdpn clone <your-fork-url>\`.`,
|
|
75
|
+
];
|
|
76
|
+
throw new CliError(403, lines.join('\n'), {
|
|
77
|
+
url: safeUrl,
|
|
78
|
+
owner: urlOwner,
|
|
79
|
+
...(availableProfiles ? { available_profiles: availableProfiles } : {}),
|
|
80
|
+
...(currentProfile ? { current_profile: currentProfile } : {}),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
console.log(`\n${fmt.yellow(`Cannot ${action} ${fmt.bold(urlOwner)}’s Pen via CodePen API v2.`)}`);
|
|
84
|
+
console.log('CodePen API v2 keys can only access and fork Pens owned by the key’s account — other users’ Pens return 404, even when public.');
|
|
85
|
+
if (profileLine) {
|
|
86
|
+
console.log(fmt.dim(` ${profileLine}`));
|
|
87
|
+
}
|
|
88
|
+
console.log(`\nWorkaround: fork this Pen in your browser on codepen.io, then clone your fork locally.`);
|
|
89
|
+
const shouldOpen = await options.confirmImpl(`Open ${safeUrl} in your browser to fork it?`, true);
|
|
90
|
+
if (!shouldOpen) {
|
|
91
|
+
console.log(fmt.dim('Run `cdpn clone <your-fork-url>` once you have forked it on CodePen.'));
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
const openImpl = options.openBrowserImpl ?? openBrowser;
|
|
95
|
+
const opened = await openImpl(safeUrl);
|
|
96
|
+
if (opened) {
|
|
97
|
+
console.log(`\n${fmt.green('✓')} Opened ${fmt.cyan(safeUrl)} in your browser.`);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
console.log(`\n${fmt.yellow('!')} Could not launch a browser automatically. Open this URL manually:\n ${fmt.cyan(safeUrl)}`);
|
|
101
|
+
}
|
|
102
|
+
const pasted = (await options.textImpl('Paste your forked Pen URL to clone it now (or press Enter to exit)')).trim();
|
|
103
|
+
if (!pasted) {
|
|
104
|
+
console.log(fmt.dim('Run `cdpn clone <your-fork-url>` whenever you are ready to clone your fork.'));
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
return pasted;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Handles a `404 NOT_FOUND` error from `GET /v2/pens/{id}` in `cdpn clone` / `cdpn fork`.
|
|
111
|
+
* If the URL points to another user's Pen, triggers the friendly explanation and optional
|
|
112
|
+
* browser fork-and-clone workflow; otherwise throws a clear, contextual 404 error.
|
|
113
|
+
*/
|
|
114
|
+
export async function handlePenNotFoundOnFetch(options) {
|
|
115
|
+
const { action, apiIdentifier, originalUrl, auth, client } = options;
|
|
116
|
+
const urlOwner = originalUrl ? extractCodePenOwnerFromUrl(originalUrl) : null;
|
|
117
|
+
const accountLabel = auth.profile ? `profile "${auth.profile}"` : 'the current API key';
|
|
118
|
+
if (urlOwner && originalUrl) {
|
|
119
|
+
let matchesAuthenticatedOwner = Boolean(auth.profile &&
|
|
120
|
+
auth.profile !== DEFAULT_PROFILE_NAME &&
|
|
121
|
+
auth.profile.toLowerCase() === urlOwner.toLowerCase());
|
|
122
|
+
if (!matchesAuthenticatedOwner && (!auth.profile || auth.profile === DEFAULT_PROFILE_NAME)) {
|
|
123
|
+
try {
|
|
124
|
+
const samplePen = await client.verifyAuth();
|
|
125
|
+
const detected = samplePen?.urls?.editor
|
|
126
|
+
? extractCodePenOwnerFromUrl(samplePen.urls.editor)
|
|
127
|
+
: null;
|
|
128
|
+
if (detected && detected.toLowerCase() === urlOwner.toLowerCase()) {
|
|
129
|
+
matchesAuthenticatedOwner = true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Ignore verifyAuth errors; treat as unowned fallback
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!matchesAuthenticatedOwner) {
|
|
137
|
+
return handleUnownedPenAccess({
|
|
138
|
+
action,
|
|
139
|
+
penUrl: originalUrl,
|
|
140
|
+
urlOwner,
|
|
141
|
+
currentProfile: auth.profile,
|
|
142
|
+
interactive: options.interactive,
|
|
143
|
+
allowBrowserFallback: options.allowBrowserFallback,
|
|
144
|
+
confirmImpl: options.confirmImpl,
|
|
145
|
+
textImpl: options.textImpl,
|
|
146
|
+
openBrowserImpl: options.openBrowserImpl,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
throw new CliError(404, `Pen ${apiIdentifier} was not found under ${accountLabel}. Verify the Pen URL/ID exists and is not in the trash.`, { pen_id: apiIdentifier, profile: auth.profile });
|
|
150
|
+
}
|
|
151
|
+
throw new CliError(404, `Pen ${apiIdentifier} was not found for ${accountLabel}.\n` +
|
|
152
|
+
`Note: CodePen API v2 keys can only access and fork Pens owned by the key’s account (other users’ Pens return 404, even when public).`, { pen_id: apiIdentifier, profile: auth.profile });
|
|
153
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { CodePenClient } from '../api/client.js';
|
|
2
|
+
import { buildSyncedFileMap, requireProject, writeProjectConfig } from '../config/project.js';
|
|
3
|
+
import { scanLocalFiles } from '../sync/fs.js';
|
|
4
|
+
import { syncRemoteFilesToDisk } from '../sync/materialize.js';
|
|
5
|
+
import { fmt, formatDate, formatTable, shortId } from '../utils/format.js';
|
|
6
|
+
import { CliError, printJsonResponse } from '../utils/json.js';
|
|
7
|
+
import { isInteractive, promptConfirm, promptSelect } from '../utils/prompts.js';
|
|
8
|
+
import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
|
|
9
|
+
export function registerVersionCommands(program) {
|
|
10
|
+
program
|
|
11
|
+
.command('versions')
|
|
12
|
+
.description('List saved versions of this Pen')
|
|
13
|
+
.option('-n, --limit <count>', 'Maximum number of versions to show', '15')
|
|
14
|
+
.option('--json', 'Output versions as JSON')
|
|
15
|
+
.action(async (options, command) => {
|
|
16
|
+
const limit = Number.parseInt(options.limit ?? '15', 10);
|
|
17
|
+
if (Number.isNaN(limit) || limit < 1) {
|
|
18
|
+
throw new CliError(400, '--limit must be a positive integer.');
|
|
19
|
+
}
|
|
20
|
+
const project = await requireProject();
|
|
21
|
+
const auth = await resolveCommandAuth({
|
|
22
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
23
|
+
project,
|
|
24
|
+
interactive: options.json ? false : undefined,
|
|
25
|
+
persistProfileToProject: !options.json,
|
|
26
|
+
});
|
|
27
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
28
|
+
const [pen, versionsPage] = await Promise.all([
|
|
29
|
+
client.getPen(project.config.pen_id),
|
|
30
|
+
client.listVersions(project.config.pen_id, {
|
|
31
|
+
per_page: Math.min(limit, 100),
|
|
32
|
+
sort: 'created',
|
|
33
|
+
direction: 'desc',
|
|
34
|
+
}),
|
|
35
|
+
]);
|
|
36
|
+
if (pen.editor === 'Classic') {
|
|
37
|
+
if (options.json) {
|
|
38
|
+
printJsonResponse(200, 'Classic Pens do not have saved versions in CodePen API v2.', []);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
console.log(fmt.yellow('Classic Pens do not have saved versions in CodePen API v2.'));
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const versions = versionsPage.items.slice(0, limit);
|
|
46
|
+
if (options.json) {
|
|
47
|
+
const message = versions.length === 0
|
|
48
|
+
? 'No saved versions found.'
|
|
49
|
+
: `Found ${versions.length} saved version(s).`;
|
|
50
|
+
printJsonResponse(200, message, versions);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (versions.length === 0) {
|
|
54
|
+
console.log(fmt.dim('No saved versions found.'));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const headId = pen.saved_version?.id ?? null;
|
|
58
|
+
const syncedId = project.config.last_synced_version_id;
|
|
59
|
+
const rows = versions.map((v) => {
|
|
60
|
+
const status = v.build?.status ?? '—';
|
|
61
|
+
const coloredStatus = status === 'Success'
|
|
62
|
+
? fmt.green(status)
|
|
63
|
+
: status === 'Failed'
|
|
64
|
+
? fmt.red(status)
|
|
65
|
+
: fmt.yellow(status);
|
|
66
|
+
const markers = [];
|
|
67
|
+
if (v.id === headId)
|
|
68
|
+
markers.push(fmt.cyan('head'));
|
|
69
|
+
if (v.id === syncedId)
|
|
70
|
+
markers.push(fmt.green('local'));
|
|
71
|
+
if (v.deployed)
|
|
72
|
+
markers.push(fmt.magenta('deployed'));
|
|
73
|
+
return [
|
|
74
|
+
v.id,
|
|
75
|
+
coloredStatus,
|
|
76
|
+
v.label ? v.label : fmt.dim('—'),
|
|
77
|
+
markers.length > 0 ? markers.join(', ') : fmt.dim('—'),
|
|
78
|
+
fmt.dim(formatDate(v.created_at)),
|
|
79
|
+
];
|
|
80
|
+
});
|
|
81
|
+
console.log(formatTable(['Version ID', 'Build', 'Label', 'Markers', 'Created'], rows));
|
|
82
|
+
});
|
|
83
|
+
program
|
|
84
|
+
.command('rollback [version-id]')
|
|
85
|
+
.description('Restore an older saved version to head and sync files locally')
|
|
86
|
+
.option('-m, --label <label>', 'Optional label for the restored version (max 80 chars)')
|
|
87
|
+
.option('-y, --yes', 'Skip confirmation prompt')
|
|
88
|
+
.option('--json', 'Output rollback result as JSON')
|
|
89
|
+
.action(async (versionIdArg, options, command) => {
|
|
90
|
+
if (options.label && options.label.length > 80) {
|
|
91
|
+
throw new CliError(400, 'Version label must be at most 80 characters.');
|
|
92
|
+
}
|
|
93
|
+
const interactive = isInteractive() && !options.json;
|
|
94
|
+
const project = await requireProject();
|
|
95
|
+
const auth = await resolveCommandAuth({
|
|
96
|
+
explicitProfile: getGlobalProfileOption(command),
|
|
97
|
+
project,
|
|
98
|
+
interactive,
|
|
99
|
+
persistProfileToProject: !options.json,
|
|
100
|
+
});
|
|
101
|
+
const client = new CodePenClient({ apiKey: auth.apiKey });
|
|
102
|
+
let targetVersionId = versionIdArg?.trim();
|
|
103
|
+
if (!targetVersionId) {
|
|
104
|
+
if (!interactive) {
|
|
105
|
+
throw new CliError(400, 'Missing <version-id>. Run `cdpn versions` to list available version IDs.');
|
|
106
|
+
}
|
|
107
|
+
const page = await client.listVersions(project.config.pen_id, {
|
|
108
|
+
per_page: 10,
|
|
109
|
+
sort: 'created',
|
|
110
|
+
direction: 'desc',
|
|
111
|
+
});
|
|
112
|
+
if (page.items.length === 0) {
|
|
113
|
+
throw new CliError(404, 'No saved versions available to restore.');
|
|
114
|
+
}
|
|
115
|
+
targetVersionId = await promptSelect('Select a version to restore to head:', page.items.map((v) => ({
|
|
116
|
+
value: v.id,
|
|
117
|
+
label: `${shortId(v.id)}${v.label ? ` — ${v.label}` : ''}`,
|
|
118
|
+
description: `${v.build?.status ?? 'Unknown'} · ${formatDate(v.created_at)}${v.deployed ? ' · deployed' : ''}`,
|
|
119
|
+
})), 0);
|
|
120
|
+
}
|
|
121
|
+
if (!options.yes) {
|
|
122
|
+
if (!interactive) {
|
|
123
|
+
throw new CliError(400, 'Refusing to rollback in non-interactive mode without --yes.');
|
|
124
|
+
}
|
|
125
|
+
const ok = await promptConfirm(`Restore version ${fmt.cyan(targetVersionId)} as the new head and overwrite local files?`, false);
|
|
126
|
+
if (!ok) {
|
|
127
|
+
console.log('Aborted.');
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (!options.json) {
|
|
132
|
+
console.log(`Restoring version ${fmt.cyan(shortId(targetVersionId))}…`);
|
|
133
|
+
}
|
|
134
|
+
const updatedPen = await client.restoreVersion(project.config.pen_id, targetVersionId, options.label);
|
|
135
|
+
const newHeadId = updatedPen.saved_version?.id ?? null;
|
|
136
|
+
const [localFiles, remoteFiles] = await Promise.all([
|
|
137
|
+
scanLocalFiles(project.rootDir),
|
|
138
|
+
client.getPenFiles(updatedPen.id),
|
|
139
|
+
]);
|
|
140
|
+
const materialized = await syncRemoteFilesToDisk({
|
|
141
|
+
client,
|
|
142
|
+
rootDir: project.rootDir,
|
|
143
|
+
remoteFiles,
|
|
144
|
+
existingLocalPaths: localFiles.keys(),
|
|
145
|
+
pruneRemoved: true,
|
|
146
|
+
});
|
|
147
|
+
await writeProjectConfig(project.rootDir, {
|
|
148
|
+
url: project.config.url || updatedPen.urls.editor,
|
|
149
|
+
pen_id: updatedPen.id,
|
|
150
|
+
...(project.config.profile ? { profile: project.config.profile } : {}),
|
|
151
|
+
last_synced_version_id: newHeadId,
|
|
152
|
+
editor: updatedPen.editor,
|
|
153
|
+
files: buildSyncedFileMap(remoteFiles, materialized.localSha256ByPath),
|
|
154
|
+
});
|
|
155
|
+
if (options.json) {
|
|
156
|
+
printJsonResponse(200, `Restored version ${targetVersionId} to head.`, {
|
|
157
|
+
pen: updatedPen,
|
|
158
|
+
profile: auth.profile ?? project.config.profile ?? null,
|
|
159
|
+
restored_version_id: targetVersionId,
|
|
160
|
+
new_version_id: newHeadId,
|
|
161
|
+
written_paths: materialized.writtenPaths,
|
|
162
|
+
deleted_paths: materialized.deletedPaths,
|
|
163
|
+
});
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
console.log(`\n${fmt.green('✓')} Restored version ${fmt.dim(shortId(targetVersionId))} → new head ${fmt.dim(shortId(newHeadId))}`);
|
|
167
|
+
console.log(` Synced ${materialized.writtenPaths.length} file(s)` +
|
|
168
|
+
(materialized.deletedPaths.length > 0
|
|
169
|
+
? `, removed ${materialized.deletedPaths.length} file(s)`
|
|
170
|
+
: ''));
|
|
171
|
+
});
|
|
172
|
+
}
|