codepen-commander 1.3.0 → 1.4.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.
Files changed (92) hide show
  1. package/README.md +103 -11
  2. package/api/client.js +129 -106
  3. package/cli.js +34 -29
  4. package/commands/auth/default.js +40 -0
  5. package/commands/auth/index.js +83 -0
  6. package/commands/auth/list.js +78 -0
  7. package/commands/auth/login.js +136 -0
  8. package/commands/auth/logout.js +186 -0
  9. package/commands/auth/status.js +212 -0
  10. package/commands/build.js +256 -0
  11. package/commands/clone.js +13 -581
  12. package/commands/delete.js +548 -80
  13. package/commands/deploy.js +164 -169
  14. package/commands/domains.js +83 -39
  15. package/commands/fork.js +13 -317
  16. package/commands/info.js +152 -0
  17. package/commands/init.js +375 -0
  18. package/commands/list.js +95 -78
  19. package/commands/new.js +155 -83
  20. package/commands/open.js +29 -19
  21. package/commands/privacy.js +52 -36
  22. package/commands/pull.js +123 -110
  23. package/commands/push.js +221 -376
  24. package/commands/restore.js +251 -0
  25. package/commands/rollback.js +141 -0
  26. package/commands/serve.js +119 -0
  27. package/commands/settings.js +126 -0
  28. package/commands/shell.js +305 -0
  29. package/commands/status.js +133 -39
  30. package/commands/sync.js +330 -0
  31. package/commands/undeploy.js +102 -0
  32. package/commands/unlink.js +191 -0
  33. package/commands/versions.js +100 -163
  34. package/config/auth.js +4 -374
  35. package/config/pen-blocks.js +166 -0
  36. package/config/project.js +103 -231
  37. package/config/user-store.js +364 -0
  38. package/constants.js +42 -0
  39. package/errors.js +17 -0
  40. package/package.json +1 -1
  41. package/shell/index.html +79 -0
  42. package/shell/scripts.js +276 -0
  43. package/shell/styles.css +492 -0
  44. package/site/blocks/classic.js +270 -0
  45. package/site/blocks/context.js +63 -0
  46. package/site/blocks/index.js +4 -0
  47. package/site/blocks/packages.js +242 -0
  48. package/site/blocks/unsupported-page.js +328 -0
  49. package/site/builder.js +475 -0
  50. package/site/detect.js +65 -0
  51. package/site/ignore-files.js +90 -0
  52. package/site/manifest.js +227 -0
  53. package/site/server.js +483 -0
  54. package/site/shell.js +363 -0
  55. package/sync/fs.js +19 -17
  56. package/sync/info.js +6 -81
  57. package/utils/browser.js +17 -10
  58. package/utils/cli-options.js +79 -0
  59. package/utils/codepen-url.js +183 -0
  60. package/utils/format.js +39 -30
  61. package/utils/fs-safe.js +95 -0
  62. package/utils/html.js +40 -1
  63. package/utils/json.js +4 -19
  64. package/utils/output.js +37 -0
  65. package/utils/package-paths.js +51 -0
  66. package/utils/prompts/index.js +5 -0
  67. package/utils/prompts/multi-select.js +185 -0
  68. package/utils/prompts/secret.js +65 -0
  69. package/utils/prompts/select.js +141 -0
  70. package/utils/prompts/text.js +99 -0
  71. package/utils/prompts/tty-list.js +165 -0
  72. package/utils/prompts/types.js +35 -0
  73. package/utils/strings.js +98 -0
  74. package/utils/watcher.js +82 -0
  75. package/{commands → workflows}/auth-context.js +13 -7
  76. package/workflows/batch-pens.js +1647 -0
  77. package/workflows/batch-target.js +184 -0
  78. package/workflows/classic-convert.js +241 -0
  79. package/workflows/clone-pen.js +381 -0
  80. package/{commands → workflows}/create-pen.js +59 -84
  81. package/workflows/discover-pens.js +91 -0
  82. package/workflows/fork-pen.js +314 -0
  83. package/workflows/missing-pen.js +212 -0
  84. package/workflows/pull-pen.js +204 -0
  85. package/workflows/push-pen.js +318 -0
  86. package/{commands → workflows}/scaffold.js +4 -3
  87. package/workflows/sync-pen.js +227 -0
  88. package/{commands → workflows}/unowned-pen.js +16 -12
  89. package/commands/auth.js +0 -593
  90. package/commands/meta.js +0 -184
  91. package/utils/prompts.js +0 -316
  92. /package/{types.js → api/types.js} +0 -0
