codepen-commander 1.2.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 (93) hide show
  1. package/README.md +104 -10
  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 +553 -37
  13. package/commands/deploy.js +164 -154
  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 +222 -365
  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 +179 -240
  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/workflows/create-pen.js +254 -0
  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/create-pen.js +0 -251
  91. package/commands/meta.js +0 -184
  92. package/utils/prompts.js +0 -316
  93. /package/{types.js → api/types.js} +0 -0
@@ -1,98 +1,614 @@
1
1
  import fs from 'node:fs/promises';
2
+ import path from 'node:path';
2
3
  import { CodePenClient } from '../api/client.js';
3
- import { PROJECT_CONFIG_FILENAME, requireProjectInDir, } from '../config/project.js';
4
- import { fmt } from '../utils/format.js';
5
- import { CliError, printJsonResponse } from '../utils/json.js';
6
- import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts.js';
7
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
8
- export const CODEPEN_DELETED_ITEMS_URL = 'https://codepen.io/your-work?item_type=DELETED_ITEMS';
4
+ import { findProject, hasProjectConfigInDir, normalizePartialPenInfo, requireProjectInDir, writeUnlinkedProjectInfo, } from '../config/project.js';
5
+ import { CODEPEN_DELETED_ITEMS_URL, CODEPEN_DIR, PROJECT_CONFIG_FILENAME, } from '../constants.js';
6
+ import { CliError } from '../errors.js';
7
+ import { analyzeInfoSync, extractPenInfo } from '../sync/info.js';
8
+ import { fmt, formatDate } from '../utils/format.js';
9
+ import { printJsonResponse } from '../utils/json.js';
10
+ import { defaultOutput } from '../utils/output.js';
11
+ import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts/index.js';
12
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
13
+ import { runBatchDelete } from '../workflows/batch-pens.js';
14
+ import { offerBatchAllFallback, resolveBatchCommandTarget, } from '../workflows/batch-target.js';
15
+ import { findProjectPenInTrash, isRemotePenNotFoundError, removeCodepenDirSafe, unlinkLinkedProject, } from '../workflows/missing-pen.js';
16
+ export { CODEPEN_DELETED_ITEMS_URL };
9
17
  /**
10
- * Deletes the online Pen linked to `.cdpn.json` directly inside `options.cwd`
11
- * (moves it to CodePen Deleted Items, restorable for 3 days) and removes `.cdpn.json`
12
- * only after the remote deletion succeeds. Local project files are kept untouched.
18
+ * Deletes the online Pen linked to `.cdpn.json` directly inside `options.cwd` (or an explicit
19
+ * directory `[target]`), moving it to CodePen Deleted Items (restorable for 3 days).
13
20
  *
14
- * Returns `null` if the user cancels at the confirmation prompt.
21
+ * Pass `[target]` = `"all"` to walk subdirectories and delete all discovered Pens in batch after
22
+ * an upfront two-step confirmation (unless `--yes` or `--dry-run` is passed).
23
+ *
24
+ * Local file behavior:
25
+ * - Default: keeps `.cdpn.json` (still linked) and `.codepen/` untouched so that
26
+ * a successive `cdpn status` detects the Pen in Trash and `cdpn restore` can restore it.
27
+ * - `--cleanup`: removes `.codepen/` and strips `.cdpn.json` down to unlinked `info`-only.
28
+ * - `--full-cleanup`: removes both `.codepen/` and `.cdpn.json`.
29
+ *
30
+ * Local project source files are always kept untouched.
31
+ * Returns `null` if the user cancels at a confirmation prompt.
15
32
  */
