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
@@ -0,0 +1,1647 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { CodePenClient } from '../api/client.js';
4
+ import { isCodePenApiError } from '../api/errors.js';
5
+ import { normalizePartialPenInfo, writeUnlinkedProjectInfo, } from '../config/project.js';
6
+ import { CODEPEN_DELETED_ITEMS_URL, CODEPEN_DIR, MAX_PEN_TAGS, PROJECT_CONFIG_FILENAME, } from '../constants.js';
7
+ import { CliError } from '../errors.js';
8
+ import { scanLocalFiles } from '../sync/fs.js';
9
+ import { analyzeInfoSync, extractPenInfo, formatInfoValue, } from '../sync/info.js';
10
+ import { assertValidProtectedPassword, normalizeAccess, resolveAccessOrVisibility, } from '../utils/cli-options.js';
11
+ import { extractPenIdFromUrl } from '../utils/codepen-url.js';
12
+ import { fmt, formatDate, shortId } from '../utils/format.js';
13
+ import { extractHtmlTitle } from '../utils/html.js';
14
+ import { printJsonResponse } from '../utils/json.js';
15
+ import { defaultOutput } from '../utils/output.js';
16
+ import { promptConfirm } from '../utils/prompts/index.js';
17
+ import { resolveCommandAuth } from './auth-context.js';
18
+ import { createPenFromDirectory } from './create-pen.js';
19
+ import { isRemotePenNotFoundError, removeCodepenDirSafe, unlinkLinkedProject, } from './missing-pen.js';
20
+ import { executePull } from './pull-pen.js';
21
+ import { executePush } from './push-pen.js';
22
+ import { formatFileDiffLines, formatSyncChangeSummary, inspectLinkedPenSyncState, } from './sync-pen.js';
23
+ function createEmptyCounts(discoveredCount) {
24
+ return {
25
+ discovered: discoveredCount,
26
+ created: 0,
27
+ pushed: 0,
28
+ pulled: 0,
29
+ deleted: 0,
30
+ unlinked: 0,
31
+ upToDate: 0,
32
+ skipped: 0,
33
+ conflicts: 0,
34
+ errors: 0,
35
+ };
36
+ }
37
+ function formatErrorMessage(error, penId, relPath) {
38
+ if (isRemotePenNotFoundError(error) && penId) {
39
+ const location = relPath ? ` inside ${relPath}` : '';
40
+ return `Remote Pen (${penId}) not found on CodePen (it may be in Deleted Items — run \`cdpn status\` or \`cdpn restore\`${location}).`;
41
+ }
42
+ if (isCodePenApiError(error)) {
43
+ return error.formatForUser();
44
+ }
45
+ return error instanceof Error ? error.message : String(error);
46
+ }
47
+ function createBatchAuthResolver(options) {
48
+ const clientsByKey = new Map();
49
+ let cachedFallback = null;
50
+ const cachedByProfile = new Map();
51
+ function getClient(apiKey) {
52
+ let client = clientsByKey.get(apiKey);
53
+ if (!client) {
54
+ client = new CodePenClient({ apiKey, baseUrl: options.baseUrl });
55
+ clientsByKey.set(apiKey, client);
56
+ }
57
+ return client;
58
+ }
59
+ async function resolveFallback() {
60
+ if (cachedFallback)
61
+ return cachedFallback;
62
+ const auth = await resolveCommandAuth({
63
+ explicitProfile: options.explicitProfile,
64
+ promptMessage: 'Which CodePen account/profile would you like to use for unlinked Pens?',
65
+ interactive: options.interactive,
66
+ persistProfileToProject: false,
67
+ output: options.output,
68
+ env: options.env,
69
+ homeDir: options.homeDir,
70
+ selectProfile: options.selectProfile,
71
+ });
72
+ cachedFallback = { auth, client: getClient(auth.apiKey) };
73
+ return cachedFallback;
74
+ }
75
+ async function resolveForProject(project) {
76
+ const profileKey = options.explicitProfile ?? project.config.profile;
77
+ if (!profileKey) {
78
+ return resolveFallback();
79
+ }
80
+ const existing = cachedByProfile.get(profileKey);
81
+ if (existing)
82
+ return existing;
83
+ const auth = await resolveCommandAuth({
84
+ explicitProfile: options.explicitProfile,
85
+ project,
86
+ interactive: false,
87
+ persistProfileToProject: false,
88
+ output: options.output,
89
+ env: options.env,
90
+ homeDir: options.homeDir,
91
+ });
92
+ const resolved = { auth, client: getClient(auth.apiKey) };
93
+ cachedByProfile.set(profileKey, resolved);
94
+ return resolved;
95
+ }
96
+ return { resolveForProject, resolveFallback };
97
+ }
98
+ /**
99
+ * Performs the upfront two-step confirmation for destructive batch commands (`delete` and `unlink`):
100
+ * 1. First yes/No prompt (defaults to No) — bails out immediately if declined.
101
+ * 2. Second confirmation `"Are you really sure?"` (defaults to No) — proceeds with all Pens only if confirmed.
102
+ */
103
+ export async function confirmBatchDestructiveAction(options) {
104
+ const { action, targets, cleanup, fullCleanup, yes, interactive, output } = options;
105
+ if (yes || targets.length === 0) {
106
+ return true;
107
+ }
108
+ if (!interactive) {
109
+ throw new CliError(400, `Refusing to ${action} ${targets.length} Pen(s) in non-interactive mode without --yes.`);
110
+ }
111
+ const confirmImpl = options.confirm ?? promptConfirm;
112
+ const count = targets.length;
113
+ const plural = count === 1 ? 'Pen' : 'Pens';
114
+ output.log('');
115
+ output.log(fmt.yellow(action === 'delete'
116
+ ? `About to delete ${count} online ${plural} on CodePen:`
117
+ : `About to unlink ${count} local ${plural} from CodePen:`));
118
+ for (const target of targets) {
119
+ const titlePart = target.title ? ` — ${target.title}` : '';
120
+ output.log(` ${fmt.cyan(target.relPath)}${titlePart} ${fmt.dim(`(${target.url || target.penId})`)}`);
121
+ }
122
+ if (action === 'delete') {
123
+ output.log(fmt.dim(fullCleanup
124
+ ? `\nLocal source files will stay untouched; ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/ will be removed from each folder after deletion succeeds.`
125
+ : cleanup
126
+ ? `\nLocal source files will stay untouched; ${CODEPEN_DIR}/ will be removed and only "info" will be kept in ${PROJECT_CONFIG_FILENAME} (unlinked) after deletion succeeds.`
127
+ : `\nLocal source files, ${PROJECT_CONFIG_FILENAME}, and ${CODEPEN_DIR}/ will stay untouched so you can restore Pens with \`cdpn restore\`.`));
128
+ }
129
+ else {
130
+ output.log(fmt.dim(`\nOnline Pens on CodePen, ${CODEPEN_DIR}/, and all local source files will stay untouched.\n` +
131
+ `Only the remote link fields in each ${PROJECT_CONFIG_FILENAME} will be cleared (keeping "info").`));
132
+ }
133
+ output.log('');
134
+ const firstQuestion = action === 'delete'
135
+ ? fullCleanup
136
+ ? `Delete ${count} online ${plural} on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/?`
137
+ : cleanup
138
+ ? `Delete ${count} online ${plural} on CodePen (moves to Deleted Items for 3 days), remove ${CODEPEN_DIR}/, and keep only "info" in ${PROJECT_CONFIG_FILENAME}?`
139
+ : `Delete ${count} online ${plural} on CodePen (moves to Deleted Items for 3 days)?`
140
+ : `Unlink ${count} local ${plural} from CodePen (keeps online Pens, ${CODEPEN_DIR}/, and "info" in ${PROJECT_CONFIG_FILENAME})?`;
141
+ const firstOk = await confirmImpl(firstQuestion, false);
142
+ if (!firstOk) {
143
+ output.log('Aborted.');
144
+ return false;
145
+ }
146
+ const secondOk = await confirmImpl('Are you really sure?', false);
147
+ if (!secondOk) {
148
+ output.log('Aborted.');
149
+ return false;
150
+ }
151
+ output.log('');
152
+ return true;
153
+ }
154
+ function buildSummaryMessage(mode, counts, dryRun) {
155
+ const prefix = dryRun ? '[DRY RUN] ' : '';
156
+ const parts = [];
157
+ if (mode === 'push' || mode === 'sync') {
158
+ parts.push(`${counts.created} created`, `${counts.pushed} pushed`);
159
+ }
160
+ if (mode === 'pull' || mode === 'sync') {
161
+ parts.push(`${counts.pulled} pulled`);
162
+ }
163
+ if (mode === 'delete') {
164
+ parts.push(`${counts.deleted} deleted`);
165
+ }
166
+ if (mode === 'unlink') {
167
+ parts.push(`${counts.unlinked} unlinked`);
168
+ }
169
+ if (mode === 'push' || mode === 'pull' || mode === 'sync') {
170
+ parts.push(`${counts.upToDate} up to date`);
171
+ }
172
+ parts.push(`${counts.skipped} skipped`);
173
+ if (mode === 'push' || mode === 'pull' || mode === 'sync') {
174
+ parts.push(`${counts.conflicts} conflicts`);
175
+ }
176
+ parts.push(`${counts.errors} errors`);
177
+ return `${prefix}Batch ${mode} complete (${counts.discovered} discovered): ${parts.join(', ')}.`;
178
+ }
179
+ function finalizeBatchResult(options) {
180
+ const { mode, dryRun, rootDir, counts, results, jsonMode, output } = options;
181
+ const hasBlockingFailure = counts.errors > 0 || (!dryRun && counts.conflicts > 0);
182
+ const exitCode = hasBlockingFailure ? 1 : undefined;
183
+ if (jsonMode) {
184
+ const statusCode = counts.errors > 0 ? 500 : !dryRun && counts.conflicts > 0 ? 409 : 200;
185
+ printJsonResponse(statusCode, buildSummaryMessage(mode, counts, dryRun), {
186
+ batch: true,
187
+ mode,
188
+ dry_run: dryRun,
189
+ root_dir: rootDir,
190
+ counts: {
191
+ discovered: counts.discovered,
192
+ created: counts.created,
193
+ pushed: counts.pushed,
194
+ pulled: counts.pulled,
195
+ deleted: counts.deleted,
196
+ unlinked: counts.unlinked,
197
+ up_to_date: counts.upToDate,
198
+ skipped: counts.skipped,
199
+ conflicts: counts.conflicts,
200
+ errors: counts.errors,
201
+ },
202
+ results: results.map((item) => ({
203
+ path: item.path,
204
+ root_dir: item.rootDir,
205
+ action: item.action,
206
+ dry_run: item.dryRun,
207
+ ...(item.penId ? { pen_id: item.penId } : {}),
208
+ ...(item.url ? { url: item.url } : {}),
209
+ ...(item.title ? { title: item.title } : {}),
210
+ ...(item.versionId !== undefined ? { version_id: item.versionId } : {}),
211
+ ...(item.reason ? { reason: item.reason } : {}),
212
+ ...(item.error ? { error: item.error } : {}),
213
+ })),
214
+ }, output);
215
+ }
216
+ else {
217
+ const prefix = dryRun ? '[DRY RUN] ' : '';
218
+ output.log(`\n${fmt.bold(`${prefix}Summary (${mode}):`)}`);
219
+ output.log(` Found: ${counts.discovered}`);
220
+ if (mode === 'push' || mode === 'sync') {
221
+ output.log(` Created: ${counts.created}`);
222
+ output.log(` Pushed: ${counts.pushed}`);
223
+ }
224
+ if (mode === 'pull' || mode === 'sync') {
225
+ output.log(` Pulled: ${counts.pulled}`);
226
+ }
227
+ if (mode === 'delete') {
228
+ output.log(` Deleted: ${counts.deleted}`);
229
+ }
230
+ if (mode === 'unlink') {
231
+ output.log(` Unlinked: ${counts.unlinked}`);
232
+ }
233
+ if (mode === 'push' || mode === 'pull' || mode === 'sync') {
234
+ output.log(` Up to date: ${counts.upToDate}`);
235
+ }
236
+ output.log(` Skipped: ${counts.skipped}`);
237
+ if (mode === 'push' || mode === 'pull' || mode === 'sync') {
238
+ output.log(` Conflicts: ${counts.conflicts}`);
239
+ }
240
+ output.log(` Errors: ${counts.errors}`);
241
+ if (mode === 'delete' && !dryRun && counts.deleted > 0) {
242
+ output.log(`\n${fmt.dim('Deleted Pens move to CodePen Deleted Items (restorable for 3 days):')}`);
243
+ output.log(` ${fmt.cyan(CODEPEN_DELETED_ITEMS_URL)}`);
244
+ }
245
+ const conflicts = results.filter((r) => r.action === 'conflict');
246
+ if (conflicts.length > 0) {
247
+ output.log(`\n${fmt.yellow('Conflicts requiring manual resolution:')}`);
248
+ for (const c of conflicts) {
249
+ output.log(` - ${c.path}${c.url ? ` (${c.url})` : ''}`);
250
+ }
251
+ }
252
+ const errors = results.filter((r) => r.action === 'error');
253
+ if (errors.length > 0) {
254
+ output.log(`\n${fmt.red('Errors:')}`);
255
+ for (const e of errors) {
256
+ output.log(` - ${e.path}: ${e.error ?? 'Unknown error'}`);
257
+ }
258
+ }
259
+ }
260
+ return {
261
+ batch: true,
262
+ mode,
263
+ dryRun,
264
+ rootDir,
265
+ counts,
266
+ results,
267
+ ...(exitCode !== undefined ? { exitCode } : {}),
268
+ };
269
+ }
270
+ function logBatchHeader(mode, discoveredCount, dryRun, jsonMode, output) {
271
+ if (jsonMode)
272
+ return;
273
+ const prefix = dryRun ? `${fmt.cyan('[DRY RUN]')} ` : '';
274
+ const plural = discoveredCount === 1 ? 'Pen' : 'Pens';
275
+ output.log(`${prefix}Walking directory tree (${fmt.bold(mode)}) — found ${fmt.bold(String(discoveredCount))} ${plural}.\n`);
276
+ }
277
+ function logConflictDetails(relPath, inspection, output) {
278
+ output.log(`${fmt.yellow('! [CONFLICT]')} ${fmt.bold(relPath)}`);
279
+ output.log(` Pen: ${fmt.cyan(inspection.pen.urls.editor || inspection.pen.id)}`);
280
+ if (inspection.remoteVersionChanged) {
281
+ output.log(` Synced version: ${shortId(inspection.localHead)} → Remote head: ${shortId(inspection.remoteHead)}`);
282
+ }
283
+ if (!inspection.hasFileBaseline) {
284
+ output.log(` Local baseline missing in ${PROJECT_CONFIG_FILENAME}; cannot rule out local edits.`);
285
+ }
286
+ if (inspection.diffCount > 0) {
287
+ for (const line of formatFileDiffLines(inspection.diff, 'push', ' ')) {
288
+ output.log(line);
289
+ }
290
+ }
291
+ if (inspection.infoAnalysis.changes.length > 0) {
292
+ const fields = inspection.infoAnalysis.changes.map((c) => c.field).join(', ');
293
+ output.log(` Pen info differences: ${fields}`);
294
+ }
295
+ output.log(fmt.dim(` Resolve in ${relPath}: run \`cdpn status\`, then \`cdpn push --force\` or \`cdpn pull --force\`.`));
296
+ }
297
+ async function handleBatchUnlinkedCreate(options) {
298
+ const { pen, retainedInfo, resolvedAccess, password, force, wait, dryRun, jsonMode, authResolver, output, counts, results, } = options;
299
+ try {
300
+ const effectiveAccess = resolvedAccess ?? normalizeAccess(retainedInfo.access) ?? 'Public';
301
+ if (retainedInfo.tags && retainedInfo.tags.length > MAX_PEN_TAGS) {
302
+ throw new CliError(400, `CodePen allows at most ${MAX_PEN_TAGS} tags per Pen (found ${retainedInfo.tags.length} in ${PROJECT_CONFIG_FILENAME}).`);
303
+ }
304
+ assertValidProtectedPassword(effectiveAccess, password, false);
305
+ const scanned = await scanLocalFiles(pen.rootDir);
306
+ if (scanned.size === 0) {
307
+ throw new CliError(400, `No syncable files found in ${pen.relPath} (only an unlinked ${PROJECT_CONFIG_FILENAME} is present).`);
308
+ }
309
+ const indexFile = scanned.get('/index.html');
310
+ if (!indexFile && !force) {
311
+ throw new CliError(400, `No index.html found in ${pen.relPath}. Pass --force to push without an index.html.`);
312
+ }
313
+ const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
314
+ ? extractHtmlTitle(indexFile.textContent)
315
+ : null;
316
+ const title = retainedInfo.title?.trim() || htmlTitle || path.basename(pen.rootDir) || 'Untitled';
317
+ if (dryRun) {
318
+ if (!jsonMode) {
319
+ output.log(`${fmt.green('+ [WOULD CREATE]')} ${fmt.bold(pen.relPath)} — new ${effectiveAccess} Pen "${title}" (${scanned.size} file(s))`);
320
+ }
321
+ counts.created++;
322
+ results.push({
323
+ path: pen.relPath,
324
+ rootDir: pen.rootDir,
325
+ action: 'created',
326
+ dryRun: true,
327
+ title,
328
+ });
329
+ return;
330
+ }
331
+ const { auth } = await authResolver.resolveFallback();
332
+ if (!jsonMode) {
333
+ output.log(`${fmt.green('+ [CREATING]')} ${fmt.bold(pen.relPath)} — creating new ${effectiveAccess} Pen "${title}"…`);
334
+ }
335
+ const created = await createPenFromDirectory({
336
+ targetDir: pen.rootDir,
337
+ folderDisplay: pen.relPath,
338
+ explicitProfile: auth.profile ?? undefined,
339
+ access: effectiveAccess,
340
+ password,
341
+ force,
342
+ wait,
343
+ silent: true,
344
+ interactive: false,
345
+ baseUrl: options.baseUrl,
346
+ env: options.env,
347
+ homeDir: options.homeDir,
348
+ output,
349
+ });
350
+ if (!created) {
351
+ counts.skipped++;
352
+ results.push({
353
+ path: pen.relPath,
354
+ rootDir: pen.rootDir,
355
+ action: 'skipped',
356
+ dryRun: false,
357
+ reason: 'Canceled',
358
+ });
359
+ return;
360
+ }
361
+ if (created.exitCode) {
362
+ const msg = `Created Pen ${created.pen.urls.editor || created.pen.id}, but the initial build failed.`;
363
+ if (!jsonMode) {
364
+ output.log(` ${fmt.red('✗')} ${msg}`);
365
+ }
366
+ counts.errors++;
367
+ results.push({
368
+ path: pen.relPath,
369
+ rootDir: pen.rootDir,
370
+ action: 'error',
371
+ dryRun: false,
372
+ penId: created.pen.id,
373
+ url: created.pen.urls.editor,
374
+ title: created.pen.title,
375
+ versionId: created.versionId,
376
+ error: msg,
377
+ });
378
+ return;
379
+ }
380
+ if (!jsonMode) {
381
+ output.log(` ${fmt.green('✓')} Created ${created.pen.access} Pen: ${fmt.cyan(created.pen.urls.editor || created.pen.id)}`);
382
+ }
383
+ counts.created++;
384
+ results.push({
385
+ path: pen.relPath,
386
+ rootDir: pen.rootDir,
387
+ action: 'created',
388
+ dryRun: false,
389
+ penId: created.pen.id,
390
+ url: created.pen.urls.editor,
391
+ title: created.pen.title,
392
+ versionId: created.versionId,
393
+ });
394
+ }
395
+ catch (error) {
396
+ const message = formatErrorMessage(error);
397
+ if (!jsonMode) {
398
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
399
+ output.log(` ${message}`);
400
+ }
401
+ counts.errors++;
402
+ results.push({
403
+ path: pen.relPath,
404
+ rootDir: pen.rootDir,
405
+ action: 'error',
406
+ dryRun,
407
+ error: message,
408
+ });
409
+ }
410
+ }
411
+ async function runBatchPushOrSync(mode, options) {
412
+ const output = options.output ?? defaultOutput;
413
+ const dryRun = Boolean(options.dryRun);
414
+ const jsonMode = Boolean(options.json);
415
+ const interactive = !jsonMode && Boolean(options.interactive);
416
+ const force = Boolean(options.force);
417
+ const resolvedAccess = resolveAccessOrVisibility(options.access, options.visibility);
418
+ assertValidProtectedPassword(resolvedAccess, options.password, false);
419
+ const counts = createEmptyCounts(options.discovered.length);
420
+ const results = [];
421
+ logBatchHeader(mode, options.discovered.length, dryRun, jsonMode, output);
422
+ const authResolver = createBatchAuthResolver({
423
+ explicitProfile: options.explicitProfile,
424
+ interactive,
425
+ baseUrl: options.baseUrl,
426
+ env: options.env,
427
+ homeDir: options.homeDir,
428
+ output,
429
+ selectProfile: options.prompts?.select,
430
+ });
431
+ // Validate explicit profile early if provided (fail fast on typo or missing key)
432
+ if (options.explicitProfile) {
433
+ await authResolver.resolveFallback();
434
+ }
435
+ for (const pen of options.discovered) {
436
+ if (pen.parseError || !pen.parsed) {
437
+ const message = pen.parseError ?? `Invalid ${PROJECT_CONFIG_FILENAME}`;
438
+ if (!jsonMode) {
439
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
440
+ output.log(` ${message}`);
441
+ }
442
+ counts.errors++;
443
+ results.push({
444
+ path: pen.relPath,
445
+ rootDir: pen.rootDir,
446
+ action: 'error',
447
+ dryRun,
448
+ error: message,
449
+ });
450
+ continue;
451
+ }
452
+ if (!pen.parsed.linked) {
453
+ await handleBatchUnlinkedCreate({
454
+ pen,
455
+ retainedInfo: pen.parsed.config.info,
456
+ resolvedAccess,
457
+ password: options.password,
458
+ force,
459
+ wait: options.wait,
460
+ dryRun,
461
+ jsonMode,
462
+ authResolver,
463
+ baseUrl: options.baseUrl,
464
+ env: options.env,
465
+ homeDir: options.homeDir,
466
+ output,
467
+ counts,
468
+ results,
469
+ });
470
+ continue;
471
+ }
472
+ const project = {
473
+ rootDir: pen.rootDir,
474
+ configPath: pen.configPath,
475
+ config: pen.parsed.config,
476
+ };
477
+ try {
478
+ const { auth, client } = await authResolver.resolveForProject(project);
479
+ const inspection = await inspectLinkedPenSyncState(client, project);
480
+ if (inspection.state === 'up-to-date') {
481
+ if (!jsonMode) {
482
+ output.log(`${fmt.green('✓ [UP TO DATE]')} ${pen.relPath}`);
483
+ }
484
+ counts.upToDate++;
485
+ results.push({
486
+ path: pen.relPath,
487
+ rootDir: pen.rootDir,
488
+ action: 'up-to-date',
489
+ dryRun,
490
+ penId: inspection.pen.id,
491
+ url: inspection.pen.urls.editor,
492
+ title: inspection.pen.title,
493
+ versionId: inspection.remoteHead,
494
+ });
495
+ continue;
496
+ }
497
+ if (inspection.state === 'conflict' && !(mode === 'push' && force)) {
498
+ if (!jsonMode) {
499
+ logConflictDetails(pen.relPath, inspection, output);
500
+ }
501
+ counts.conflicts++;
502
+ results.push({
503
+ path: pen.relPath,
504
+ rootDir: pen.rootDir,
505
+ action: 'conflict',
506
+ dryRun,
507
+ penId: inspection.pen.id,
508
+ url: inspection.pen.urls.editor,
509
+ title: inspection.pen.title,
510
+ versionId: inspection.remoteHead,
511
+ reason: 'Both local and remote have changed',
512
+ });
513
+ continue;
514
+ }
515
+ const isRemoteAhead = inspection.state === 'remote-ahead' || inspection.state === 'remote-metadata-ahead';
516
+ if (isRemoteAhead && mode === 'push' && !force) {
517
+ const remoteSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
518
+ if (!jsonMode) {
519
+ output.log(`${fmt.dim('- [SKIP]')} ${pen.relPath} — remote is ahead (${remoteSummary}); run \`cdpn pull\` or \`cdpn sync\``);
520
+ }
521
+ counts.skipped++;
522
+ results.push({
523
+ path: pen.relPath,
524
+ rootDir: pen.rootDir,
525
+ action: 'skipped',
526
+ dryRun,
527
+ penId: inspection.pen.id,
528
+ url: inspection.pen.urls.editor,
529
+ title: inspection.pen.title,
530
+ reason: `Remote is ahead (${remoteSummary})`,
531
+ });
532
+ continue;
533
+ }
534
+ // --- PULL (in sync mode when remote is ahead) ---
535
+ if (isRemoteAhead && mode === 'sync') {
536
+ const remoteSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
537
+ const versionRange = inspection.remoteVersionChanged
538
+ ? `${shortId(inspection.localHead)} → ${shortId(inspection.remoteHead)}, `
539
+ : '';
540
+ if (dryRun) {
541
+ if (!jsonMode) {
542
+ output.log(`${fmt.cyan('↓ [WOULD PULL]')} ${fmt.bold(pen.relPath)} (${versionRange}${remoteSummary})`);
543
+ for (const line of formatFileDiffLines(inspection.diff, 'pull')) {
544
+ output.log(line);
545
+ }
546
+ }
547
+ counts.pulled++;
548
+ results.push({
549
+ path: pen.relPath,
550
+ rootDir: pen.rootDir,
551
+ action: 'pulled',
552
+ dryRun: true,
553
+ penId: inspection.pen.id,
554
+ url: inspection.pen.urls.editor,
555
+ title: inspection.pen.title,
556
+ versionId: inspection.remoteHead,
557
+ });
558
+ continue;
559
+ }
560
+ if (!jsonMode) {
561
+ output.log(`${fmt.cyan('↓ [PULLING]')} ${fmt.bold(pen.relPath)} (${versionRange}${remoteSummary})…`);
562
+ }
563
+ const pullRes = await executePull(client, project, auth, {
564
+ force: inspection.state === 'remote-metadata-ahead',
565
+ dryRun: false,
566
+ silent: true,
567
+ interactive: false,
568
+ prefetchedPen: inspection.pen,
569
+ prefetchedRemoteFiles: inspection.remoteFiles,
570
+ prefetchedLocalFiles: inspection.localFiles,
571
+ handleMissingPen: false,
572
+ output,
573
+ });
574
+ const writtenCount = pullRes?.writtenPaths.length ?? 0;
575
+ const deletedCount = pullRes?.deletedPaths.length ?? 0;
576
+ if (!jsonMode) {
577
+ output.log(` ${fmt.green('✓')} Pulled (version ${shortId(inspection.remoteHead)}, updated ${writtenCount}, removed ${deletedCount})`);
578
+ }
579
+ counts.pulled++;
580
+ results.push({
581
+ path: pen.relPath,
582
+ rootDir: pen.rootDir,
583
+ action: 'pulled',
584
+ dryRun: false,
585
+ penId: inspection.pen.id,
586
+ url: inspection.pen.urls.editor,
587
+ title: inspection.pen.title,
588
+ versionId: inspection.remoteHead,
589
+ });
590
+ continue;
591
+ }
592
+ // --- PUSH (local-ahead, or forced push over remote-ahead / conflict) ---
593
+ if (inspection.classicReadOnly) {
594
+ throw new CliError(403, 'This is a Classic Pen, which is read-only in CodePen API v2. Only CodePen 2.0 Pens can be pushed.');
595
+ }
596
+ const changeSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes, 'forced overwrite');
597
+ const isForced = mode === 'push' && force && inspection.state !== 'local-ahead';
598
+ if (dryRun) {
599
+ if (!jsonMode) {
600
+ output.log(`${fmt.cyan(isForced ? '↑ [WOULD FORCE PUSH]' : '↑ [WOULD PUSH]')} ${fmt.bold(pen.relPath)} (${changeSummary})`);
601
+ for (const line of formatFileDiffLines(inspection.diff, 'push')) {
602
+ output.log(line);
603
+ }
604
+ }
605
+ counts.pushed++;
606
+ results.push({
607
+ path: pen.relPath,
608
+ rootDir: pen.rootDir,
609
+ action: 'pushed',
610
+ dryRun: true,
611
+ penId: inspection.pen.id,
612
+ url: inspection.pen.urls.editor,
613
+ title: inspection.pen.title,
614
+ versionId: inspection.remoteHead,
615
+ });
616
+ continue;
617
+ }
618
+ if (!jsonMode) {
619
+ output.log(`${fmt.cyan(isForced ? '↑ [FORCE PUSHING]' : '↑ [PUSHING]')} ${fmt.bold(pen.relPath)} (${changeSummary})…`);
620
+ for (const line of formatFileDiffLines(inspection.diff, 'push')) {
621
+ output.log(line);
622
+ }
623
+ }
624
+ const pushRes = await executePush(client, project, {
625
+ label: options.label,
626
+ force: mode === 'push' && force,
627
+ dryRun: false,
628
+ wait: options.wait,
629
+ silent: true,
630
+ output,
631
+ prefetchedPen: inspection.pen,
632
+ });
633
+ if (pushRes.exitCode) {
634
+ const msg = `Files were saved as version ${shortId(pushRes.versionId)}, but the build failed.`;
635
+ if (!jsonMode) {
636
+ output.log(` ${fmt.red('✗')} ${msg}`);
637
+ }
638
+ counts.errors++;
639
+ results.push({
640
+ path: pen.relPath,
641
+ rootDir: pen.rootDir,
642
+ action: 'error',
643
+ dryRun: false,
644
+ penId: pushRes.pen.id,
645
+ url: pushRes.pen.urls.editor,
646
+ title: pushRes.pen.title,
647
+ versionId: pushRes.versionId,
648
+ error: msg,
649
+ });
650
+ continue;
651
+ }
652
+ if (!jsonMode) {
653
+ output.log(` ${fmt.green('✓')} Pushed (version ${shortId(pushRes.versionId)})`);
654
+ }
655
+ counts.pushed++;
656
+ results.push({
657
+ path: pen.relPath,
658
+ rootDir: pen.rootDir,
659
+ action: 'pushed',
660
+ dryRun: false,
661
+ penId: pushRes.pen.id,
662
+ url: pushRes.pen.urls.editor,
663
+ title: pushRes.pen.title,
664
+ versionId: pushRes.versionId,
665
+ });
666
+ }
667
+ catch (error) {
668
+ const message = formatErrorMessage(error, project.config.pen_id, pen.relPath);
669
+ if (!jsonMode) {
670
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
671
+ output.log(` ${message}`);
672
+ }
673
+ counts.errors++;
674
+ results.push({
675
+ path: pen.relPath,
676
+ rootDir: pen.rootDir,
677
+ action: 'error',
678
+ dryRun,
679
+ penId: project.config.pen_id,
680
+ url: project.config.url,
681
+ error: message,
682
+ });
683
+ }
684
+ }
685
+ return finalizeBatchResult({
686
+ mode,
687
+ dryRun,
688
+ rootDir: options.rootDir,
689
+ counts,
690
+ results,
691
+ jsonMode,
692
+ output,
693
+ });
694
+ }
695
+ export async function runBatchPush(options) {
696
+ return runBatchPushOrSync('push', options);
697
+ }
698
+ export async function runBatchSync(options) {
699
+ return runBatchPushOrSync('sync', options);
700
+ }
701
+ export async function runBatchPull(options) {
702
+ const output = options.output ?? defaultOutput;
703
+ const dryRun = Boolean(options.dryRun);
704
+ const jsonMode = Boolean(options.json);
705
+ const interactive = !jsonMode && Boolean(options.interactive);
706
+ const force = Boolean(options.force);
707
+ const counts = createEmptyCounts(options.discovered.length);
708
+ const results = [];
709
+ logBatchHeader('pull', options.discovered.length, dryRun, jsonMode, output);
710
+ const authResolver = createBatchAuthResolver({
711
+ explicitProfile: options.explicitProfile,
712
+ interactive,
713
+ baseUrl: options.baseUrl,
714
+ env: options.env,
715
+ homeDir: options.homeDir,
716
+ output,
717
+ selectProfile: options.prompts?.select,
718
+ });
719
+ if (options.explicitProfile) {
720
+ await authResolver.resolveFallback();
721
+ }
722
+ for (const pen of options.discovered) {
723
+ if (pen.parseError || !pen.parsed) {
724
+ const message = pen.parseError ?? `Invalid ${PROJECT_CONFIG_FILENAME}`;
725
+ if (!jsonMode) {
726
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
727
+ output.log(` ${message}`);
728
+ }
729
+ counts.errors++;
730
+ results.push({
731
+ path: pen.relPath,
732
+ rootDir: pen.rootDir,
733
+ action: 'error',
734
+ dryRun,
735
+ error: message,
736
+ });
737
+ continue;
738
+ }
739
+ if (!pen.parsed.linked) {
740
+ if (!jsonMode) {
741
+ output.log(`${fmt.dim('- [SKIP]')} ${pen.relPath} — unlinked (info-only ${PROJECT_CONFIG_FILENAME}); nothing to pull`);
742
+ }
743
+ counts.skipped++;
744
+ results.push({
745
+ path: pen.relPath,
746
+ rootDir: pen.rootDir,
747
+ action: 'skipped',
748
+ dryRun,
749
+ reason: `Unlinked (info-only ${PROJECT_CONFIG_FILENAME})`,
750
+ });
751
+ continue;
752
+ }
753
+ const project = {
754
+ rootDir: pen.rootDir,
755
+ configPath: pen.configPath,
756
+ config: pen.parsed.config,
757
+ };
758
+ try {
759
+ const { auth, client } = await authResolver.resolveForProject(project);
760
+ if (force) {
761
+ if (dryRun) {
762
+ const preview = await executePull(client, project, auth, {
763
+ force: true,
764
+ dryRun: true,
765
+ silent: true,
766
+ interactive: false,
767
+ handleMissingPen: false,
768
+ output,
769
+ });
770
+ const changeDesc = formatSyncChangeSummary((preview?.writtenPaths.length ?? 0) + (preview?.deletedPaths.length ?? 0), preview?.infoChanges ?? [], 'refresh');
771
+ if (!jsonMode) {
772
+ output.log(`${fmt.cyan('↓ [WOULD FORCE PULL]')} ${fmt.bold(pen.relPath)} (${changeDesc})`);
773
+ }
774
+ counts.pulled++;
775
+ results.push({
776
+ path: pen.relPath,
777
+ rootDir: pen.rootDir,
778
+ action: 'pulled',
779
+ dryRun: true,
780
+ penId: preview?.pen.id ?? project.config.pen_id,
781
+ url: preview?.pen.urls.editor ?? project.config.url,
782
+ title: preview?.pen.title,
783
+ versionId: preview?.pen.saved_version?.id ?? null,
784
+ });
785
+ continue;
786
+ }
787
+ if (!jsonMode) {
788
+ output.log(`${fmt.cyan('↓ [FORCE PULLING]')} ${fmt.bold(pen.relPath)} (${shortId(project.config.last_synced_version_id)})…`);
789
+ }
790
+ const pullRes = await executePull(client, project, auth, {
791
+ force: true,
792
+ dryRun: false,
793
+ silent: true,
794
+ interactive: false,
795
+ handleMissingPen: false,
796
+ output,
797
+ });
798
+ const writtenCount = pullRes?.writtenPaths.length ?? 0;
799
+ const deletedCount = pullRes?.deletedPaths.length ?? 0;
800
+ const nextVersion = pullRes?.pen.saved_version?.id ?? null;
801
+ if (!jsonMode) {
802
+ output.log(` ${fmt.green('✓')} Pulled (version ${shortId(nextVersion)}, updated ${writtenCount}, removed ${deletedCount})`);
803
+ }
804
+ counts.pulled++;
805
+ results.push({
806
+ path: pen.relPath,
807
+ rootDir: pen.rootDir,
808
+ action: 'pulled',
809
+ dryRun: false,
810
+ penId: pullRes?.pen.id ?? project.config.pen_id,
811
+ url: pullRes?.pen.urls.editor ?? project.config.url,
812
+ title: pullRes?.pen.title,
813
+ versionId: nextVersion,
814
+ });
815
+ continue;
816
+ }
817
+ const inspection = await inspectLinkedPenSyncState(client, project);
818
+ if (inspection.state === 'up-to-date') {
819
+ if (!jsonMode) {
820
+ output.log(`${fmt.green('✓ [UP TO DATE]')} ${pen.relPath}`);
821
+ }
822
+ counts.upToDate++;
823
+ results.push({
824
+ path: pen.relPath,
825
+ rootDir: pen.rootDir,
826
+ action: 'up-to-date',
827
+ dryRun,
828
+ penId: inspection.pen.id,
829
+ url: inspection.pen.urls.editor,
830
+ title: inspection.pen.title,
831
+ versionId: inspection.remoteHead,
832
+ });
833
+ continue;
834
+ }
835
+ if (inspection.state === 'local-ahead') {
836
+ const changeSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
837
+ if (!jsonMode) {
838
+ output.log(`${fmt.dim('- [SKIP]')} ${pen.relPath} — local has unpushed changes (${changeSummary}); run \`cdpn push\` or \`cdpn sync\``);
839
+ }
840
+ counts.skipped++;
841
+ results.push({
842
+ path: pen.relPath,
843
+ rootDir: pen.rootDir,
844
+ action: 'skipped',
845
+ dryRun,
846
+ penId: inspection.pen.id,
847
+ url: inspection.pen.urls.editor,
848
+ title: inspection.pen.title,
849
+ reason: `Local has unpushed changes (${changeSummary})`,
850
+ });
851
+ continue;
852
+ }
853
+ if (inspection.state === 'conflict') {
854
+ if (!jsonMode) {
855
+ logConflictDetails(pen.relPath, inspection, output);
856
+ }
857
+ counts.conflicts++;
858
+ results.push({
859
+ path: pen.relPath,
860
+ rootDir: pen.rootDir,
861
+ action: 'conflict',
862
+ dryRun,
863
+ penId: inspection.pen.id,
864
+ url: inspection.pen.urls.editor,
865
+ title: inspection.pen.title,
866
+ versionId: inspection.remoteHead,
867
+ reason: 'Both local and remote have changed',
868
+ });
869
+ continue;
870
+ }
871
+ // remote-ahead or remote-metadata-ahead
872
+ const remoteSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
873
+ const versionRange = inspection.remoteVersionChanged
874
+ ? `${shortId(inspection.localHead)} → ${shortId(inspection.remoteHead)}, `
875
+ : '';
876
+ if (dryRun) {
877
+ if (!jsonMode) {
878
+ output.log(`${fmt.cyan('↓ [WOULD PULL]')} ${fmt.bold(pen.relPath)} (${versionRange}${remoteSummary})`);
879
+ for (const line of formatFileDiffLines(inspection.diff, 'pull')) {
880
+ output.log(line);
881
+ }
882
+ }
883
+ counts.pulled++;
884
+ results.push({
885
+ path: pen.relPath,
886
+ rootDir: pen.rootDir,
887
+ action: 'pulled',
888
+ dryRun: true,
889
+ penId: inspection.pen.id,
890
+ url: inspection.pen.urls.editor,
891
+ title: inspection.pen.title,
892
+ versionId: inspection.remoteHead,
893
+ });
894
+ continue;
895
+ }
896
+ if (!jsonMode) {
897
+ output.log(`${fmt.cyan('↓ [PULLING]')} ${fmt.bold(pen.relPath)} (${versionRange}${remoteSummary})…`);
898
+ }
899
+ const pullRes = await executePull(client, project, auth, {
900
+ force: inspection.state === 'remote-metadata-ahead',
901
+ dryRun: false,
902
+ silent: true,
903
+ interactive: false,
904
+ prefetchedPen: inspection.pen,
905
+ prefetchedRemoteFiles: inspection.remoteFiles,
906
+ prefetchedLocalFiles: inspection.localFiles,
907
+ handleMissingPen: false,
908
+ output,
909
+ });
910
+ const writtenCount = pullRes?.writtenPaths.length ?? 0;
911
+ const deletedCount = pullRes?.deletedPaths.length ?? 0;
912
+ if (!jsonMode) {
913
+ output.log(` ${fmt.green('✓')} Pulled (version ${shortId(inspection.remoteHead)}, updated ${writtenCount}, removed ${deletedCount})`);
914
+ }
915
+ counts.pulled++;
916
+ results.push({
917
+ path: pen.relPath,
918
+ rootDir: pen.rootDir,
919
+ action: 'pulled',
920
+ dryRun: false,
921
+ penId: inspection.pen.id,
922
+ url: inspection.pen.urls.editor,
923
+ title: inspection.pen.title,
924
+ versionId: inspection.remoteHead,
925
+ });
926
+ }
927
+ catch (error) {
928
+ const message = formatErrorMessage(error, project.config.pen_id, pen.relPath);
929
+ if (!jsonMode) {
930
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
931
+ output.log(` ${message}`);
932
+ }
933
+ counts.errors++;
934
+ results.push({
935
+ path: pen.relPath,
936
+ rootDir: pen.rootDir,
937
+ action: 'error',
938
+ dryRun,
939
+ penId: project.config.pen_id,
940
+ url: project.config.url,
941
+ error: message,
942
+ });
943
+ }
944
+ }
945
+ return finalizeBatchResult({
946
+ mode: 'pull',
947
+ dryRun,
948
+ rootDir: options.rootDir,
949
+ counts,
950
+ results,
951
+ jsonMode,
952
+ output,
953
+ });
954
+ }
955
+ export async function runBatchDelete(options) {
956
+ const output = options.output ?? defaultOutput;
957
+ const dryRun = Boolean(options.dryRun);
958
+ const jsonMode = Boolean(options.json);
959
+ const interactive = !jsonMode && Boolean(options.interactive);
960
+ const cleanup = Boolean(options.cleanup);
961
+ const fullCleanup = Boolean(options.fullCleanup);
962
+ const linkedTargets = options.discovered
963
+ .filter((pen) => pen.parsed?.linked)
964
+ .map((pen) => {
965
+ const cfg = pen.parsed.config;
966
+ return {
967
+ relPath: pen.relPath,
968
+ penId: cfg.pen_id,
969
+ url: cfg.url,
970
+ title: cfg.info?.title,
971
+ };
972
+ });
973
+ if (!dryRun && linkedTargets.length > 0) {
974
+ const confirmed = await confirmBatchDestructiveAction({
975
+ action: 'delete',
976
+ targets: linkedTargets,
977
+ cleanup,
978
+ fullCleanup,
979
+ yes: options.yes,
980
+ interactive,
981
+ output,
982
+ confirm: options.prompts?.confirm,
983
+ });
984
+ if (!confirmed) {
985
+ return null;
986
+ }
987
+ }
988
+ const counts = createEmptyCounts(options.discovered.length);
989
+ const results = [];
990
+ logBatchHeader('delete', options.discovered.length, dryRun, jsonMode, output);
991
+ const authResolver = createBatchAuthResolver({
992
+ explicitProfile: options.explicitProfile,
993
+ interactive,
994
+ baseUrl: options.baseUrl,
995
+ env: options.env,
996
+ homeDir: options.homeDir,
997
+ output,
998
+ selectProfile: options.prompts?.select,
999
+ });
1000
+ if (!dryRun && options.explicitProfile && linkedTargets.length > 0) {
1001
+ await authResolver.resolveFallback();
1002
+ }
1003
+ const localActionNote = fullCleanup
1004
+ ? `removing ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`
1005
+ : cleanup
1006
+ ? `removing ${CODEPEN_DIR}/ and retaining info in ${PROJECT_CONFIG_FILENAME}`
1007
+ : `keeping ${PROJECT_CONFIG_FILENAME} and ${CODEPEN_DIR}/`;
1008
+ for (const pen of options.discovered) {
1009
+ if (pen.parseError || !pen.parsed) {
1010
+ const message = pen.parseError ?? `Invalid ${PROJECT_CONFIG_FILENAME}`;
1011
+ if (!jsonMode) {
1012
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
1013
+ output.log(` ${message}`);
1014
+ }
1015
+ counts.errors++;
1016
+ results.push({
1017
+ path: pen.relPath,
1018
+ rootDir: pen.rootDir,
1019
+ action: 'error',
1020
+ dryRun,
1021
+ error: message,
1022
+ });
1023
+ continue;
1024
+ }
1025
+ if (!pen.parsed.linked) {
1026
+ if (!jsonMode) {
1027
+ output.log(`${fmt.dim('- [SKIP]')} ${pen.relPath} — already unlinked (info-only ${PROJECT_CONFIG_FILENAME}); nothing to delete`);
1028
+ }
1029
+ counts.skipped++;
1030
+ results.push({
1031
+ path: pen.relPath,
1032
+ rootDir: pen.rootDir,
1033
+ action: 'skipped',
1034
+ dryRun,
1035
+ reason: `Already unlinked (info-only ${PROJECT_CONFIG_FILENAME})`,
1036
+ });
1037
+ continue;
1038
+ }
1039
+ const project = {
1040
+ rootDir: pen.rootDir,
1041
+ configPath: pen.configPath,
1042
+ config: pen.parsed.config,
1043
+ };
1044
+ if (dryRun) {
1045
+ if (!jsonMode) {
1046
+ output.log(`${fmt.yellow('× [WOULD DELETE]')} ${fmt.bold(pen.relPath)} (${project.config.url || project.config.pen_id}) — ${localActionNote}`);
1047
+ }
1048
+ counts.deleted++;
1049
+ results.push({
1050
+ path: pen.relPath,
1051
+ rootDir: pen.rootDir,
1052
+ action: 'deleted',
1053
+ dryRun: true,
1054
+ penId: project.config.pen_id,
1055
+ url: project.config.url,
1056
+ title: project.config.info?.title,
1057
+ });
1058
+ continue;
1059
+ }
1060
+ try {
1061
+ const { client } = await authResolver.resolveForProject(project);
1062
+ if (!jsonMode) {
1063
+ output.log(`${fmt.yellow('× [DELETING]')} ${fmt.bold(pen.relPath)} (${project.config.url || project.config.pen_id})…`);
1064
+ }
1065
+ // When --cleanup is requested, read remote Pen info before deleting so retained info stays complete
1066
+ let fetchedPen = null;
1067
+ if (cleanup) {
1068
+ try {
1069
+ fetchedPen = await client.getPen(project.config.pen_id);
1070
+ }
1071
+ catch (error) {
1072
+ if (!isRemotePenNotFoundError(error)) {
1073
+ throw error;
1074
+ }
1075
+ }
1076
+ }
1077
+ let alreadyDeletedRemotely = false;
1078
+ try {
1079
+ await client.deletePen(project.config.pen_id);
1080
+ }
1081
+ catch (error) {
1082
+ if (isRemotePenNotFoundError(error)) {
1083
+ alreadyDeletedRemotely = true;
1084
+ }
1085
+ else {
1086
+ throw error;
1087
+ }
1088
+ }
1089
+ if (fullCleanup) {
1090
+ await fs.unlink(project.configPath);
1091
+ await removeCodepenDirSafe(project.rootDir);
1092
+ }
1093
+ else if (cleanup) {
1094
+ if (fetchedPen) {
1095
+ const remoteInfo = extractPenInfo(fetchedPen);
1096
+ const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, fetchedPen);
1097
+ const retainedInfo = infoAnalysis.localChanged && project.config.info
1098
+ ? { ...remoteInfo, ...normalizePartialPenInfo(project.config.info) }
1099
+ : remoteInfo;
1100
+ await writeUnlinkedProjectInfo(project.rootDir, retainedInfo);
1101
+ }
1102
+ else {
1103
+ await unlinkLinkedProject(project);
1104
+ }
1105
+ await removeCodepenDirSafe(project.rootDir);
1106
+ }
1107
+ const displayTitle = fetchedPen?.title || project.config.info?.title || path.basename(project.rootDir);
1108
+ if (!jsonMode) {
1109
+ const note = alreadyDeletedRemotely
1110
+ ? `already deleted remotely (${localActionNote})`
1111
+ : localActionNote;
1112
+ output.log(` ${fmt.green('✓')} Deleted "${displayTitle}" (${shortId(project.config.pen_id)}) — ${note}`);
1113
+ }
1114
+ counts.deleted++;
1115
+ results.push({
1116
+ path: pen.relPath,
1117
+ rootDir: pen.rootDir,
1118
+ action: 'deleted',
1119
+ dryRun: false,
1120
+ penId: project.config.pen_id,
1121
+ url: project.config.url,
1122
+ title: displayTitle,
1123
+ ...(alreadyDeletedRemotely ? { reason: 'Already deleted remotely' } : {}),
1124
+ });
1125
+ }
1126
+ catch (error) {
1127
+ const message = formatErrorMessage(error, project.config.pen_id, pen.relPath);
1128
+ if (!jsonMode) {
1129
+ output.log(` ${fmt.red('✗')} Delete failed: ${message}`);
1130
+ }
1131
+ counts.errors++;
1132
+ results.push({
1133
+ path: pen.relPath,
1134
+ rootDir: pen.rootDir,
1135
+ action: 'error',
1136
+ dryRun: false,
1137
+ penId: project.config.pen_id,
1138
+ url: project.config.url,
1139
+ error: message,
1140
+ });
1141
+ }
1142
+ }
1143
+ return finalizeBatchResult({
1144
+ mode: 'delete',
1145
+ dryRun,
1146
+ rootDir: options.rootDir,
1147
+ counts,
1148
+ results,
1149
+ jsonMode,
1150
+ output,
1151
+ });
1152
+ }
1153
+ export async function runBatchUnlink(options) {
1154
+ const output = options.output ?? defaultOutput;
1155
+ const dryRun = Boolean(options.dryRun);
1156
+ const jsonMode = Boolean(options.json);
1157
+ const interactive = !jsonMode && Boolean(options.interactive);
1158
+ const linkedTargets = options.discovered
1159
+ .filter((pen) => pen.parsed?.linked)
1160
+ .map((pen) => {
1161
+ const cfg = pen.parsed.config;
1162
+ return {
1163
+ relPath: pen.relPath,
1164
+ penId: cfg.pen_id,
1165
+ url: cfg.url,
1166
+ title: cfg.info?.title,
1167
+ };
1168
+ });
1169
+ if (!dryRun && linkedTargets.length > 0) {
1170
+ const confirmed = await confirmBatchDestructiveAction({
1171
+ action: 'unlink',
1172
+ targets: linkedTargets,
1173
+ yes: options.yes,
1174
+ interactive,
1175
+ output,
1176
+ confirm: options.prompts?.confirm,
1177
+ });
1178
+ if (!confirmed) {
1179
+ return null;
1180
+ }
1181
+ }
1182
+ const counts = createEmptyCounts(options.discovered.length);
1183
+ const results = [];
1184
+ logBatchHeader('unlink', options.discovered.length, dryRun, jsonMode, output);
1185
+ for (const pen of options.discovered) {
1186
+ if (pen.parseError || !pen.parsed) {
1187
+ const message = pen.parseError ?? `Invalid ${PROJECT_CONFIG_FILENAME}`;
1188
+ if (!jsonMode) {
1189
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
1190
+ output.log(` ${message}`);
1191
+ }
1192
+ counts.errors++;
1193
+ results.push({
1194
+ path: pen.relPath,
1195
+ rootDir: pen.rootDir,
1196
+ action: 'error',
1197
+ dryRun,
1198
+ error: message,
1199
+ });
1200
+ continue;
1201
+ }
1202
+ if (!pen.parsed.linked) {
1203
+ if (!jsonMode) {
1204
+ output.log(`${fmt.dim('- [SKIP]')} ${pen.relPath} — already unlinked (info-only ${PROJECT_CONFIG_FILENAME})`);
1205
+ }
1206
+ counts.skipped++;
1207
+ results.push({
1208
+ path: pen.relPath,
1209
+ rootDir: pen.rootDir,
1210
+ action: 'skipped',
1211
+ dryRun,
1212
+ reason: `Already unlinked (info-only ${PROJECT_CONFIG_FILENAME})`,
1213
+ });
1214
+ continue;
1215
+ }
1216
+ const project = {
1217
+ rootDir: pen.rootDir,
1218
+ configPath: pen.configPath,
1219
+ config: pen.parsed.config,
1220
+ };
1221
+ if (dryRun) {
1222
+ if (!jsonMode) {
1223
+ output.log(`${fmt.yellow('× [WOULD UNLINK]')} ${fmt.bold(pen.relPath)} (${project.config.url || project.config.pen_id}) — keeping ${CODEPEN_DIR}/ and info in ${PROJECT_CONFIG_FILENAME}`);
1224
+ }
1225
+ counts.unlinked++;
1226
+ results.push({
1227
+ path: pen.relPath,
1228
+ rootDir: pen.rootDir,
1229
+ action: 'unlinked',
1230
+ dryRun: true,
1231
+ penId: project.config.pen_id,
1232
+ url: project.config.url,
1233
+ title: project.config.info?.title,
1234
+ });
1235
+ continue;
1236
+ }
1237
+ try {
1238
+ await unlinkLinkedProject(project);
1239
+ if (!jsonMode) {
1240
+ output.log(`${fmt.green('✓ [UNLINKED]')} ${fmt.bold(pen.relPath)} ${fmt.dim(`(${project.config.pen_id})`)}`);
1241
+ }
1242
+ counts.unlinked++;
1243
+ results.push({
1244
+ path: pen.relPath,
1245
+ rootDir: pen.rootDir,
1246
+ action: 'unlinked',
1247
+ dryRun: false,
1248
+ penId: project.config.pen_id,
1249
+ url: project.config.url,
1250
+ title: project.config.info?.title,
1251
+ });
1252
+ }
1253
+ catch (error) {
1254
+ const message = formatErrorMessage(error);
1255
+ if (!jsonMode) {
1256
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
1257
+ output.log(` ${message}`);
1258
+ }
1259
+ counts.errors++;
1260
+ results.push({
1261
+ path: pen.relPath,
1262
+ rootDir: pen.rootDir,
1263
+ action: 'error',
1264
+ dryRun: false,
1265
+ penId: project.config.pen_id,
1266
+ url: project.config.url,
1267
+ error: message,
1268
+ });
1269
+ }
1270
+ }
1271
+ return finalizeBatchResult({
1272
+ mode: 'unlink',
1273
+ dryRun,
1274
+ rootDir: options.rootDir,
1275
+ counts,
1276
+ results,
1277
+ jsonMode,
1278
+ output,
1279
+ });
1280
+ }
1281
+ async function loadTrashMapForClient(client) {
1282
+ const byItemId = new Map();
1283
+ try {
1284
+ let page = await client.listTrash({ per_page: 100 });
1285
+ for (let i = 0; i < 10; i++) {
1286
+ for (const item of page.items) {
1287
+ if (item.type === 'Pen') {
1288
+ byItemId.set(item.item_id.toLowerCase(), item);
1289
+ byItemId.set(item.id.toLowerCase(), item);
1290
+ }
1291
+ }
1292
+ if (!page.links.next)
1293
+ break;
1294
+ page = await client.listTrashPageByUrl(page.links.next);
1295
+ }
1296
+ }
1297
+ catch {
1298
+ // Gracefully fall back to empty map if Trash endpoint is unavailable
1299
+ }
1300
+ return byItemId;
1301
+ }
1302
+ /**
1303
+ * Walks all discovered Pens in a directory tree and reports their read-only sync status
1304
+ * (`up-to-date`, `local-ahead`, `remote-ahead`, `conflict`, `unlinked`, `trashed`, `missing`, `error`)
1305
+ * along with summary counts and optional `--json` output.
1306
+ */
1307
+ export async function runBatchStatus(options) {
1308
+ const output = options.output ?? defaultOutput;
1309
+ const jsonMode = Boolean(options.json);
1310
+ const interactive = !jsonMode && Boolean(options.interactive);
1311
+ const counts = {
1312
+ discovered: options.discovered.length,
1313
+ upToDate: 0,
1314
+ localAhead: 0,
1315
+ remoteAhead: 0,
1316
+ unlinked: 0,
1317
+ conflicts: 0,
1318
+ inTrash: 0,
1319
+ missing: 0,
1320
+ errors: 0,
1321
+ };
1322
+ const results = [];
1323
+ logBatchHeader('status', options.discovered.length, false, jsonMode, output);
1324
+ const authResolver = createBatchAuthResolver({
1325
+ explicitProfile: options.explicitProfile,
1326
+ interactive,
1327
+ baseUrl: options.baseUrl,
1328
+ env: options.env,
1329
+ homeDir: options.homeDir,
1330
+ output,
1331
+ selectProfile: options.prompts?.select,
1332
+ });
1333
+ if (options.explicitProfile) {
1334
+ await authResolver.resolveFallback();
1335
+ }
1336
+ const trashCacheByClient = new Map();
1337
+ async function findTrashedCached(client, project) {
1338
+ let trashMap = trashCacheByClient.get(client);
1339
+ if (!trashMap) {
1340
+ trashMap = await loadTrashMapForClient(client);
1341
+ trashCacheByClient.set(client, trashMap);
1342
+ }
1343
+ const direct = trashMap.get(project.config.pen_id.toLowerCase());
1344
+ if (direct)
1345
+ return direct;
1346
+ const urlId = extractPenIdFromUrl(project.config.url);
1347
+ return urlId ? (trashMap.get(urlId.toLowerCase()) ?? null) : null;
1348
+ }
1349
+ for (const pen of options.discovered) {
1350
+ if (pen.parseError || !pen.parsed) {
1351
+ const message = pen.parseError ?? `Invalid ${PROJECT_CONFIG_FILENAME}`;
1352
+ if (!jsonMode) {
1353
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
1354
+ output.log(` ${message}`);
1355
+ }
1356
+ counts.errors++;
1357
+ results.push({
1358
+ path: pen.relPath,
1359
+ rootDir: pen.rootDir,
1360
+ state: 'error',
1361
+ error: message,
1362
+ });
1363
+ continue;
1364
+ }
1365
+ if (!pen.parsed.linked) {
1366
+ const retainedInfo = pen.parsed.config.info;
1367
+ const scanned = await scanLocalFiles(pen.rootDir);
1368
+ const indexFile = scanned.get('/index.html');
1369
+ const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
1370
+ ? extractHtmlTitle(indexFile.textContent)
1371
+ : null;
1372
+ const title = retainedInfo.title?.trim() || htmlTitle || path.basename(pen.rootDir) || 'Untitled';
1373
+ if (!jsonMode) {
1374
+ output.log(`${fmt.cyan('+ [UNLINKED]')} ${fmt.bold(pen.relPath)} — "${title}" ${fmt.dim(`(${scanned.size} file(s), not linked to CodePen yet)`)}`);
1375
+ }
1376
+ counts.unlinked++;
1377
+ results.push({
1378
+ path: pen.relPath,
1379
+ rootDir: pen.rootDir,
1380
+ state: 'unlinked',
1381
+ title,
1382
+ fileCount: scanned.size,
1383
+ });
1384
+ continue;
1385
+ }
1386
+ const project = {
1387
+ rootDir: pen.rootDir,
1388
+ configPath: pen.configPath,
1389
+ config: pen.parsed.config,
1390
+ };
1391
+ try {
1392
+ const { client } = await authResolver.resolveForProject(project);
1393
+ let inspection;
1394
+ try {
1395
+ inspection = await inspectLinkedPenSyncState(client, project);
1396
+ }
1397
+ catch (error) {
1398
+ if (isRemotePenNotFoundError(error)) {
1399
+ const trashItem = await findTrashedCached(client, project);
1400
+ const displayTitle = trashItem?.title || project.config.info?.title || path.basename(project.rootDir);
1401
+ if (trashItem) {
1402
+ if (!jsonMode) {
1403
+ output.log(`${fmt.yellow('! [IN TRASH]')} ${fmt.bold(pen.relPath)} ${fmt.dim(`(${project.config.pen_id})`)} — deleted on CodePen ${fmt.dim(`(expires ${formatDate(trashItem.expires_at)})`)}`);
1404
+ }
1405
+ counts.inTrash++;
1406
+ results.push({
1407
+ path: pen.relPath,
1408
+ rootDir: pen.rootDir,
1409
+ state: 'trashed',
1410
+ penId: project.config.pen_id,
1411
+ url: project.config.url,
1412
+ title: displayTitle,
1413
+ localVersionId: project.config.last_synced_version_id,
1414
+ trashItem,
1415
+ });
1416
+ }
1417
+ else {
1418
+ if (!jsonMode) {
1419
+ output.log(`${fmt.red('✗ [MISSING]')} ${fmt.bold(pen.relPath)} ${fmt.dim(`(${project.config.pen_id})`)} — no longer exists on CodePen ${fmt.dim('(or belongs to another profile)')}`);
1420
+ }
1421
+ counts.missing++;
1422
+ results.push({
1423
+ path: pen.relPath,
1424
+ rootDir: pen.rootDir,
1425
+ state: 'missing',
1426
+ penId: project.config.pen_id,
1427
+ url: project.config.url,
1428
+ title: displayTitle,
1429
+ localVersionId: project.config.last_synced_version_id,
1430
+ });
1431
+ }
1432
+ continue;
1433
+ }
1434
+ throw error;
1435
+ }
1436
+ const changes = {
1437
+ added: inspection.diff.added.map((i) => i.path),
1438
+ modified: inspection.diff.modified.map((i) => i.path),
1439
+ deleted: inspection.diff.deleted.map((i) => i.path),
1440
+ };
1441
+ if (inspection.state === 'up-to-date') {
1442
+ if (!jsonMode) {
1443
+ output.log(`${fmt.green('✓ [UP TO DATE]')} ${pen.relPath}`);
1444
+ }
1445
+ counts.upToDate++;
1446
+ results.push({
1447
+ path: pen.relPath,
1448
+ rootDir: pen.rootDir,
1449
+ state: 'up-to-date',
1450
+ penId: inspection.pen.id,
1451
+ url: inspection.pen.urls.editor,
1452
+ title: inspection.pen.title,
1453
+ localVersionId: inspection.localHead,
1454
+ remoteVersionId: inspection.remoteHead,
1455
+ changes,
1456
+ infoChanges: [],
1457
+ });
1458
+ continue;
1459
+ }
1460
+ if (inspection.state === 'local-ahead') {
1461
+ const changeSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
1462
+ if (!jsonMode) {
1463
+ output.log(`${fmt.cyan('↑ [LOCAL AHEAD]')} ${fmt.bold(pen.relPath)} (${changeSummary})`);
1464
+ for (const line of formatFileDiffLines(inspection.diff, 'push')) {
1465
+ output.log(line);
1466
+ }
1467
+ for (const change of inspection.infoAnalysis.changes) {
1468
+ output.log(` ${fmt.yellow('~')} info.${change.field}: ${formatInfoValue(change.field, change.remote)} → ${formatInfoValue(change.field, change.local)}`);
1469
+ }
1470
+ }
1471
+ counts.localAhead++;
1472
+ results.push({
1473
+ path: pen.relPath,
1474
+ rootDir: pen.rootDir,
1475
+ state: 'local-ahead',
1476
+ penId: inspection.pen.id,
1477
+ url: inspection.pen.urls.editor,
1478
+ title: inspection.pen.title,
1479
+ localVersionId: inspection.localHead,
1480
+ remoteVersionId: inspection.remoteHead,
1481
+ changes,
1482
+ infoChanges: inspection.infoAnalysis.changes,
1483
+ });
1484
+ continue;
1485
+ }
1486
+ if (inspection.state === 'remote-ahead' || inspection.state === 'remote-metadata-ahead') {
1487
+ const remoteSummary = formatSyncChangeSummary(inspection.diffCount, inspection.infoAnalysis.changes);
1488
+ const versionRange = inspection.remoteVersionChanged
1489
+ ? `${shortId(inspection.localHead)} → ${shortId(inspection.remoteHead)}, `
1490
+ : '';
1491
+ if (!jsonMode) {
1492
+ output.log(`${fmt.cyan('↓ [REMOTE AHEAD]')} ${fmt.bold(pen.relPath)} (${versionRange}${remoteSummary})`);
1493
+ for (const line of formatFileDiffLines(inspection.diff, 'pull')) {
1494
+ output.log(line);
1495
+ }
1496
+ for (const change of inspection.infoAnalysis.changes) {
1497
+ output.log(` ${fmt.yellow('~')} info.${change.field}: ${formatInfoValue(change.field, change.local)} → ${formatInfoValue(change.field, change.remote)}`);
1498
+ }
1499
+ }
1500
+ counts.remoteAhead++;
1501
+ results.push({
1502
+ path: pen.relPath,
1503
+ rootDir: pen.rootDir,
1504
+ state: inspection.state,
1505
+ penId: inspection.pen.id,
1506
+ url: inspection.pen.urls.editor,
1507
+ title: inspection.pen.title,
1508
+ localVersionId: inspection.localHead,
1509
+ remoteVersionId: inspection.remoteHead,
1510
+ changes,
1511
+ infoChanges: inspection.infoAnalysis.changes,
1512
+ });
1513
+ continue;
1514
+ }
1515
+ // conflict
1516
+ if (!jsonMode) {
1517
+ logConflictDetails(pen.relPath, inspection, output);
1518
+ }
1519
+ counts.conflicts++;
1520
+ results.push({
1521
+ path: pen.relPath,
1522
+ rootDir: pen.rootDir,
1523
+ state: 'conflict',
1524
+ penId: inspection.pen.id,
1525
+ url: inspection.pen.urls.editor,
1526
+ title: inspection.pen.title,
1527
+ localVersionId: inspection.localHead,
1528
+ remoteVersionId: inspection.remoteHead,
1529
+ changes,
1530
+ infoChanges: inspection.infoAnalysis.changes,
1531
+ });
1532
+ }
1533
+ catch (error) {
1534
+ const message = formatErrorMessage(error, project.config.pen_id, pen.relPath);
1535
+ if (!jsonMode) {
1536
+ output.log(`${fmt.red('✗ [ERROR]')} ${fmt.bold(pen.relPath)}`);
1537
+ output.log(` ${message}`);
1538
+ }
1539
+ counts.errors++;
1540
+ results.push({
1541
+ path: pen.relPath,
1542
+ rootDir: pen.rootDir,
1543
+ state: 'error',
1544
+ penId: project.config.pen_id,
1545
+ url: project.config.url,
1546
+ error: message,
1547
+ });
1548
+ }
1549
+ }
1550
+ const upToDate = counts.discovered > 0 && counts.upToDate === counts.discovered;
1551
+ const remoteMoved = counts.remoteAhead > 0 || counts.conflicts > 0;
1552
+ const exitCode = counts.errors > 0 ? 1 : undefined;
1553
+ if (jsonMode) {
1554
+ const summaryParts = [
1555
+ `${counts.upToDate} up to date`,
1556
+ `${counts.localAhead} local ahead`,
1557
+ `${counts.remoteAhead} remote ahead`,
1558
+ `${counts.unlinked} unlinked`,
1559
+ `${counts.conflicts} conflicts`,
1560
+ ...(counts.inTrash > 0 ? [`${counts.inTrash} in trash`] : []),
1561
+ ...(counts.missing > 0 ? [`${counts.missing} missing`] : []),
1562
+ `${counts.errors} errors`,
1563
+ ];
1564
+ printJsonResponse(counts.errors > 0 ? 500 : 200, `Batch status complete (${counts.discovered} discovered): ${summaryParts.join(', ')}.`, {
1565
+ batch: true,
1566
+ mode: 'status',
1567
+ root_dir: options.rootDir,
1568
+ up_to_date: upToDate,
1569
+ remote_ahead: remoteMoved,
1570
+ counts: {
1571
+ discovered: counts.discovered,
1572
+ up_to_date: counts.upToDate,
1573
+ local_ahead: counts.localAhead,
1574
+ remote_ahead: counts.remoteAhead,
1575
+ unlinked: counts.unlinked,
1576
+ conflicts: counts.conflicts,
1577
+ in_trash: counts.inTrash,
1578
+ missing: counts.missing,
1579
+ errors: counts.errors,
1580
+ },
1581
+ results: results.map((item) => ({
1582
+ path: item.path,
1583
+ root_dir: item.rootDir,
1584
+ state: item.state,
1585
+ ...(item.penId ? { pen_id: item.penId } : {}),
1586
+ ...(item.url ? { url: item.url } : {}),
1587
+ ...(item.title ? { title: item.title } : {}),
1588
+ ...(item.localVersionId !== undefined ? { local_version_id: item.localVersionId } : {}),
1589
+ ...(item.remoteVersionId !== undefined
1590
+ ? { remote_version_id: item.remoteVersionId }
1591
+ : {}),
1592
+ ...(item.changes ? { changes: item.changes } : {}),
1593
+ ...(item.infoChanges ? { info_changes: item.infoChanges } : {}),
1594
+ ...(item.fileCount !== undefined ? { file_count: item.fileCount } : {}),
1595
+ ...(item.trashItem ? { trash_item: item.trashItem } : {}),
1596
+ ...(item.error ? { error: item.error } : {}),
1597
+ })),
1598
+ }, output);
1599
+ }
1600
+ else {
1601
+ output.log(`\n${fmt.bold('Summary (status):')}`);
1602
+ output.log(` Found: ${counts.discovered}`);
1603
+ output.log(` Up to date: ${counts.upToDate}`);
1604
+ output.log(` Local ahead: ${counts.localAhead}`);
1605
+ output.log(` Remote ahead: ${counts.remoteAhead}`);
1606
+ output.log(` Unlinked: ${counts.unlinked}`);
1607
+ output.log(` Conflicts: ${counts.conflicts}`);
1608
+ if (counts.inTrash > 0) {
1609
+ output.log(` In Trash: ${counts.inTrash}`);
1610
+ }
1611
+ if (counts.missing > 0) {
1612
+ output.log(` Missing: ${counts.missing}`);
1613
+ }
1614
+ output.log(` Errors: ${counts.errors}`);
1615
+ if (counts.inTrash > 0) {
1616
+ output.log(`\n${fmt.dim('Trashed Pens can be restored with `cdpn restore` inside each folder (or at Deleted Items):')}`);
1617
+ output.log(` ${fmt.cyan(CODEPEN_DELETED_ITEMS_URL)}`);
1618
+ }
1619
+ const conflicts = results.filter((r) => r.state === 'conflict');
1620
+ if (conflicts.length > 0) {
1621
+ output.log(`\n${fmt.yellow('Conflicts requiring manual resolution:')}`);
1622
+ for (const c of conflicts) {
1623
+ output.log(` - ${c.path}${c.url ? ` (${c.url})` : ''}`);
1624
+ }
1625
+ }
1626
+ const errors = results.filter((r) => r.state === 'error');
1627
+ if (errors.length > 0) {
1628
+ output.log(`\n${fmt.red('Errors:')}`);
1629
+ for (const e of errors) {
1630
+ output.log(` - ${e.path}: ${e.error ?? 'Unknown error'}`);
1631
+ }
1632
+ }
1633
+ if (counts.localAhead > 0 || counts.remoteAhead > 0 || counts.unlinked > 0) {
1634
+ output.log(`\n${fmt.dim('Tip: Run `cdpn sync` to synchronize changes (or `cdpn sync --dry-run` to preview).')}`);
1635
+ }
1636
+ }
1637
+ return {
1638
+ batch: true,
1639
+ mode: 'status',
1640
+ rootDir: options.rootDir,
1641
+ upToDate,
1642
+ remoteMoved,
1643
+ counts,
1644
+ results,
1645
+ ...(exitCode !== undefined ? { exitCode } : {}),
1646
+ };
1647
+ }