package/commands/clone.js CHANGED
@@ -1,586 +1,15 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { CodePenClient } from '../api/client.js';
4
- import { CodePenApiError } from '../api/errors.js';
5
- import { DEFAULT_PROFILE_NAME, findMatchingProfile } from '../config/auth.js';
6
- import { buildSyncedFileMap, extractCodePenOwnerFromUrl, hasProjectConfigInDir, normalizePenReference, PROJECT_CONFIG_FILENAME, suggestFolderName, writeProjectConfig, } from '../config/project.js';
7
- import { isDirectoryNonEmpty } from '../sync/fs.js';
8
- import { buildPenInfoConfigFields } from '../sync/info.js';
9
- import { syncRemoteFilesToDisk } from '../sync/materialize.js';
10
- import { openBrowser, validateBrowserUrl } from '../utils/browser.js';
11
- import { fmt, shortId } from '../utils/format.js';
12
- import { CliError, printJsonResponse } from '../utils/json.js';
13
- import { isInteractive, promptConfirm, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
14
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
15
- import { forkPenCommand } from './fork.js';
16
- import { findUnmatchedStoredOwner, handlePenNotFoundOnFetch, handleUnownedPenAccess, } from './unowned-pen.js';
17
- function validateEditorBrowserUrl(rawUrl) {
18
- let candidate = rawUrl.trim();
19
- try {
20
- const parsed = new URL(candidate);
21
- if (parsed.protocol === 'http:') {
22
- parsed.protocol = 'https:';
23
- }
24
- candidate = parsed.toString();
25
- }
26
- catch {
27
- // Let validateBrowserUrl throw a clean validation error
28
- }
29
- const safeUrl = validateBrowserUrl(candidate);
30
- const host = new URL(safeUrl).hostname.toLowerCase();
31
- const isCodePenHost = host === 'codepen.io' || host.endsWith('.codepen.io');
32
- if (!isCodePenHost) {
33
- throw new CliError(400, `Refusing to open non-CodePen URL in browser: ${host}`);
34
- }
35
- return safeUrl;
36
- }
37
- async function promptClassicRetryChoice(selectImpl) {
38
- return selectImpl('How would you like to proceed?', [
39
- {
40
- value: 'retry',
41
- label: 'Check again / paste 2.0 Pen URL',
42
- description: 're-fetch after converting or enter the new URL',
43
- },
44
- {
45
- value: 'clone-unlinked',
46
- label: 'Just clone without linking',
47
- description: `download files without ${PROJECT_CONFIG_FILENAME}`,
48
- },
49
- {
50
- value: 'cancel',
51
- label: 'Cancel',
52
- description: 'abort clone',
53
- },
54
- ], 0);
55
- }
56
- async function resolveCurrentUsername(client, auth, penOwner) {
57
- // Fast path: named profile already matches the Pen owner
58
- if (auth.profile &&
59
- auth.profile !== DEFAULT_PROFILE_NAME &&
60
- auth.profile.toLowerCase() === penOwner.toLowerCase()) {
61
- return auth.profile;
62
- }
63
- // Inspect one Pen owned by this API key to discover the actual CodePen account username
64
- // (handles CODEPEN_API_KEY env var, "default" profile, and custom profile aliases)
65
- try {
66
- const samplePen = await client.verifyAuth();
67
- const detected = samplePen?.urls?.editor
68
- ? extractCodePenOwnerFromUrl(samplePen.urls.editor)
69
- : null;
70
- if (detected) {
71
- return detected;
72
- }
73
- }
74
- catch {
75
- // Fall back to profile name if the account has no Pens or listing fails
76
- }
77
- if (auth.profile && auth.profile !== DEFAULT_PROFILE_NAME) {
78
- return auth.profile;
79
- }
80
- return null;
81
- }
82
- async function handleClassicPenClone(params) {
83
- const { pen, apiIdentifier, effectiveUrl, options, selectImpl, textImpl } = params;
84
- let currentAuth = params.auth;
85
- let currentClient = params.client;
86
- let fallbackPen = pen;
87
- const makeFallbackResult = (action) => ({
88
- action,
89
- pen: fallbackPen,
90
- effectiveUrl,
91
- auth: currentAuth,
92
- client: currentClient,
93
- isOwnedByAnotherUser: false,
94
- penOwner: null,
95
- currentUsername: null,
96
- });
97
- console.log(`\n${fmt.yellow('This is a Classic (v1) Pen, which is read-only through CodePen API v2 and cannot be synced.')}`);
98
- console.log('You can convert it to a CodePen 2.0 Pen in the browser using the dropdown on the Save button.\n');
99
- const initialChoice = await selectImpl('How would you like to proceed?', [
100
- {
101
- value: 'convert',
102
- label: 'Open the Pen to convert it first',
103
- description: 'open in browser, then clone linked',
104
- },
105
- {
106
- value: 'clone-unlinked',
107
- label: 'Just clone without linking',
108
- description: `download files without ${PROJECT_CONFIG_FILENAME}`,
109
- },
110
- ], 0);
111
- if (initialChoice === 'clone-unlinked') {
112
- return makeFallbackResult('clone-unlinked');
113
- }
114
- const editorUrl = validateEditorBrowserUrl(pen.urls.editor || effectiveUrl);
115
- const openImpl = options.openBrowser ?? openBrowser;
116
- const opened = await openImpl(editorUrl);
117
- if (opened) {
118
- console.log(`\n${fmt.green('✓')} Opened ${fmt.cyan(editorUrl)} in your browser.`);
119
- }
120
- else {
121
- console.log(`\n${fmt.yellow('!')} Could not launch a browser automatically. Open this URL manually:\n ${fmt.cyan(editorUrl)}`);
122
- }
123
- console.log(fmt.dim('In CodePen, use the dropdown on the Save button to convert this Pen to CodePen 2.0.'));
124
- for (;;) {
125
- console.log('');
126
- const pasted = (await textImpl('Press Enter once converted to re-fetch & clone (or paste the new 2.0 Pen URL)')).trim();
127
- let targetApiId = apiIdentifier;
128
- let pastedOriginalUrl;
129
- if (pasted) {
130
- try {
131
- const normalized = normalizePenReference(pasted);
132
- targetApiId = normalized.apiIdentifier;
133
- pastedOriginalUrl = normalized.originalUrl;
134
- }
135
- catch (error) {
136
- const msg = error instanceof Error ? error.message : String(error);
137
- console.log(`\n${fmt.yellow('!')} ${msg}\n`);
138
- const nextAction = await promptClassicRetryChoice(selectImpl);
139
- if (nextAction === 'retry')
140
- continue;
141
- if (nextAction === 'clone-unlinked')
142
- return makeFallbackResult('clone-unlinked');
143
- console.log('Aborted.');
144
- return makeFallbackResult('cancel');
145
- }
146
- if (!options.explicitProfile && currentAuth.source === 'file' && pastedOriginalUrl) {
147
- const matchedProfile = findMatchingProfile(currentAuth.availableProfiles, pastedOriginalUrl);
148
- if (matchedProfile && matchedProfile !== currentAuth.profile) {
149
- currentAuth = await resolveCommandAuth({
150
- explicitProfile: matchedProfile,
151
- interactive: true,
152
- env: options.env,
153
- homeDir: options.homeDir,
154
- });
155
- currentClient = new CodePenClient({ apiKey: currentAuth.apiKey, baseUrl: options.baseUrl });
156
- console.log(fmt.dim(`Using profile "${matchedProfile}" (matches Pen owner).`));
157
- }
158
- }
159
- }
160
- console.log(`Fetching Pen ${fmt.cyan(targetApiId)}…`);
161
- let refetched;
162
- try {
163
- refetched = await currentClient.getPen(targetApiId);
164
- }
165
- catch (error) {
166
- const msg = error instanceof CodePenApiError
167
- ? error.formatForUser()
168
- : error instanceof Error
169
- ? error.message
170
- : String(error);
171
- console.log(`\n${fmt.yellow('!')} Could not fetch Pen ${targetApiId}: ${msg}\n`);
172
- const nextAction = await promptClassicRetryChoice(selectImpl);
173
- if (nextAction === 'retry')
174
- continue;
175
- if (nextAction === 'clone-unlinked')
176
- return makeFallbackResult('clone-unlinked');
177
- console.log('Aborted.');
178
- return makeFallbackResult('cancel');
179
- }
180
- const refetchedOwner = extractCodePenOwnerFromUrl(refetched.urls.editor) ??
181
- (pastedOriginalUrl ? extractCodePenOwnerFromUrl(pastedOriginalUrl) : null);
182
- if (refetchedOwner &&
183
- !options.explicitProfile &&
184
- currentAuth.source === 'file' &&
185
- currentAuth.profile?.toLowerCase() !== refetchedOwner.toLowerCase()) {
186
- const matchedStoredProfile = findMatchingProfile(currentAuth.availableProfiles, refetched.urls.editor);
187
- if (matchedStoredProfile && matchedStoredProfile !== currentAuth.profile) {
188
- currentAuth = await resolveCommandAuth({
189
- explicitProfile: matchedStoredProfile,
190
- interactive: true,
191
- env: options.env,
192
- homeDir: options.homeDir,
193
- });
194
- currentClient = new CodePenClient({ apiKey: currentAuth.apiKey, baseUrl: options.baseUrl });
195
- console.log(fmt.dim(`Using profile "${matchedStoredProfile}" (matches Pen owner).`));
196
- }
197
- }
198
- if (refetched.editor !== 'Classic') {
199
- const detectedUsername = refetchedOwner
200
- ? await resolveCurrentUsername(currentClient, currentAuth, refetchedOwner)
201
- : null;
202
- const ownedByOther = Boolean(refetchedOwner &&
203
- detectedUsername &&
204
- refetchedOwner.toLowerCase() !== detectedUsername.toLowerCase());
205
- const resolvedUrl = pasted
206
- ? (pastedOriginalUrl ?? refetched.urls.editor)
207
- : (refetched.urls.editor || effectiveUrl);
208
- if (!ownedByOther) {
209
- console.log(`\n${fmt.green('✓')} Pen is now CodePen 2.0 ${fmt.dim(`(${refetched.id})`)} — continuing linked clone.`);
210
- }
211
- return {
212
- action: ownedByOther ? 'clone-unlinked' : 'clone-linked',
213
- pen: refetched,
214
- effectiveUrl: resolvedUrl,
215
- auth: currentAuth,
216
- client: currentClient,
217
- isOwnedByAnotherUser: ownedByOther,
218
- penOwner: refetchedOwner,
219
- currentUsername: detectedUsername,
220
- };
221
- }
222
- if (!pasted) {
223
- fallbackPen = refetched;
224
- }
225
- console.log(`\n${fmt.yellow('!')} ${fmt.bold(refetched.title || 'Untitled')} is still a Classic (v1) Pen on CodePen.`);
226
- console.log(fmt.dim('Make sure you converted it to 2.0 via the Save button dropdown (or paste the new 2.0 Pen URL if CodePen opened a new one).\n'));
227
- const nextAction = await promptClassicRetryChoice(selectImpl);
228
- if (nextAction === 'retry') {
229
- continue;
230
- }
231
- if (nextAction === 'clone-unlinked') {
232
- return makeFallbackResult('clone-unlinked');
233
- }
234
- console.log('Aborted.');
235
- return makeFallbackResult('cancel');
236
- }
237
- }
238
- async function ensureCloneTargetReady(targetDir, folderDisplay, options) {
239
- try {
240
- const stat = await fs.lstat(targetDir);
241
- if (!stat.isDirectory()) {
242
- throw new CliError(409, `Target path ${targetDir} already exists and is not a directory.`);
243
- }
244
- }
245
- catch (error) {
246
- if (error.code === 'ENOENT') {
247
- return true;
248
- }
249
- throw error;
250
- }
251
- const [hasExistingConfig, nonEmpty] = await Promise.all([
252
- hasProjectConfigInDir(targetDir),
253
- isDirectoryNonEmpty(targetDir),
254
- ]);
255
- if ((nonEmpty || hasExistingConfig) && !options.force) {
256
- if (!options.interactive) {
257
- throw new CliError(409, `Target directory ${targetDir} is not empty. Pass --force to overwrite.`);
258
- }
259
- const ok = await options.confirmImpl(`Directory ${fmt.bold(folderDisplay)} already exists and is not empty. Continue and overwrite matching files?`, false);
260
- if (!ok) {
261
- console.log('Aborted.');
262
- return false;
263
- }
264
- }
265
- return true;
266
- }
1
+ import { getGlobalProfileOption } from '../workflows/auth-context.js';
2
+ import { clonePenWorkflow, } from '../workflows/clone-pen.js';
3
+ import { forkPenWorkflow } from '../workflows/fork-pen.js';
267
4
  /**
268
- * Clones an existing CodePen Pen into a local folder.
269
- *
270
- * When the Pen's owner does not match the current authenticated account, offers to fork it
271
- * instead (interactively). If not forked, downloads files locally without writing `.cdpn.json`
272
- * so the local folder is not linked to an online Pen owned by another user.
273
- *
274
- * When the Pen is a Classic (v1) Pen (read-only through CodePen API v2), interactively offers
275
- * a choice to open it in the browser to convert to CodePen 2.0 first (waiting to re-fetch or
276
- * accept the new 2.0 URL for a linked clone) or to clone it locally without writing `.cdpn.json`.
277
- *
278
- * Returns `null` if the user cancels interactively.
5
+ * Clones an existing CodePen Pen into a local folder, offering to convert Classic Pens
6
+ * or fork unowned Pens interactively.
279
7
  */
280
- export async function clonePenCommand(options) {
281
- const cwd = path.resolve(options.cwd ?? process.cwd());
282
- const jsonMode = Boolean(options.json);
283
- const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
284
- const force = Boolean(options.force);
285
- const textImpl = options.prompts?.text ?? promptText;
286
- const confirmImpl = options.prompts?.confirm ?? promptConfirm;
287
- const secretImpl = options.prompts?.secret ?? promptSecret;
288
- const selectImpl = options.prompts?.select ?? promptSelect;
289
- const { apiIdentifier, originalUrl } = normalizePenReference(options.urlArg);
290
- // If target folder was passed explicitly, validate before hitting the network
291
- let targetFolderDisplay = options.folderArg?.trim() || '';
292
- let targetDir = null;
293
- if (targetFolderDisplay) {
294
- targetDir = path.resolve(cwd, targetFolderDisplay);
295
- const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
296
- force,
297
- interactive,
298
- confirmImpl,
299
- });
300
- if (!ready) {
301
- return null;
302
- }
303
- }
304
- const unmatched = await findUnmatchedStoredOwner({
305
- originalUrl,
306
- explicitProfile: options.explicitProfile,
307
- env: options.env,
308
- homeDir: options.homeDir,
8
+ export async function runCloneCommand(options) {
9
+ return clonePenWorkflow({
10
+ ...options,
11
+ forkUnowned: (params) => forkPenWorkflow(params),
309
12
  });
310
- if (unmatched && originalUrl) {
311
- const pastedUrl = await handleUnownedPenAccess({
312
- action: 'clone',
313
- penUrl: originalUrl,
314
- urlOwner: unmatched.urlOwner,
315
- availableProfiles: unmatched.availableProfiles,
316
- interactive,
317
- allowBrowserFallback: options.allowBrowserFallback,
318
- confirmImpl,
319
- textImpl,
320
- openBrowserImpl: options.openBrowser,
321
- });
322
- if (!pastedUrl) {
323
- return null;
324
- }
325
- return clonePenCommand({
326
- ...options,
327
- urlArg: pastedUrl,
328
- explicitProfile: undefined,
329
- allowBrowserFallback: false,
330
- });
331
- }
332
- let auth = await resolveCommandAuth({
333
- explicitProfile: options.explicitProfile,
334
- urlHint: originalUrl ?? options.urlArg,
335
- autoSelectUrlMatch: true,
336
- promptMessage: 'Which CodePen profile should be used for this Pen?',
337
- interactive,
338
- env: options.env,
339
- homeDir: options.homeDir,
340
- selectProfile: selectImpl,
341
- });
342
- let client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
343
- if (!jsonMode &&
344
- !options.explicitProfile &&
345
- auth.source === 'file' &&
346
- auth.profile &&
347
- auth.availableProfiles.length > 1 &&
348
- findMatchingProfile(auth.availableProfiles, originalUrl ?? options.urlArg) === auth.profile) {
349
- console.log(fmt.dim(`Using profile "${auth.profile}" (matches Pen owner).`));
350
- }
351
- if (!jsonMode) {
352
- console.log(`Fetching Pen ${fmt.cyan(apiIdentifier)}…`);
353
- }
354
- let pen;
355
- try {
356
- pen = await client.getPen(apiIdentifier);
357
- }
358
- catch (error) {
359
- if (error instanceof CodePenApiError && error.status === 404) {
360
- const pastedUrl = await handlePenNotFoundOnFetch({
361
- action: 'clone',
362
- apiIdentifier,
363
- originalUrl,
364
- auth,
365
- client,
366
- interactive,
367
- allowBrowserFallback: options.allowBrowserFallback,
368
- confirmImpl,
369
- textImpl,
370
- openBrowserImpl: options.openBrowser,
371
- });
372
- if (!pastedUrl) {
373
- return null;
374
- }
375
- return clonePenCommand({
376
- ...options,
377
- urlArg: pastedUrl,
378
- explicitProfile: undefined,
379
- allowBrowserFallback: false,
380
- });
381
- }
382
- throw error;
383
- }
384
- // Check whether this Pen belongs to a stored profile (handles Pen IDs / preview URLs without an owner in the input)
385
- let penOwner = extractCodePenOwnerFromUrl(pen.urls.editor) ??
386
- (originalUrl ? extractCodePenOwnerFromUrl(originalUrl) : null);
387
- if (penOwner &&
388
- !options.explicitProfile &&
389
- auth.source === 'file' &&
390
- auth.profile?.toLowerCase() !== penOwner.toLowerCase()) {
391
- const matchedStoredProfile = findMatchingProfile(auth.availableProfiles, pen.urls.editor);
392
- if (matchedStoredProfile && matchedStoredProfile !== auth.profile) {
393
- auth = await resolveCommandAuth({
394
- explicitProfile: matchedStoredProfile,
395
- interactive,
396
- env: options.env,
397
- homeDir: options.homeDir,
398
- });
399
- client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
400
- if (!jsonMode) {
401
- console.log(fmt.dim(`Using profile "${matchedStoredProfile}" (matches Pen owner).`));
402
- }
403
- }
404
- }
405
- let currentUsername = penOwner ? await resolveCurrentUsername(client, auth, penOwner) : null;
406
- let isOwnedByAnotherUser = Boolean(penOwner && currentUsername && penOwner.toLowerCase() !== currentUsername.toLowerCase());
407
- let effectiveUrl = originalUrl ?? pen.urls.editor;
408
- if (isOwnedByAnotherUser && penOwner && currentUsername) {
409
- if (!jsonMode) {
410
- console.log(fmt.yellow(`\nThis Pen belongs to ${fmt.bold(penOwner)} (your current account is ${fmt.bold(currentUsername)}).`));
411
- }
412
- if (interactive) {
413
- const shouldFork = await confirmImpl(`Fork this Pen under ${currentUsername} instead?`, true);
414
- if (shouldFork) {
415
- const forkedResult = await forkPenCommand({
416
- urlArg: options.urlArg,
417
- folderArg: options.folderArg,
418
- cwd,
419
- resolvedAuth: auth,
420
- sourcePen: pen,
421
- allowOverwrite: Boolean(targetDir),
422
- baseUrl: options.baseUrl,
423
- interactive,
424
- env: options.env,
425
- homeDir: options.homeDir,
426
- openBrowser: options.openBrowser,
427
- prompts: {
428
- text: textImpl,
429
- confirm: confirmImpl,
430
- select: selectImpl,
431
- secret: secretImpl,
432
- },
433
- });
434
- if (!forkedResult) {
435
- return null;
436
- }
437
- return {
438
- pen: forkedResult.pen,
439
- sourcePen: forkedResult.sourcePen ?? undefined,
440
- rootDir: forkedResult.project.rootDir,
441
- writtenPaths: forkedResult.writtenPaths,
442
- auth: forkedResult.auth,
443
- forked: true,
444
- linked: true,
445
- project: forkedResult.project,
446
- };
447
- }
448
- }
449
- }
450
- if (pen.editor === 'Classic' && !isOwnedByAnotherUser && interactive) {
451
- const classicResolution = await handleClassicPenClone({
452
- pen,
453
- apiIdentifier,
454
- effectiveUrl,
455
- auth,
456
- client,
457
- options,
458
- selectImpl,
459
- textImpl,
460
- });
461
- if (classicResolution.action === 'cancel') {
462
- return null;
463
- }
464
- pen = classicResolution.pen;
465
- effectiveUrl = classicResolution.effectiveUrl;
466
- auth = classicResolution.auth;
467
- client = classicResolution.client;
468
- isOwnedByAnotherUser = classicResolution.isOwnedByAnotherUser;
469
- penOwner = classicResolution.penOwner;
470
- currentUsername = classicResolution.currentUsername;
471
- }
472
- if (!targetDir) {
473
- const defaultFolder = suggestFolderName(pen);
474
- if (interactive) {
475
- const chosen = (await textImpl('Target folder', defaultFolder)).trim();
476
- targetFolderDisplay = chosen || defaultFolder;
477
- }
478
- else {
479
- targetFolderDisplay = defaultFolder;
480
- }
481
- targetDir = path.resolve(cwd, targetFolderDisplay);
482
- const ready = await ensureCloneTargetReady(targetDir, targetFolderDisplay, {
483
- force,
484
- interactive,
485
- confirmImpl,
486
- });
487
- if (!ready) {
488
- return null;
489
- }
490
- }
491
- const remoteFiles = await client.getPenFiles(pen.id);
492
- const result = await syncRemoteFilesToDisk({
493
- client,
494
- rootDir: targetDir,
495
- remoteFiles,
496
- pruneRemoved: false,
497
- });
498
- const isUnlinked = isOwnedByAnotherUser || pen.editor === 'Classic';
499
- if (isUnlinked) {
500
- if (jsonMode) {
501
- printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay} (unlinked local copy).`, {
502
- pen,
503
- linked: false,
504
- forked: false,
505
- profile: auth.profile,
506
- folder: targetFolderDisplay,
507
- root_dir: targetDir,
508
- config_path: null,
509
- version_id: pen.saved_version?.id ?? null,
510
- written_paths: result.writtenPaths,
511
- });
512
- }
513
- else {
514
- console.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)} ${fmt.dim('(unlinked local copy)')}`);
515
- console.log(` Source: ${fmt.dim(effectiveUrl)}`);
516
- console.log(` Files: ${result.writtenPaths.length} downloaded`);
517
- if (isOwnedByAnotherUser) {
518
- console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this Pen belongs to ${penOwner}, not ${currentUsername}.\n` +
519
- `Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new Pen under your account, or \`cdpn fork ${effectiveUrl}\` to fork it on CodePen.`));
520
- }
521
- else {
522
- console.log(fmt.yellow(`\nNote: No ${PROJECT_CONFIG_FILENAME} was created because this is a Classic (v1) Pen (read-only through CodePen API v2).\n` +
523
- `Run \`cdpn push\` inside ${targetFolderDisplay} later to publish it as a new CodePen 2.0 Pen, or convert it to 2.0 on CodePen via the Save button dropdown and re-clone.`));
524
- }
525
- }
526
- return {
527
- pen,
528
- rootDir: targetDir,
529
- writtenPaths: result.writtenPaths,
530
- auth,
531
- forked: false,
532
- linked: false,
533
- project: null,
534
- };
535
- }
536
- const syncedFiles = buildSyncedFileMap(remoteFiles, result.localSha256ByPath);
537
- const config = {
538
- url: effectiveUrl,
539
- pen_id: pen.id,
540
- ...(auth.profile ? { profile: auth.profile } : {}),
541
- last_synced_version_id: pen.saved_version?.id ?? null,
542
- editor: pen.editor,
543
- ...buildPenInfoConfigFields(pen),
544
- files: syncedFiles,
545
- };
546
- const configPath = await writeProjectConfig(targetDir, config);
547
- if (jsonMode) {
548
- printJsonResponse(200, `Cloned ${pen.title || 'Untitled'} into ${targetFolderDisplay}.`, {
549
- pen,
550
- linked: true,
551
- forked: false,
552
- profile: auth.profile,
553
- folder: targetFolderDisplay,
554
- root_dir: targetDir,
555
- config_path: configPath,
556
- version_id: pen.saved_version?.id ?? null,
557
- written_paths: result.writtenPaths,
558
- });
559
- }
560
- else {
561
- console.log(`\n${fmt.green('✓')} Cloned ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} into ${fmt.cyan(targetFolderDisplay)}`);
562
- if (auth.profile) {
563
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
564
- }
565
- console.log(` Files: ${result.writtenPaths.length} downloaded`);
566
- if (pen.saved_version) {
567
- console.log(` Version: ${fmt.dim(shortId(pen.saved_version.id))}`);
568
- }
569
- console.log(` Config: ${fmt.dim(path.join(targetFolderDisplay, PROJECT_CONFIG_FILENAME))}`);
570
- }
571
- return {
572
- pen,
573
- rootDir: targetDir,
574
- writtenPaths: result.writtenPaths,
575
- auth,
576
- forked: false,
577
- linked: true,
578
- project: {
579
- rootDir: targetDir,
580
- configPath,
581
- config,
582
- },
583
- };
584
13
  }
585
14
  export function registerCloneCommand(program) {
586
15
  program
@@ -589,12 +18,15 @@ export function registerCloneCommand(program) {
589
18
  .option('-f, --force', 'Overwrite files if the target directory already exists and is not empty')
590
19
  .option('--json', 'Output clone result as JSON')
591
20
  .action(async (urlArg, folderArg, options, command) => {
592
- await clonePenCommand({
21
+ const result = await runCloneCommand({
593
22
  urlArg,
594
23
  folderArg,
595
24
  force: options.force,
596
25
  json: options.json,
597
26
  explicitProfile: getGlobalProfileOption(command),
598
27
  });
28
+ if (result?.exitCode !== undefined) {
29
+ process.exitCode = result.exitCode;
30
+ }
599
31
  });
600
32
  }