16
- export async function deletePenCommand(options = {}) {
17
- const cwd = options.cwd ?? process.cwd();
33
+ export async function runDeleteCommand(options = {}) {
34
+ const output = options.output ?? defaultOutput;
35
+ const cwd = path.resolve(options.cwd ?? process.cwd());
36
+ const dryRun = Boolean(options.dryRun);
37
+ const cleanup = Boolean(options.cleanup);
38
+ const fullCleanup = Boolean(options.fullCleanup);
18
39
  const interactive = (options.interactive ?? isInteractive()) && !options.json;
19
40
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
20
41
  const selectImpl = options.prompts?.select ?? promptSelect;
21
- // Strictly require `.cdpn.json` directly inside the current folder
22
- const project = await requireProjectInDir(cwd);
42
+ if (cleanup && fullCleanup) {
43
+ throw new CliError(400, 'Cannot combine --cleanup and --full-cleanup.');
44
+ }
45
+ const executeBatch = async (rootDir, discovered) => {
46
+ const batch = await runBatchDelete({
47
+ rootDir,
48
+ discovered,
49
+ yes: options.yes,
50
+ dryRun,
51
+ cleanup,
52
+ fullCleanup,
53
+ json: options.json,
54
+ interactive,
55
+ explicitProfile: options.explicitProfile,
56
+ baseUrl: options.baseUrl,
57
+ env: options.env,
58
+ homeDir: options.homeDir,
59
+ output,
60
+ prompts: options.prompts,
61
+ });
62
+ if (!batch) {
63
+ return null;
64
+ }
65
+ return {
66
+ pen: null,
67
+ configRemoved: false,
68
+ codepenDirRemoved: false,
69
+ configKeptLinked: false,
70
+ infoRetained: false,
71
+ dryRun,
72
+ batch,
73
+ ...(batch.exitCode !== undefined ? { exitCode: batch.exitCode } : {}),
74
+ };
75
+ };
76
+ const resolvedTarget = await resolveBatchCommandTarget({
77
+ commandName: 'delete',
78
+ cwd,
79
+ target: options.target,
80
+ interactive,
81
+ output,
82
+ prompts: options.prompts,
83
+ });
84
+ if (resolvedTarget.mode === 'batch') {
85
+ return executeBatch(resolvedTarget.rootDir, resolvedTarget.discovered);
86
+ }
87
+ const targetDir = resolvedTarget.targetDir;
88
+ // Outside a Pen directory: preserve parent-dir refusal, then offer `cdpn delete all` if child Pens exist
89
+ if (!(await hasProjectConfigInDir(targetDir))) {
90
+ const parentDir = path.dirname(targetDir);
91
+ const hasParentProject = parentDir !== targetDir && Boolean(await findProject(parentDir));
92
+ if (!hasParentProject) {
93
+ const fallback = await offerBatchAllFallback({
94
+ commandName: 'delete',
95
+ targetDir,
96
+ fromExplicitDir: resolvedTarget.fromExplicitDir,
97
+ displayDir: resolvedTarget.displayDir,
98
+ dryRun,
99
+ interactive,
100
+ output,
101
+ prompts: options.prompts,
102
+ });
103
+ if (fallback.action === 'batch') {
104
+ return executeBatch(targetDir, fallback.discovered);
105
+ }
106
+ if (fallback.action === 'canceled') {
107
+ return null;
108
+ }
109
+ }
110
+ }
111
+ // Strictly require `.cdpn.json` directly inside the target folder
112
+ const project = await requireProjectInDir(targetDir);
23
113
  const auth = await resolveCommandAuth({
24
114
  explicitProfile: options.explicitProfile,
25
115
  project,
26
116
  interactive,
27
117
  persistProfileToProject: false,
118
+ output,
28
119
  env: options.env,
29
120
  homeDir: options.homeDir,
30
121
  selectProfile: selectImpl,
31
122
  });
32
123
  const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
33
- const pen = await client.getPen(project.config.pen_id);
124
+ let pen = null;
125
+ try {
126
+ pen = await client.getPen(project.config.pen_id);
127
+ }
128
+ catch (error) {
129
+ if (!isRemotePenNotFoundError(error)) {
130
+ throw error;
131
+ }
132
+ }
133
+ // Remote Pen is already gone (in Trash or permanently deleted)
134
+ if (!pen) {
135
+ const trashItem = await findProjectPenInTrash(client, project);
136
+ const displayTitle = trashItem?.title || project.config.info?.title || 'Untitled';
137
+ let purgedFromTrash = false;
138
+ let localAction = fullCleanup
139
+ ? 'full-cleanup'
140
+ : cleanup
141
+ ? 'cleanup'
142
+ : trashItem
143
+ ? 'keep-linked'
144
+ : 'unlink-info';
145
+ if (dryRun) {
146
+ const localNote = localAction === 'full-cleanup'
147
+ ? `would remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
148
+ : localAction === 'cleanup'
149
+ ? `would remove ${CODEPEN_DIR}/ and retain info in ${PROJECT_CONFIG_FILENAME}`
150
+ : localAction === 'unlink-info'
151
+ ? `would clear remote link in ${PROJECT_CONFIG_FILENAME} (keeping ${CODEPEN_DIR}/ and info)`
152
+ : `would keep ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ untouched`;
153
+ const statusText = trashItem
154
+ ? 'already in CodePen Deleted Items'
155
+ : 'no longer exists on CodePen';
156
+ if (options.json) {
157
+ printJsonResponse(200, `Dry run complete — Pen ${displayTitle} (${project.config.pen_id}) ${statusText}; ${localNote}.`, {
158
+ pen_id: project.config.pen_id,
159
+ title: displayTitle,
160
+ profile: auth.profile,
161
+ editor_url: project.config.url,
162
+ deleted: false,
163
+ dry_run: true,
164
+ already_deleted_remotely: true,
165
+ in_trash: Boolean(trashItem),
166
+ ...(trashItem ? { trash_item: trashItem, restore_url: CODEPEN_DELETED_ITEMS_URL } : {}),
167
+ planned_local_action: localAction,
168
+ }, output);
169
+ }
170
+ else {
171
+ output.log(`\n${fmt.yellow('× [WOULD DELETE]')} ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} — ${statusText} (${localNote})`);
172
+ output.log(`\n${fmt.cyan('ℹ')} Dry run complete — no changes were made.`);
173
+ }
174
+ return {
175
+ pen: null,
176
+ project,
177
+ auth,
178
+ configRemoved: false,
179
+ codepenDirRemoved: false,
180
+ configKeptLinked: false,
181
+ infoRetained: false,
182
+ dryRun: true,
183
+ alreadyDeletedRemotely: true,
184
+ purgedFromTrash: false,
185
+ recoveredFromTrash: false,
186
+ trashItem,
187
+ };
188
+ }
189
+ if (!options.yes) {
190
+ if (!interactive) {
191
+ throw new CliError(400, 'Refusing to delete Pen in non-interactive mode without --yes.');
192
+ }
193
+ if (trashItem) {
194
+ output.log('');
195
+ output.log(`${fmt.boldYellow('!')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} is already in CodePen’s ${fmt.bold('Deleted Items (Trash)')}.`);
196
+ output.log(` ${fmt.dim('Deleted:')} ${formatDate(trashItem.deleted_at)} ${fmt.dim('·')} ${fmt.dim('Expires:')} ${fmt.yellow(formatDate(trashItem.expires_at))}`);
197
+ output.log(` ${fmt.dim('URL:')} ${fmt.cyan(project.config.url)}`);
198
+ output.log('');
199
+ const menuOptions = [
200
+ {
201
+ value: 'purge',
202
+ label: 'Delete the Pen permanently from Trash',
203
+ description: fullCleanup
204
+ ? `purge from CodePen Trash and remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
205
+ : cleanup
206
+ ? `purge from CodePen Trash, remove ${CODEPEN_DIR}/, and keep only "info" in ${PROJECT_CONFIG_FILENAME}`
207
+ : `purge from CodePen Trash and unlink ${PROJECT_CONFIG_FILENAME} (keeps ${CODEPEN_DIR}/ and "info")`,
208
+ },
209
+ ];
210
+ if (!cleanup && !fullCleanup) {
211
+ menuOptions.push({
212
+ value: 'unlink',
213
+ label: `Unlink local ${PROJECT_CONFIG_FILENAME} (keep ${CODEPEN_DIR}/ & "info")`,
214
+ description: `leave Pen in Trash until expiry and clear remote link in ${PROJECT_CONFIG_FILENAME}`,
215
+ }, {
216
+ value: 'cleanup',
217
+ label: `Remove ${CODEPEN_DIR}/ and keep only "info" in ${PROJECT_CONFIG_FILENAME}`,
218
+ description: `leave Pen in Trash until expiry, remove ${CODEPEN_DIR}/, and unlink ${PROJECT_CONFIG_FILENAME}`,
219
+ }, {
220
+ value: 'full-cleanup',
221
+ label: `Remove local ${PROJECT_CONFIG_FILENAME} & ${CODEPEN_DIR}/`,
222
+ description: `leave Pen in Trash until expiry and remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`,
223
+ });
224
+ }
225
+ else if (cleanup) {
226
+ menuOptions.push({
227
+ value: 'cleanup',
228
+ label: `Only remove ${CODEPEN_DIR}/ and keep "info" in ${PROJECT_CONFIG_FILENAME}`,
229
+ description: `leave Pen in Trash until expiry, remove ${CODEPEN_DIR}/, and unlink ${PROJECT_CONFIG_FILENAME}`,
230
+ });
231
+ }
232
+ else {
233
+ menuOptions.push({
234
+ value: 'full-cleanup',
235
+ label: `Only remove local ${PROJECT_CONFIG_FILENAME} & ${CODEPEN_DIR}/`,
236
+ description: `leave Pen in Trash until expiry and remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`,
237
+ });
238
+ }
239
+ menuOptions.push({
240
+ value: 'recover',
241
+ label: 'Restore the Pen from Trash instead',
242
+ description: `restore it on CodePen and keep ${PROJECT_CONFIG_FILENAME} linked`,
243
+ }, {
244
+ value: 'cancel',
245
+ label: 'Cancel (do nothing)',
246
+ description: `leave Trash and ${PROJECT_CONFIG_FILENAME} untouched`,
247
+ });
248
+ const choice = await selectImpl('What would you like to do?', menuOptions, 0);
249
+ if (choice === 'cancel') {
250
+ output.log('Aborted.');
251
+ return null;
252
+ }
253
+ if (choice === 'recover') {
254
+ const restoredPen = await client.restorePen(trashItem.item_id);
255
+ output.log(`\n${fmt.boldGreen('✓')} Restored ${fmt.bold(restoredPen.title || displayTitle)} ${fmt.dim(`(${restoredPen.id})`)} from CodePen Trash ${fmt.dim(`(kept ${PROJECT_CONFIG_FILENAME} linked)`)}.`);
256
+ return {
257
+ pen: restoredPen,
258
+ project,
259
+ auth,
260
+ configRemoved: false,
261
+ codepenDirRemoved: false,
262
+ configKeptLinked: true,
263
+ infoRetained: false,
264
+ alreadyDeletedRemotely: false,
265
+ purgedFromTrash: false,
266
+ recoveredFromTrash: true,
267
+ trashItem,
268
+ };
269
+ }
270
+ if (choice === 'purge') {
271
+ const confirmed = await confirmImpl(`Permanently delete "${displayTitle}" (${trashItem.item_id}) from CodePen Trash? This cannot be undone.`, false);
272
+ if (!confirmed) {
273
+ output.log('Aborted.');
274
+ return null;
275
+ }
276
+ await client.purgeTrashedPen(trashItem.item_id);
277
+ purgedFromTrash = true;
278
+ localAction = fullCleanup ? 'full-cleanup' : cleanup ? 'cleanup' : 'unlink-info';
279
+ }
280
+ else if (choice === 'full-cleanup') {
281
+ localAction = 'full-cleanup';
282
+ }
283
+ else if (choice === 'cleanup') {
284
+ localAction = 'cleanup';
285
+ }
286
+ else if (choice === 'unlink') {
287
+ localAction = 'unlink-info';
288
+ }
289
+ }
290
+ else {
291
+ output.log('');
292
+ output.log(`${fmt.boldYellow('!')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} no longer exists on CodePen (already deleted).`);
293
+ output.log(` ${fmt.dim('URL:')} ${fmt.cyan(project.config.url)}`);
294
+ output.log('');
295
+ const ok = await confirmImpl(fullCleanup
296
+ ? `Remove local ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ (local source files stay untouched)?`
297
+ : cleanup
298
+ ? `Remove ${CODEPEN_DIR}/ and keep only "info" in ${PROJECT_CONFIG_FILENAME} (local source files stay untouched)?`
299
+ : `Clear the remote link in ${PROJECT_CONFIG_FILENAME} (keeping ${CODEPEN_DIR}/, "info", and local files)?`, true);
300
+ if (!ok) {
301
+ output.log('Aborted.');
302
+ return null;
303
+ }
304
+ localAction = fullCleanup ? 'full-cleanup' : cleanup ? 'cleanup' : 'unlink-info';
305
+ }
306
+ }
307
+ let retainedInfo;
308
+ let codepenDirRemoved = false;
309
+ if (localAction === 'full-cleanup') {
310
+ await fs.unlink(project.configPath);
311
+ codepenDirRemoved = await removeCodepenDirSafe(project.rootDir);
312
+ }
313
+ else if (localAction === 'cleanup') {
314
+ const unlinked = await unlinkLinkedProject(project, trashItem?.title);
315
+ retainedInfo = unlinked.info;
316
+ codepenDirRemoved = await removeCodepenDirSafe(project.rootDir);
317
+ }
318
+ else if (localAction === 'unlink-info') {
319
+ const unlinked = await unlinkLinkedProject(project, trashItem?.title);
320
+ retainedInfo = unlinked.info;
321
+ }
322
+ const configRemoved = localAction === 'full-cleanup';
323
+ const infoRetained = localAction === 'cleanup' || localAction === 'unlink-info';
324
+ const configKeptLinked = localAction === 'keep-linked';
325
+ const removedSummary = codepenDirRemoved
326
+ ? `${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
327
+ : PROJECT_CONFIG_FILENAME;
328
+ if (options.json) {
329
+ let msg;
330
+ if (trashItem) {
331
+ if (configRemoved) {
332
+ msg = `Pen ${displayTitle} (${project.config.pen_id}) was already in CodePen Deleted Items; removed ${removedSummary}.`;
333
+ }
334
+ else if (localAction === 'cleanup') {
335
+ msg = codepenDirRemoved
336
+ ? `Pen ${displayTitle} (${project.config.pen_id}) was already in CodePen Deleted Items; removed ${CODEPEN_DIR}/ and retained info in ${PROJECT_CONFIG_FILENAME}.`
337
+ : `Pen ${displayTitle} (${project.config.pen_id}) was already in CodePen Deleted Items; retained info in ${PROJECT_CONFIG_FILENAME}.`;
338
+ }
339
+ else if (localAction === 'unlink-info') {
340
+ msg = `Pen ${displayTitle} (${project.config.pen_id}) was already in CodePen Deleted Items; retained info in ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/.`;
341
+ }
342
+ else {
343
+ msg = `Pen ${displayTitle} (${project.config.pen_id}) is already in CodePen Deleted Items (kept ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/).`;
344
+ }
345
+ }
346
+ else if (configRemoved) {
347
+ msg = `Pen ${displayTitle} (${project.config.pen_id}) no longer exists on CodePen; removed ${removedSummary}.`;
348
+ }
349
+ else if (localAction === 'cleanup') {
350
+ msg = codepenDirRemoved
351
+ ? `Pen ${displayTitle} (${project.config.pen_id}) no longer exists on CodePen; removed ${CODEPEN_DIR}/ and retained info in ${PROJECT_CONFIG_FILENAME}.`
352
+ : `Pen ${displayTitle} (${project.config.pen_id}) no longer exists on CodePen; retained info in ${PROJECT_CONFIG_FILENAME}.`;
353
+ }
354
+ else {
355
+ msg = `Pen ${displayTitle} (${project.config.pen_id}) no longer exists on CodePen; retained info in ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/.`;
356
+ }
357
+ printJsonResponse(200, msg, {
358
+ pen_id: project.config.pen_id,
359
+ title: displayTitle,
360
+ profile: auth.profile,
361
+ editor_url: project.config.url,
362
+ deleted: true,
363
+ already_deleted_remotely: true,
364
+ in_trash: Boolean(trashItem),
365
+ purged_from_trash: purgedFromTrash,
366
+ ...(trashItem ? { trash_item: trashItem, restore_url: CODEPEN_DELETED_ITEMS_URL } : {}),
367
+ config_removed: configRemoved,
368
+ codepen_dir_removed: codepenDirRemoved,
369
+ config_kept_linked: configKeptLinked,
370
+ info_retained: infoRetained,
371
+ ...(infoRetained ? { info: retainedInfo } : {}),
372
+ }, output);
373
+ }
374
+ else {
375
+ if (purgedFromTrash) {
376
+ output.log(`\n${fmt.boldGreen('✓')} Permanently deleted ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} from CodePen Trash.`);
377
+ }
378
+ else if (trashItem) {
379
+ output.log(`\n${fmt.boldGreen('✓')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} is already in CodePen Deleted Items.`);
380
+ }
381
+ else {
382
+ output.log(`\n${fmt.boldGreen('✓')} Pen ${fmt.bold(displayTitle)} ${fmt.dim(`(${project.config.pen_id})`)} no longer exists on CodePen.`);
383
+ }
384
+ if (auth.profile) {
385
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
386
+ }
387
+ if (configRemoved) {
388
+ output.log(` Removed: ${fmt.cyan(removedSummary)} ${fmt.dim('(local files were kept untouched)')}`);
389
+ }
390
+ else if (localAction === 'cleanup') {
391
+ if (codepenDirRemoved) {
392
+ output.log(` Removed: ${fmt.cyan(`${CODEPEN_DIR}/`)}`);
393
+ }
394
+ output.log(` Retained: ${fmt.cyan(`info in ${PROJECT_CONFIG_FILENAME}`)} ${fmt.dim('(unlinked; local files were kept untouched)')}`);
395
+ }
396
+ else if (localAction === 'unlink-info') {
397
+ output.log(` Retained: ${fmt.cyan(`${CODEPEN_DIR}/ and info in ${PROJECT_CONFIG_FILENAME}`)} ${fmt.dim('(unlinked; local files were kept untouched)')}`);
398
+ }
399
+ else {
400
+ output.log(` Local: ${fmt.cyan(`${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ kept untouched`)}`);
401
+ }
402
+ if (trashItem && !purgedFromTrash) {
403
+ output.log(` Restore: Run \`cdpn restore\` ${fmt.dim(`(or ${CODEPEN_DELETED_ITEMS_URL})`)}`);
404
+ }
405
+ }
406
+ return {
407
+ pen: null,
408
+ project,
409
+ auth,
410
+ configRemoved,
411
+ codepenDirRemoved,
412
+ configKeptLinked,
413
+ infoRetained,
414
+ ...(retainedInfo ? { retainedInfo } : {}),
415
+ alreadyDeletedRemotely: true,
416
+ purgedFromTrash,
417
+ recoveredFromTrash: false,
418
+ trashItem,
419
+ };
420
+ }
421
+ const localAction = fullCleanup
422
+ ? 'full-cleanup'
423
+ : cleanup
424
+ ? 'cleanup'
425
+ : 'keep-linked';
426
+ if (dryRun) {
427
+ const localNote = localAction === 'full-cleanup'
428
+ ? `would remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
429
+ : localAction === 'cleanup'
430
+ ? `would remove ${CODEPEN_DIR}/ and retain info in ${PROJECT_CONFIG_FILENAME}`
431
+ : `would keep ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ untouched`;
432
+ if (options.json) {
433
+ printJsonResponse(200, `Dry run complete — would delete ${pen.title || 'Untitled'} (${pen.id}) on CodePen (${localNote}).`, {
434
+ pen_id: pen.id,
435
+ title: pen.title,
436
+ profile: auth.profile,
437
+ editor_url: pen.urls.editor,
438
+ deleted: false,
439
+ dry_run: true,
440
+ would_delete: true,
441
+ planned_local_action: localAction,
442
+ }, output);
443
+ }
444
+ else {
445
+ output.log(`\n${fmt.yellow('× [WOULD DELETE]')} ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
446
+ if (auth.profile) {
447
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
448
+ }
449
+ output.log(` Editor: ${fmt.cyan(pen.urls.editor)}`);
450
+ if (pen.deployment) {
451
+ output.log(` Live: ${fmt.yellow(pen.deployment.url)} ${fmt.dim('(would also be taken down)')}`);
452
+ }
453
+ output.log(` Local: ${fmt.dim(localNote)}`);
454
+ output.log(`\n${fmt.cyan('ℹ')} Dry run complete — no changes were made.`);
455
+ }
456
+ return {
457
+ pen,
458
+ project,
459
+ auth,
460
+ configRemoved: false,
461
+ codepenDirRemoved: false,
462
+ configKeptLinked: false,
463
+ infoRetained: false,
464
+ dryRun: true,
465
+ };
466
+ }
34
467
  if (!options.yes) {
35
468
  if (!interactive) {
36
469
  throw new CliError(400, 'Refusing to delete Pen in non-interactive mode without --yes.');
37
470
  }
38
- console.log(`\n${fmt.yellow('About to delete online Pen:')}`);
39
- console.log(` Title: ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
471
+ output.log(`\n${fmt.yellow('About to delete online Pen:')}`);
472
+ output.log(` Title: ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}`);
40
473
  if (auth.profile) {
41
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
474
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
42
475
  }
43
- console.log(` Editor: ${fmt.cyan(pen.urls.editor)}`);
476
+ output.log(` Editor: ${fmt.cyan(pen.urls.editor)}`);
44
477
  if (pen.deployment) {
45
- console.log(` Live: ${fmt.yellow(pen.deployment.url)} ${fmt.dim('(will also be taken down)')}`);
478
+ output.log(` Live: ${fmt.yellow(pen.deployment.url)} ${fmt.dim('(will also be taken down)')}`);
46
479
  }
47
- console.log(fmt.dim(`\nLocal files will stay untouched; ${PROJECT_CONFIG_FILENAME} will be removed after deletion succeeds.`));
48
- const ok = await confirmImpl(`Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME}?`, false);
480
+ output.log(fmt.dim(localAction === 'full-cleanup'
481
+ ? `\nLocal source files will stay untouched; ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ will be removed after deletion succeeds.`
482
+ : localAction === 'cleanup'
483
+ ? `\nLocal source files will stay untouched; ${CODEPEN_DIR}/ will be removed and only the "info" section will be kept in ${PROJECT_CONFIG_FILENAME} (unlinked) after deletion succeeds.`
484
+ : `\nLocal source files, ${PROJECT_CONFIG_FILENAME}, and ${CODEPEN_DIR}/ will stay untouched so you can restore the Pen with \`cdpn restore\` or inspect it with \`cdpn status\`.`));
485
+ const ok = await confirmImpl(localAction === 'full-cleanup'
486
+ ? `Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/?`
487
+ : localAction === 'cleanup'
488
+ ? `Delete this Pen on CodePen (moves to Deleted Items for 3 days), remove ${CODEPEN_DIR}/, and keep only "info" in ${PROJECT_CONFIG_FILENAME}?`
489
+ : 'Delete this Pen on CodePen (moves to Deleted Items for 3 days)?', false);
49
490
  if (!ok) {
50
- console.log('Aborted.');
491
+ output.log('Aborted.');
51
492
  return null;
52
493
  }
