codepen-commander 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +103 -11
  2. package/api/client.js +129 -106
  3. package/cli.js +34 -29
  4. package/commands/auth/default.js +40 -0
  5. package/commands/auth/index.js +83 -0
  6. package/commands/auth/list.js +78 -0
  7. package/commands/auth/login.js +136 -0
  8. package/commands/auth/logout.js +186 -0
  9. package/commands/auth/status.js +212 -0
  10. package/commands/build.js +256 -0
  11. package/commands/clone.js +13 -581
  12. package/commands/delete.js +548 -80
  13. package/commands/deploy.js +164 -169
  14. package/commands/domains.js +83 -39
  15. package/commands/fork.js +13 -317
  16. package/commands/info.js +152 -0
  17. package/commands/init.js +375 -0
  18. package/commands/list.js +95 -78
  19. package/commands/new.js +155 -83
  20. package/commands/open.js +29 -19
  21. package/commands/privacy.js +52 -36
  22. package/commands/pull.js +123 -110
  23. package/commands/push.js +221 -376
  24. package/commands/restore.js +251 -0
  25. package/commands/rollback.js +141 -0
  26. package/commands/serve.js +119 -0
  27. package/commands/settings.js +126 -0
  28. package/commands/shell.js +305 -0
  29. package/commands/status.js +133 -39
  30. package/commands/sync.js +330 -0
  31. package/commands/undeploy.js +102 -0
  32. package/commands/unlink.js +191 -0
  33. package/commands/versions.js +100 -163
  34. package/config/auth.js +4 -374
  35. package/config/pen-blocks.js +166 -0
  36. package/config/project.js +103 -231
  37. package/config/user-store.js +364 -0
  38. package/constants.js +42 -0
  39. package/errors.js +17 -0
  40. package/package.json +1 -1
  41. package/shell/index.html +79 -0
  42. package/shell/scripts.js +276 -0
  43. package/shell/styles.css +492 -0
  44. package/site/blocks/classic.js +270 -0
  45. package/site/blocks/context.js +63 -0
  46. package/site/blocks/index.js +4 -0
  47. package/site/blocks/packages.js +242 -0
  48. package/site/blocks/unsupported-page.js +328 -0
  49. package/site/builder.js +475 -0
  50. package/site/detect.js +65 -0
  51. package/site/ignore-files.js +90 -0
  52. package/site/manifest.js +227 -0
  53. package/site/server.js +483 -0
  54. package/site/shell.js +363 -0
  55. package/sync/fs.js +19 -17
  56. package/sync/info.js +6 -81
  57. package/utils/browser.js +17 -10
  58. package/utils/cli-options.js +79 -0
  59. package/utils/codepen-url.js +183 -0
  60. package/utils/format.js +39 -30
  61. package/utils/fs-safe.js +95 -0
  62. package/utils/html.js +40 -1
  63. package/utils/json.js +4 -19
  64. package/utils/output.js +37 -0
  65. package/utils/package-paths.js +51 -0
  66. package/utils/prompts/index.js +5 -0
  67. package/utils/prompts/multi-select.js +185 -0
  68. package/utils/prompts/secret.js +65 -0
  69. package/utils/prompts/select.js +141 -0
  70. package/utils/prompts/text.js +99 -0
  71. package/utils/prompts/tty-list.js +165 -0
  72. package/utils/prompts/types.js +35 -0
  73. package/utils/strings.js +98 -0
  74. package/utils/watcher.js +82 -0
  75. package/{commands → workflows}/auth-context.js +13 -7
  76. package/workflows/batch-pens.js +1647 -0
  77. package/workflows/batch-target.js +184 -0
  78. package/workflows/classic-convert.js +241 -0
  79. package/workflows/clone-pen.js +381 -0
  80. package/{commands → workflows}/create-pen.js +59 -84
  81. package/workflows/discover-pens.js +91 -0
  82. package/workflows/fork-pen.js +314 -0
  83. package/workflows/missing-pen.js +212 -0
  84. package/workflows/pull-pen.js +204 -0
  85. package/workflows/push-pen.js +318 -0
  86. package/{commands → workflows}/scaffold.js +4 -3
  87. package/workflows/sync-pen.js +227 -0
  88. package/{commands → workflows}/unowned-pen.js +16 -12
  89. package/commands/auth.js +0 -593
  90. package/commands/meta.js +0 -184
  91. package/utils/prompts.js +0 -316
  92. /package/{types.js → api/types.js} +0 -0