53
494
  }
54
- await client.deletePen(project.config.pen_id);
55
- // Remove `.cdpn.json` only after remote deletion succeeded
56
- await fs.unlink(project.configPath);
495
+ let alreadyDeletedRemotely = false;
496
+ try {
497
+ await client.deletePen(project.config.pen_id);
498
+ }
499
+ catch (error) {
500
+ if (isRemotePenNotFoundError(error)) {
501
+ alreadyDeletedRemotely = true;
502
+ }
503
+ else {
504
+ throw error;
505
+ }
506
+ }
507
+ // Only mutate/remove local config files after remote deletion succeeds (or Pen was already gone)
508
+ let retainedInfo;
509
+ let codepenDirRemoved = false;
510
+ if (localAction === 'full-cleanup') {
511
+ await fs.unlink(project.configPath);
512
+ codepenDirRemoved = await removeCodepenDirSafe(project.rootDir);
513
+ }
514
+ else if (localAction === 'cleanup') {
515
+ const remoteInfo = extractPenInfo(pen);
516
+ const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, pen);
517
+ retainedInfo =
518
+ infoAnalysis.localChanged && project.config.info
519
+ ? { ...remoteInfo, ...normalizePartialPenInfo(project.config.info) }
520
+ : remoteInfo;
521
+ await writeUnlinkedProjectInfo(project.rootDir, retainedInfo);
522
+ codepenDirRemoved = await removeCodepenDirSafe(project.rootDir);
523
+ }
524
+ const configRemoved = localAction === 'full-cleanup';
525
+ const infoRetained = localAction === 'cleanup';
526
+ const configKeptLinked = localAction === 'keep-linked';
527
+ const removedSummary = codepenDirRemoved
528
+ ? `${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
529
+ : PROJECT_CONFIG_FILENAME;
57
530
  if (options.json) {
58
- printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${PROJECT_CONFIG_FILENAME}.`, {
531
+ const message = configRemoved
532
+ ? `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${removedSummary}.`
533
+ : infoRetained
534
+ ? codepenDirRemoved
535
+ ? `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen, removed ${CODEPEN_DIR}/, and retained info in ${PROJECT_CONFIG_FILENAME}.`
536
+ : `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and retained info in ${PROJECT_CONFIG_FILENAME}.`
537
+ : `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen (kept ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/).`;
538
+ printJsonResponse(200, message, {
59
539
  pen_id: pen.id,
60
540
  title: pen.title,
61
541
  profile: auth.profile,
62
542
  editor_url: pen.urls.editor,
63
543
  deleted: true,
64
- config_removed: true,
544
+ ...(alreadyDeletedRemotely ? { already_deleted_remotely: true } : {}),
545
+ config_removed: configRemoved,
546
+ codepen_dir_removed: codepenDirRemoved,
547
+ config_kept_linked: configKeptLinked,
548
+ info_retained: infoRetained,
549
+ ...(infoRetained ? { info: retainedInfo } : {}),
65
550
  restore_url: CODEPEN_DELETED_ITEMS_URL,
66
- });
551
+ }, output);
67
552
  }