package/commands/push.js CHANGED
@@ -1,418 +1,263 @@
1
1
  import path from 'node:path';
2
2
  import { CodePenClient } from '../api/client.js';
3
- import { buildSyncedFileMap, findNearestConfig, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
4
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
5
- import { createPenFromDirectory } from './create-pen.js';
6
- import { computeSyncDiff, hasDiffChanges } from '../sync/diff.js';
7
- import { scanLocalFiles } from '../sync/fs.js';
8
- import { analyzeInfoSync, buildInfoUpdatePatch, buildPenInfoConfigFields, formatInfoValue, hashPenInfo, isCompletePenInfo, } from '../sync/info.js';
9
- import { applyCompilerPatchesToDisk } from '../sync/materialize.js';
10
- import { fmt, printBuildSummary, shortId } from '../utils/format.js';
11
- import { CliError, printJsonResponse } from '../utils/json.js';
12
- import { isInteractive } from '../utils/prompts.js';
13
- export async function executePush(client, project, options = {}) {
14
- const silent = Boolean(options.silent);
15
- const [pen, remoteFiles, localFiles] = await Promise.all([
16
- client.getPen(project.config.pen_id),
17
- client.getPenFiles(project.config.pen_id),
18
- scanLocalFiles(project.rootDir),
19
- ]);
20
- if (pen.editor === 'Classic') {
21
- 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.');
22
- }
23
- const localHead = project.config.last_synced_version_id;
24
- const remoteHead = pen.saved_version?.id ?? null;
25
- if (remoteHead && localHead && remoteHead !== localHead && !options.force) {
26
- throw new CliError(409, `Remote Pen head (${shortId(remoteHead)}) has moved ahead of your last synced version (${shortId(localHead)}).\n` +
27
- 'Run `cdpn status` to inspect differences, `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite.', {
28
- local_head: localHead,
29
- remote_head: remoteHead,
30
- });
31
- }
32
- const diff = await computeSyncDiff({
33
- localFiles,
34
- remoteFiles,
35
- baseline: project.config.files,
36
- downloadFile: (url) => client.downloadFile(url),
37
- });
38
- const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, pen);
39
- if (infoAnalysis.localChanged && infoAnalysis.remoteChanged && !options.force) {
40
- const fields = infoAnalysis.changes.map((c) => c.field).join(', ');
41
- throw new CliError(409, `Remote Pen info has changed since your last sync, and you also have local info edits in ${PROJECT_CONFIG_FILENAME} (${fields}).\n` +
42
- 'Run `cdpn status` to inspect differences, `cdpn pull` to sync remote changes, or `cdpn push --force` to overwrite.', {
43
- info_changes: infoAnalysis.changes,
44
- });
45
- }
46
- const hasFileChanges = hasDiffChanges(diff);
47
- const shouldPushInfo = infoAnalysis.changes.length > 0 && (infoAnalysis.localChanged || Boolean(options.force));
48
- const infoChangesToPush = shouldPushInfo ? infoAnalysis.changes : [];
49
- // Validate info patch constraints up-front before making any write API calls
50
- const infoPatch = shouldPushInfo ? buildInfoUpdatePatch(infoChangesToPush) : null;
51
- if (!hasFileChanges && !shouldPushInfo) {
52
- let backfilledLegacyInfo = false;
53
- if (!options.dryRun && infoAnalysis.changes.length === 0) {
54
- const remoteHash = hashPenInfo(infoAnalysis.remoteInfo);
55
- const needsInfoUpgrade = !infoAnalysis.tracked ||
56
- !isCompletePenInfo(project.config.info) ||
57
- project.config.last_synced_info_hash !== remoteHash;
58
- if (needsInfoUpgrade) {
59
- backfilledLegacyInfo = !infoAnalysis.tracked;
60
- const nextConfig = {
61
- ...project.config,
62
- ...buildPenInfoConfigFields(pen),
63
- };
64
- await writeProjectConfig(project.rootDir, nextConfig);
65
- project.config = nextConfig;
66
- }
67
- }
68
- if (!silent) {
69
- if (infoAnalysis.remoteChanged) {
70
- console.log(`${fmt.cyan('ℹ')} No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`);
71
- }
72
- else {
73
- console.log(`${fmt.green('✓')} Everything is up to date — nothing to push.`);
74
- if (backfilledLegacyInfo) {
75
- console.log(fmt.dim(` Added Pen info to ${PROJECT_CONFIG_FILENAME}.`));
76
- }
77
- }
3
+ import { findNearestConfig } from '../config/project.js';
4
+ import { PROJECT_CONFIG_FILENAME } from '../constants.js';
5
+ import { CliError } from '../errors.js';
6
+ import { assertValidVersionLabel, resolveAccessOrVisibility } from '../utils/cli-options.js';
7
+ import { fmt, shortId } from '../utils/format.js';
8
+ import { printJsonResponse } from '../utils/json.js';
9
+ import { defaultOutput } from '../utils/output.js';
10
+ import { isInteractive } from '../utils/prompts/index.js';
11
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
12
+ import { runBatchPush } from '../workflows/batch-pens.js';
13
+ import { offerBatchAllFallback, resolveBatchCommandTarget, } from '../workflows/batch-target.js';
14
+ import { createPenFromDirectory } from '../workflows/create-pen.js';
15
+ import { fetchLinkedPenOrHandleMissing } from '../workflows/missing-pen.js';
16
+ import { executePush } from '../workflows/push-pen.js';
17
+ export async function runPushCommand(options = {}) {
18
+ const output = options.output ?? defaultOutput;
19
+ const cwd = path.resolve(options.cwd ?? process.cwd());
20
+ const jsonMode = Boolean(options.json);
21
+ const interactive = !jsonMode && (options.interactive ?? isInteractive());
22
+ assertValidVersionLabel(options.label);
23
+ const resolvedAccess = resolveAccessOrVisibility(options.access, options.visibility);
24
+ const executeBatch = async (rootDir, discovered) => {
25
+ if (options.title?.trim()) {
26
+ throw new CliError(400, '--title cannot be used when pushing multiple Pens in a directory tree.');
78
27
  }
28
+ const batch = await runBatchPush({
29
+ rootDir,
30
+ discovered,
31
+ label: options.label,
32
+ force: options.force,
33
+ dryRun: options.dryRun,
34
+ wait: options.wait,
35
+ access: resolvedAccess,
36
+ password: options.password,
37
+ json: jsonMode,
38
+ interactive,
39
+ explicitProfile: options.explicitProfile,
40
+ baseUrl: options.baseUrl,
41
+ env: options.env,
42
+ homeDir: options.homeDir,
43
+ output,
44
+ prompts: options.prompts,
45
+ });
79
46
  return {
80
- pushed: false,
81
- dryRun: Boolean(options.dryRun),
82
- pen,
83
- versionId: remoteHead,
84
- build: pen.saved_version?.build ?? null,
85
- changes: { added: [], modified: [], deleted: [] },
86
- infoChanges: [],
87
- appliedPatches: [],
88
- remoteInfoChanged: infoAnalysis.remoteChanged,
47
+ pushed: !batch.dryRun && (batch.counts.pushed > 0 || batch.counts.created > 0),
48
+ created: !batch.dryRun && batch.counts.created > 0,
49
+ dryRun: batch.dryRun,
50
+ batch,
51
+ ...(batch.exitCode !== undefined ? { exitCode: batch.exitCode } : {}),
89
52
  };
90
- }
91
- const changes = {
92
- added: diff.added.map((item) => item.path),
93
- modified: diff.modified.map((item) => item.path),
94
- deleted: diff.deleted.map((item) => item.path),
95
53
  };
96
- if (!silent) {
97
- console.log(`${options.dryRun ? 'Dry-run pushing' : 'Pushing'} changes to ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)}:`);
98
- for (const item of diff.added)
99
- console.log(` ${fmt.green('+')} ${item.path}`);
100
- for (const item of diff.modified)
101
- console.log(` ${fmt.yellow('~')} ${item.path}`);
102
- for (const item of diff.deleted)
103
- console.log(` ${fmt.red('-')} ${item.path}`);
104
- for (const change of infoChangesToPush) {
105
- console.log(` ${fmt.yellow('~')} info.${change.field}: ${formatInfoValue(change.field, change.remote)} → ${formatInfoValue(change.field, change.local)}`);
106
- }
54
+ const resolvedTarget = await resolveBatchCommandTarget({
55
+ commandName: 'push',
56
+ cwd,
57
+ target: options.target,
58
+ interactive,
59
+ output,
60
+ prompts: options.prompts,
61
+ });
62
+ if (resolvedTarget.mode === 'batch') {
63
+ return executeBatch(resolvedTarget.rootDir, resolvedTarget.discovered);
107
64
  }
108
- let finalBuild = pen.saved_version?.build ?? null;
109
- let finalVersionId = remoteHead;
110
- let appliedPatches = [];
111
- let updatedPen = pen;
112
- let finalRemoteFiles;
113
- let localShaByPath;
114
- if (hasFileChanges) {
115
- const fileChanges = [];
116
- const binaryUploads = [];
117
- for (const item of [...diff.added, ...diff.modified]) {
118
- const local = item.local;
119
- // Note: CodePen API returns 400 on empty multipart parts, so 0-byte files always go as text JSON
120
- if (local.isBinary && local.buffer.length > 0) {
121
- binaryUploads.push({ path: item.path, content: local.buffer });
122
- }
123
- else {
124
- fileChanges.push({
125
- path: item.path,
126
- content: local.textContent ?? '',
127
- });
128
- }
65
+ const targetCwd = resolvedTarget.targetDir;
66
+ const nearest = await findNearestConfig(targetCwd);
67
+ if (!nearest) {
68
+ const fallback = await offerBatchAllFallback({
69
+ commandName: 'push',
70
+ targetDir: targetCwd,
71
+ fromExplicitDir: resolvedTarget.fromExplicitDir,
72
+ displayDir: resolvedTarget.displayDir,
73
+ dryRun: options.dryRun,
74
+ interactive,
75
+ output,
76
+ prompts: options.prompts,
77
+ });
78
+ if (fallback.action === 'batch') {
79
+ return executeBatch(targetCwd, fallback.discovered);
129
80
  }
130
- for (const item of diff.deleted) {
131
- fileChanges.push({
132
- path: item.path,
133
- delete: true,
134
- });
81
+ if (fallback.action === 'canceled') {
82
+ return { pushed: false, created: false, dryRun: Boolean(options.dryRun), aborted: true };
135
83
  }
136
- const expectedVersionId = options.force ? undefined : (localHead ?? remoteHead ?? undefined);
137
- const shouldWait = options.wait !== false;
138
- if (!silent) {
139
- console.log(shouldWait ? '\nUploading and building on CodePen…' : '\nUploading to CodePen…');
84
+ }
85
+ // First-time push: no linked .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
86
+ if (!nearest || !nearest.linked) {
87
+ if (options.dryRun) {
88
+ throw new CliError(400, nearest
89
+ ? `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} is not linked to an online Pen yet. --dry-run is only supported for an existing synced Pen.`
90
+ : `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
140
91
  }
141
- const writeResult = await client.writePenFiles(pen.id, {
142
- files: fileChanges,
143
- ...(options.label ? { label: options.label } : {}),
144
- ...(expectedVersionId ? { expected_version_id: expectedVersionId } : {}),
145
- ...(options.dryRun ? { dry_run: true } : {}),
146
- wait: shouldWait ? 45 : 0,
147
- }, binaryUploads);
148
- finalBuild = writeResult.build;
149
- if (finalBuild && shouldWait) {
150
- let lastStatus = `${finalBuild.status}:${finalBuild.id}`;
151
- finalBuild = await client.settleBuild(finalBuild, {
152
- onUpdate: (b) => {
153
- if (silent)
154
- return;
155
- const key = `${b.status}:${b.id}`;
156
- if (key !== lastStatus) {
157
- lastStatus = key;
158
- if (b.status === 'Running' || b.status === 'Queued') {
159
- console.log(fmt.dim(` Build ${shortId(b.id)}: ${b.status}…`));
160
- }
161
- else if (b.status === 'Canceled' && b.next_id) {
162
- console.log(fmt.dim(' Compiler requested patches — waiting for converged rebuild…'));
163
- }
164
- }
165
- },
166
- });
92
+ const targetDir = nearest ? nearest.rootDir : targetCwd;
93
+ const folderDisplay = path.relative(cwd, targetDir) || '.';
94
+ if (!jsonMode) {
95
+ output.log(fmt.dim(nearest
96
+ ? `Found unlinked ${PROJECT_CONFIG_FILENAME} with saved Pen info — pushing this local folder as a new CodePen 2.0 Pen.`
97
+ : `No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
167
98
  }
168
- if (finalBuild && !silent) {
169
- printBuildSummary(finalBuild);
99
+ const created = await createPenFromDirectory({
100
+ targetDir,
101
+ folderDisplay,
102
+ explicitProfile: options.explicitProfile,
103
+ title: options.title,
104
+ access: resolvedAccess,
105
+ password: options.password,
106
+ force: options.force,
107
+ wait: options.wait,
108
+ silent: jsonMode,
109
+ output,
110
+ baseUrl: options.baseUrl,
111
+ interactive,
112
+ env: options.env,
113
+ homeDir: options.homeDir,
114
+ prompts: options.prompts,
115
+ });
116
+ if (!created) {
117
+ return { pushed: false, created: false, dryRun: false, aborted: true };
170
118
  }
171
- finalVersionId = finalBuild?.version_id ?? writeResult.version?.id ?? null;
172
- appliedPatches = finalBuild?.applied_patches ?? [];
173
- updatedPen = writeResult.pen ?? pen;
174
- if (!options.dryRun) {
175
- // Re-read the converged version's source files so we write back any compiler patches
176
- let convergedFiles = writeResult.version?.files;
177
- if (finalVersionId && (appliedPatches.length > 0 || !convergedFiles)) {
178
- const version = await client.getVersion(finalVersionId);
179
- convergedFiles = version.files;
180
- }
181
- if (finalBuild && appliedPatches.length > 0) {
182
- await applyCompilerPatchesToDisk({
183
- client,
184
- rootDir: project.rootDir,
185
- patches: appliedPatches,
186
- convergedFiles,
187
- });
188
- if (!silent) {
189
- console.log(fmt.cyan('✓ Synced compiler patches back to local folder.'));
190
- }
191
- }
192
- // Re-scan local hashes so .cdpn.json reflects exact post-patch local state
193
- const postPushLocalFiles = await scanLocalFiles(project.rootDir);
194
- localShaByPath = new Map();
195
- for (const [p, lf] of postPushLocalFiles) {
196
- localShaByPath.set(p, lf.sha256);
197
- }
198
- finalRemoteFiles = convergedFiles ?? (await client.getPenFiles(pen.id));
199
- // If an info PATCH is still pending, persist the synced file manifest now while preserving
200
- // unpushed local `info` so a subsequent info validation error never leaves version metadata stale.
201
- if (shouldPushInfo) {
202
- const intermediateConfig = {
203
- url: project.config.url || updatedPen.urls.editor,
204
- pen_id: updatedPen.id,
205
- ...(project.config.profile ? { profile: project.config.profile } : {}),
206
- last_synced_version_id: finalVersionId,
207
- ...(project.config.last_synced_info_hash
208
- ? { last_synced_info_hash: project.config.last_synced_info_hash }
209
- : {}),
210
- editor: updatedPen.editor,
211
- ...(project.config.info !== undefined ? { info: project.config.info } : {}),
212
- files: buildSyncedFileMap(finalRemoteFiles, localShaByPath),
213
- };
214
- await writeProjectConfig(project.rootDir, intermediateConfig);
215
- project.config = intermediateConfig;
216
- }
217
- }
218
- }
219
- if (options.dryRun) {
220
- if (!silent) {
221
- console.log(`\n${fmt.cyan('ℹ')} Dry run complete — no changes were saved to CodePen` +
222
- (hasFileChanges && finalVersionId
223
- ? ` ${fmt.dim(`(ephemeral version ${shortId(finalVersionId)})`)}.`
224
- : '.'));
119
+ const buildFailed = created.build?.status === 'Failed';
120
+ if (jsonMode) {
121
+ printJsonResponse(buildFailed ? 422 : 201, buildFailed
122
+ ? `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}), but the initial build failed.`
123
+ : `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}).`, {
124
+ pushed: true,
125
+ created: true,
126
+ dry_run: false,
127
+ pen: created.pen,
128
+ profile: created.auth.profile,
129
+ folder: folderDisplay,
130
+ root_dir: created.project.rootDir,
131
+ config_path: created.project.configPath,
132
+ version_id: created.versionId,
133
+ build: created.build,
134
+ }, output);
225
135
  }
226
136
  return {
227
- pushed: false,
228
- dryRun: true,
229
- pen: updatedPen,
230
- versionId: hasFileChanges ? finalVersionId : remoteHead,
231
- build: hasFileChanges ? finalBuild : null,
232
- changes,
233
- infoChanges: infoChangesToPush,
234
- appliedPatches,
137
+ pushed: true,
138
+ created: true,
139
+ dryRun: false,
140
+ pen: created.pen,
141
+ versionId: created.versionId,
142
+ build: created.build,
143
+ ...(created.exitCode !== undefined ? { exitCode: created.exitCode } : {}),
235
144
  };
236
145
  }
237
- if (shouldPushInfo && infoPatch) {
238
- if (!silent) {
239
- console.log('\nUpdating Pen info on CodePen…');
240
- }
241
- updatedPen = await client.updatePen(pen.id, infoPatch);
242
- }
243
- const nextConfig = {
244
- url: project.config.url || updatedPen.urls.editor,
245
- pen_id: updatedPen.id,
246
- ...(project.config.profile ? { profile: project.config.profile } : {}),
247
- last_synced_version_id: hasFileChanges ? finalVersionId : project.config.last_synced_version_id,
248
- editor: updatedPen.editor,
249
- ...buildPenInfoConfigFields(updatedPen),
250
- ...(hasFileChanges && finalRemoteFiles && localShaByPath
251
- ? { files: buildSyncedFileMap(finalRemoteFiles, localShaByPath) }
252
- : project.config.files
253
- ? { files: project.config.files }
254
- : {}),
146
+ const project = {
147
+ rootDir: nearest.rootDir,
148
+ configPath: nearest.configPath,
149
+ config: nearest.config,
255
150
  };
256
- await writeProjectConfig(project.rootDir, nextConfig);
257
- project.config = nextConfig;
258
- if (!silent) {
259
- if (hasFileChanges && !shouldPushInfo && infoAnalysis.remoteChanged) {
260
- console.log(fmt.cyan(`ℹ Synced remote Pen info into ${PROJECT_CONFIG_FILENAME}.`));
151
+ const auth = await resolveCommandAuth({
152
+ explicitProfile: options.explicitProfile,
153
+ project,
154
+ interactive,
155
+ persistProfileToProject: !jsonMode,
156
+ output,
157
+ env: options.env,
158
+ homeDir: options.homeDir,
159
+ selectProfile: options.prompts?.select,
160
+ });
161
+ const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
162
+ const penLookup = await fetchLinkedPenOrHandleMissing({
163
+ client,
164
+ project,
165
+ auth,
166
+ commandName: 'push',
167
+ interactive,
168
+ json: jsonMode,
169
+ output,
170
+ prompts: options.prompts,
171
+ });
172
+ if (!penLookup.found) {
173
+ return { pushed: false, created: false, dryRun: Boolean(options.dryRun), aborted: true };
174
+ }
175
+ const result = await executePush(client, project, {
176
+ label: options.label,
177
+ force: options.force,
178
+ dryRun: options.dryRun,
179
+ wait: options.wait,
180
+ title: options.title,
181
+ access: resolvedAccess,
182
+ password: options.password,
183
+ json: jsonMode,
184
+ prefetchedPen: penLookup.pen,
185
+ silent: jsonMode,
186
+ output,
187
+ });
188
+ const hasFileChanges = result.changes.added.length > 0 ||
189
+ result.changes.modified.length > 0 ||
190
+ result.changes.deleted.length > 0;
191
+ const buildFailed = hasFileChanges && result.build?.status === 'Failed';
192
+ if (jsonMode) {
193
+ const payload = {
194
+ pushed: result.pushed,
195
+ created: false,
196
+ dry_run: result.dryRun,
197
+ pen: result.pen,
198
+ profile: auth.profile,
199
+ version_id: result.versionId,
200
+ build: result.build,
201
+ changes: result.changes,
202
+ info_changes: result.infoChanges,
203
+ applied_patches: result.appliedPatches,
204
+ };
205
+ if (result.dryRun) {
206
+ printJsonResponse(buildFailed ? 422 : 200, buildFailed
207
+ ? 'Dry run completed, but the build failed.'
208
+ : 'Dry run complete — no changes were saved to CodePen.', payload, output);
261
209
  }
262
- else if (hasFileChanges && !infoAnalysis.tracked) {
263
- console.log(fmt.dim(`Added Pen info to ${PROJECT_CONFIG_FILENAME}.`));
210
+ else if (!result.pushed) {
211
+ printJsonResponse(200, result.remoteInfoChanged
212
+ ? `No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`
213
+ : 'Everything is up to date — nothing to push.', payload, output);
264
214
  }
265
- }
266
- if (hasFileChanges && finalBuild?.status === 'Failed') {
267
- if (!silent) {
268
- console.log(`\n${fmt.yellow('!')} Files were saved as version ${fmt.dim(shortId(finalVersionId))}, but the build failed.`);
215
+ else if (buildFailed) {
216
+ printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload, output);
269
217
  }
270
- process.exitCode = 1;
271
- }
272
- else if (!silent) {
273
- if (hasFileChanges) {
274
- console.log(`\n${fmt.green('✓')} Pushed successfully ${fmt.dim(`(version ${shortId(finalVersionId)})`)}`);
275
- console.log(` Preview: ${fmt.cyan(updatedPen.urls.preview)}`);
218
+ else if (!hasFileChanges && result.infoChanges.length > 0) {
219
+ printJsonResponse(200, `Updated Pen info (${result.infoChanges.map((c) => c.field).join(', ')}).`, payload, output);
276
220
  }
277
221
  else {
278
- console.log(`\n${fmt.green('✓')} Updated Pen info successfully.`);
279
- console.log(` Editor: ${fmt.cyan(updatedPen.urls.editor)}`);
280
- console.log(` Preview: ${fmt.cyan(updatedPen.urls.preview)}`);
222
+ printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload, output);
281
223
  }
282
224
  }
283
225
  return {
284
- pushed: true,
285
- dryRun: false,
286
- pen: updatedPen,
287
- versionId: finalVersionId,
288
- build: finalBuild,
289
- changes,
290
- infoChanges: infoChangesToPush,
291
- appliedPatches,
226
+ pushed: result.pushed,
227
+ created: false,
228
+ dryRun: result.dryRun,
229
+ pen: result.pen,
230
+ versionId: result.versionId,
231
+ build: result.build,
232
+ changes: result.changes,
233
+ infoChanges: result.infoChanges,
234
+ appliedPatches: result.appliedPatches,
235
+ ...(result.exitCode !== undefined ? { exitCode: result.exitCode } : {}),
292
236
  };
293
237
  }
294
238
  export function registerPushCommand(program) {
295
239
  program
296
240
  .command('push')
297
- .description('Push local file and Pen info changes to CodePen (or push an unlinked demo folder as a new Pen)')
241
+ .argument('[target]', 'Directory path to push, or "all" to push all Pens in subdirectories')
242
+ .allowExcessArguments(false)
243
+ .description('Push local file and Pen info changes to CodePen (pass "all" to walk subdirectories, or push an unlinked folder as a new Pen)')
298
244
  .option('-m, --label <label>', 'Label for the saved version (max 80 chars)')
299
245
  .option('-f, --force', 'Overwrite remote head if moved (or skip missing index.html prompt on first push)')
300
- .option('--dry-run', 'Build proposed changes without saving them to the Pen head')
246
+ .option('--dry-run', 'Preview changes without saving them to CodePen')
301
247
  .option('--no-wait', 'Return as soon as files are saved without waiting for the build')
302
248
  .option('-t, --title <title>', 'Title for the new Pen when pushing an unlinked folder for the first time')
303
249
  .option('--access <level>', 'Privacy for a new Pen: Public, Private, Protected, or Collaborators')
250
+ .option('--visibility <level>', 'Alias for --access')
304
251
  .option('--password <password>', 'Password for a new Protected Pen (min 8 chars)')
305
252
  .option('--json', 'Output push result as JSON')
306
- .action(async (options, command) => {
307
- if (options.label && options.label.length > 80) {
308
- throw new CliError(400, 'Version label must be at most 80 characters.');
309
- }
310
- const explicitProfile = getGlobalProfileOption(command);
311
- const nearest = await findNearestConfig(process.cwd());
312
- // First-time push: no linked .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
313
- if (!nearest || !nearest.linked) {
314
- if (options.dryRun) {
315
- throw new CliError(400, nearest
316
- ? `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} is not linked to an online Pen yet. --dry-run is only supported for an existing synced Pen.`
317
- : `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
318
- }
319
- const targetDir = nearest ? nearest.rootDir : process.cwd();
320
- const folderDisplay = path.relative(process.cwd(), targetDir) || '.';
321
- if (!options.json) {
322
- console.log(fmt.dim(nearest
323
- ? `Found unlinked ${PROJECT_CONFIG_FILENAME} with saved Pen info — pushing this local folder as a new CodePen 2.0 Pen.`
324
- : `No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
325
- }
326
- const created = await createPenFromDirectory({
327
- targetDir,
328
- folderDisplay,
329
- explicitProfile,
330
- title: options.title,
331
- access: options.access,
332
- password: options.password,
333
- force: options.force,
334
- wait: options.wait,
335
- silent: Boolean(options.json),
336
- interactive: !options.json && isInteractive(),
337
- });
338
- if (created && options.json) {
339
- const buildFailed = created.build?.status === 'Failed';
340
- if (buildFailed) {
341
- process.exitCode = 1;
342
- }
343
- printJsonResponse(buildFailed ? 422 : 201, buildFailed
344
- ? `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}), but the initial build failed.`
345
- : `Created Pen ${created.pen.title || 'Untitled'} (${created.pen.id}).`, {
346
- pushed: true,
347
- created: true,
348
- dry_run: false,
349
- pen: created.pen,
350
- profile: created.auth.profile,
351
- folder: folderDisplay,
352
- root_dir: created.project.rootDir,
353
- config_path: created.project.configPath,
354
- version_id: created.versionId,
355
- build: created.build,
356
- });
357
- }
358
- return;
359
- }
360
- const project = {
361
- rootDir: nearest.rootDir,
362
- configPath: nearest.configPath,
363
- config: nearest.config,
364
- };
365
- const auth = await resolveCommandAuth({
366
- explicitProfile,
367
- project,
368
- interactive: !options.json && isInteractive(),
369
- persistProfileToProject: !options.json,
370
- });
371
- const client = new CodePenClient({ apiKey: auth.apiKey });
372
- const result = await executePush(client, project, {
253
+ .action(async (target, options, command) => {
254
+ const result = await runPushCommand({
373
255
  ...options,
374
- silent: Boolean(options.json),
256
+ target,
257
+ explicitProfile: getGlobalProfileOption(command),
375
258
  });
376
- if (options.json) {
377
- const hasFileChanges = result.changes.added.length > 0 ||
378
- result.changes.modified.length > 0 ||
379
- result.changes.deleted.length > 0;
380
- const buildFailed = hasFileChanges && result.build?.status === 'Failed';
381
- const payload = {
382
- pushed: result.pushed,
383
- created: false,
384
- dry_run: result.dryRun,
385
- pen: result.pen,
386
- profile: auth.profile,
387
- version_id: result.versionId,
388
- build: result.build,
389
- changes: result.changes,
390
- info_changes: result.infoChanges,
391
- applied_patches: result.appliedPatches,
392
- };
393
- if (result.dryRun) {
394
- if (buildFailed) {
395
- process.exitCode = 1;
396
- }
397
- printJsonResponse(buildFailed ? 422 : 200, buildFailed
398
- ? 'Dry run completed, but the build failed.'
399
- : 'Dry run complete — no changes were saved to CodePen.', payload);
400
- }
401
- else if (!result.pushed) {
402
- printJsonResponse(200, result.remoteInfoChanged
403
- ? `No local changes to push. Remote Pen info has changed on CodePen — run \`cdpn pull\` to update ${PROJECT_CONFIG_FILENAME}, or \`cdpn push --force\` to overwrite.`
404
- : 'Everything is up to date — nothing to push.', payload);
405
- }
406
- else if (buildFailed) {
407
- process.exitCode = 1;
408
- printJsonResponse(422, `Files were saved as version ${shortId(result.versionId)}, but the build failed.`, payload);
409
- }
410
- else if (!hasFileChanges && result.infoChanges.length > 0) {
411
- printJsonResponse(200, `Updated Pen info (${result.infoChanges.map((c) => c.field).join(', ')}).`, payload);
412
- }
413
- else {
414
- printJsonResponse(200, `Pushed successfully (version ${shortId(result.versionId)}).`, payload);
415
- }
259
+ if (result.exitCode !== undefined) {
260
+ process.exitCode = result.exitCode;
416
261
  }
417
262
  });
418
263
  }