68
553
  else {
69
- console.log(`\n${fmt.green('✓')} Deleted ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} on CodePen ${fmt.dim('(moved to Deleted Items; restorable for 3 days)')}`);
554
+ output.log(`\n${fmt.green('✓')} Deleted ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} on CodePen ${fmt.dim('(moved to Deleted Items; restorable for 3 days)')}`);
70
555
  if (auth.profile) {
71
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
556
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
557
+ }
558
+ if (configRemoved) {
559
+ output.log(` Removed: ${fmt.cyan(removedSummary)} ${fmt.dim('(local files were kept untouched)')}`);
560
+ output.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
561
+ }
562
+ else if (infoRetained) {
563
+ if (codepenDirRemoved) {
564
+ output.log(` Removed: ${fmt.cyan(`${CODEPEN_DIR}/`)}`);
565
+ }
566
+ output.log(` Retained: ${fmt.cyan(`info in ${PROJECT_CONFIG_FILENAME}`)} ${fmt.dim('(unlinked; local files were kept untouched)')}`);
567
+ output.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
568
+ }
569
+ else {
570
+ output.log(` Local: ${fmt.cyan(`${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ kept untouched`)}`);
571
+ output.log(` Restore: Run \`cdpn restore\` ${fmt.dim(`(or ${CODEPEN_DELETED_ITEMS_URL})`)}`);
572
+ output.log(` ${fmt.dim(`Tip: Run \`cdpn unlink\` to unlink, \`cdpn delete --cleanup\` to remove ${CODEPEN_DIR}/ while keeping info, or \`cdpn delete --full-cleanup\` to remove both ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/.`)}`);
72
573
  }
73
- console.log(` Removed: ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(local files were kept untouched)')}`);
74
- console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
75
574
  }
76
575
  return {
77
576
  pen,
78
577
  project,
79
578
  auth,
80
- configRemoved: true,
579
+ configRemoved,
580
+ codepenDirRemoved,
581
+ configKeptLinked,
582
+ infoRetained,
583
+ dryRun: false,
584
+ ...(retainedInfo ? { retainedInfo } : {}),
585
+ ...(alreadyDeletedRemotely ? { alreadyDeletedRemotely: true } : {}),
81
586
  };
82
587
  }
83
588
  export function registerDeleteCommand(program) {
84
589
  program
85
590
  .command('delete')
86
591
  .aliases(['del', 'rm'])
592
+ .argument('[target]', 'Directory path to delete, or "all" to delete all Pens in subdirectories')
87
593
  .allowExcessArguments(false)
88
- .description(`Delete the online Pen on CodePen (moves to Deleted Items) and remove ${PROJECT_CONFIG_FILENAME}`)
594
+ .description(`Delete the online Pen on CodePen (pass "all" to walk subdirectories; keeps ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ unless --cleanup or --full-cleanup is passed)`)
595
+ .option('--cleanup', `Remove ${CODEPEN_DIR}/ and keep only the unlinked "info" section in ${PROJECT_CONFIG_FILENAME} (local source files stay untouched)`)
596
+ .option('--full-cleanup', `Remove both ${CODEPEN_DIR}/ and ${PROJECT_CONFIG_FILENAME} (local source files stay untouched)`)
597
+ .option('--dry-run', 'Preview what would be deleted without modifying CodePen or local files')
89
598
  .option('-y, --yes', 'Skip confirmation prompt')
90
599
  .option('--json', 'Output deletion result as JSON')
91
- .action(async (options, command) => {
92
- await deletePenCommand({
600
+ .action(async (target, options, command) => {
601
+ const result = await runDeleteCommand({
602
+ target,
93
603
  yes: options.yes,
604
+ dryRun: options.dryRun,
605
+ cleanup: options.cleanup,
606
+ fullCleanup: options.fullCleanup,
94
607
  json: options.json,
95
608
  explicitProfile: getGlobalProfileOption(command),
96
609
  });
610
+ if (result?.exitCode !== undefined) {
611
+ process.exitCode = result.exitCode;
612
+ }
97
613
  });
98
614
  }