codepen-commander 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,6 +97,8 @@ The `info` section tracks the Pen’s editable metadata (`title`, `description`,
97
97
 
98
98
  Older `.cdpn.json` files created without an `info` section remain fully supported: `cdpn` will never overwrite remote metadata when `info` is absent, and will seamlessly populate `info` on your next `cdpn pull` or `cdpn push`.
99
99
 
100
+ You can also run `cdpn delete --keep-info` to delete the online Pen while stripping `.cdpn.json` down to only its `info` section (unlinked). When you later push the folder for the first time with `cdpn push` or `cdpn deploy`, the saved `title`, `description`, `tags`, `access`, and `template` are reused automatically without re-prompting for title or visibility (explicit `--title` / `--access` flags still override them, and `Protected` Pens still prompt for or require `--password`).
101
+
100
102
  > **Why `.cdpn.json` instead of `.codepen`?**
101
103
  > CodePen 2.0 Pens already contain a `.codepen/` directory (housing `.codepen/pen.config.json`). Using `.cdpn.json` avoids filesystem collisions while allowing `.codepen/pen.config.json` to sync cleanly with CodePen.
102
104
 
@@ -139,7 +141,7 @@ All commands accept the global `--profile <name>` flag to override the active pr
139
141
  | `cdpn clone <url> [folder] [--force] [--json]` | Clone a CodePen Pen into a local folder (auto-matches stored profile by URL owner; offers to convert Classic Pens or clone them unlinked; offers browser fork-and-clone fallback for unowned Pens) |
140
142
  | `cdpn pull [--force] [--json]` | Pull latest remote file and Pen info changes into an existing cloned folder (requires `.cdpn.json`) |
141
143
  | `cdpn status [--json]` | Show active profile, file and Pen info diffs, remote head, build & deployment status |
142
- | `cdpn push [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local file and `.cdpn.json` Pen info changes (text & binary + deletions), or push an unlinked local demo folder as a new Pen (checks `index.html`, asks account, title, and visibility) |
144
+ | `cdpn push [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local file and `.cdpn.json` Pen info changes (text & binary + deletions), or push an unlinked local demo folder as a new Pen (reuses retained `.cdpn.json` `info` if present; otherwise checks `index.html`, asks account, title, and visibility) |
143
145
  | `cdpn deploy [--no-push] [--version <id>] [--force] [--json]` | Push local changes (creating a Pen first if unlinked) and deploy to CodePen Hosting |
144
146
  | `cdpn undeploy [--yes] [--json]` | Take down the live deployment (Pen & versions remain intact) |
145
147
  | `cdpn domains [list] [--json]` | Show the default deployed URL, custom domains, verification status, and required DNS records |
@@ -150,7 +152,7 @@ All commands accept the global `--profile <name>` flag to override the active pr
150
152
  | `cdpn versions [--limit <n>] [--json]` | List saved versions with build status, labels, and markers (`head`, `local`, `deployed`) |
151
153
  | `cdpn rollback [version-id] [-m <label>] [--yes] [--json]` | Restore an older saved version to head and sync files locally |
152
154
  | `cdpn privacy [level] [--password <pw>] [--show] [--json]` | View or update Pen privacy (`Public`, `Private`, `Protected`, `Collaborators`; alias: `cdpn access`; requires `.cdpn.json` in current folder) |
153
- | `cdpn delete [--yes] [--json]` | Delete the online Pen on CodePen (moves to Deleted Items for 3 days) and remove `.cdpn.json` while keeping local files untouched (aliases: `cdpn del`, `cdpn rm`) |
155
+ | `cdpn delete [--keep-info] [--yes] [--json]` | Delete the online Pen on CodePen (moves to Deleted Items for 3 days) and remove `.cdpn.json` — or keep only its `info` section with `--keep-info` for a later first push — while keeping local files untouched (aliases: `cdpn del`, `cdpn rm`) |
154
156
  | `cdpn info [--title ...] [--tags ...] [--access ...] [--template true\|false] [--json]` | View or update Pen metadata |
155
157
  | `cdpn settings [--auto-deploy ...] [--indent-with ...] [--json]` | View or update Pen editor & deployment settings |
156
158
 
@@ -1,9 +1,9 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { CodePenClient } from '../api/client.js';
4
- import { buildSyncedFileMap, hasProjectConfigInDir, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
4
+ import { buildSyncedFileMap, hasProjectConfigInDir, PROJECT_CONFIG_FILENAME, readProjectConfigFile, writeProjectConfig, } from '../config/project.js';
5
5
  import { scanLocalFiles } from '../sync/fs.js';
6
- import { buildPenInfoConfigFields } from '../sync/info.js';
6
+ import { buildPenInfoConfigFields, hasAnyPenInfoFields } from '../sync/info.js';
7
7
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
8
8
  import { fmt, printBuildSummary, shortId } from '../utils/format.js';
9
9
  import { extractHtmlTitle } from '../utils/html.js';
@@ -86,12 +86,15 @@ export function printMissingIndexHtmlWarning(targetDir, fileCount) {
86
86
  }
87
87
  /**
88
88
  * First-time Pen creation flow used by `cdpn push` and `cdpn deploy` when invoked inside
89
- * an unlinked local demo folder:
89
+ * an unlinked local demo folder (including one with retained `info` in `.cdpn.json` from
90
+ * `cdpn delete --keep-info`):
90
91
  *
91
92
  * 1. Checks for `/index.html`; if absent, displays a prominent warning and asks for confirmation.
92
93
  * 2. Resolves or asks which CodePen account/profile to push to (when multiple keys are in `~/.cdpn`).
93
- * 3. Asks for a title (pre-filled from `index.html`'s `<title>` when available).
94
- * 4. Asks for visibility (`Public` default, `Private`, `Protected`, or `Collaborators`).
94
+ * 3. Uses retained `info.title` (or `--title`), otherwise asks for a title (pre-filled from `index.html`'s `<title>`).
95
+ * 4. Uses retained `info.access` (or `--access`), otherwise asks for visibility (`Public` default, `Private`,
96
+ * `Protected`, or `Collaborators`), prompting for a password if `Protected`.
97
+ * 5. Carries over retained `description`, `tags`, and `template` from `.cdpn.json` when present.
95
98
  */
96
99
  export async function createPenFromDirectory(options) {
97
100
  const silent = Boolean(options.silent);
@@ -99,23 +102,45 @@ export async function createPenFromDirectory(options) {
99
102
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
100
103
  const textImpl = options.prompts?.text ?? promptText;
101
104
  const selectImpl = options.prompts?.select ?? promptSelect;
102
- // Validate --access / --password early before prompting or scanning
103
- const prevalidatedAccess = normalizeAccess(options.access);
104
- if (prevalidatedAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
105
+ // Validate explicit CLI --access / --password early before reading config or scanning
106
+ const explicitAccess = normalizeAccess(options.access);
107
+ if (explicitAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
105
108
  throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
106
109
  }
107
- if (prevalidatedAccess === 'Protected' && !options.password && !interactive) {
110
+ if (explicitAccess === 'Protected' && !options.password && !interactive) {
108
111
  throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
109
112
  }
110
113
  const targetDir = path.resolve(options.targetDir);
111
114
  const folderDisplay = options.folderDisplay;
115
+ let retainedInfo;
112
116
  if (await hasProjectConfigInDir(targetDir)) {
113
- throw new CliError(409, `${targetDir} already contains ${PROJECT_CONFIG_FILENAME}. Use \`cdpn push\` to update the existing Pen.`);
117
+ const existing = await readProjectConfigFile(targetDir);
118
+ if (existing.linked) {
119
+ throw new CliError(409, `${targetDir} already contains ${PROJECT_CONFIG_FILENAME}. Use \`cdpn push\` to update the existing Pen.`);
120
+ }
121
+ retainedInfo = existing.config.info;
122
+ }
123
+ const effectiveRawAccess = options.access ?? retainedInfo?.access;
124
+ const effectiveAccess = normalizeAccess(effectiveRawAccess);
125
+ const effectiveDescription = options.description !== undefined ? options.description : retainedInfo?.description;
126
+ const effectiveTags = options.tags !== undefined ? options.tags : retainedInfo?.tags;
127
+ const effectiveTemplate = options.template !== undefined ? options.template : retainedInfo?.template;
128
+ // Validate effective metadata constraints early before scanning or prompting
129
+ if (effectiveTags && effectiveTags.length > 5) {
130
+ throw new CliError(400, `CodePen allows at most 5 tags per Pen (found ${effectiveTags.length}${options.tags === undefined ? ` in ${PROJECT_CONFIG_FILENAME}` : ''}).`);
131
+ }
132
+ if (effectiveAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
133
+ throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
134
+ }
135
+ if (effectiveAccess === 'Protected' && !options.password && !interactive) {
136
+ throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
114
137
  }
115
138
  const scanned = await scanLocalFiles(targetDir);
116
139
  if (scanned.size === 0) {
117
- throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found and no syncable files in ${targetDir}.\n` +
118
- 'Run `cdpn clone <url>` to clone an existing Pen or `cdpn new` to scaffold a brand-new Pen.');
140
+ throw new CliError(400, retainedInfo !== undefined
141
+ ? `No syncable files found in ${targetDir} (only an unlinked ${PROJECT_CONFIG_FILENAME} is present).`
142
+ : `No ${PROJECT_CONFIG_FILENAME} found and no syncable files in ${targetDir}.\n` +
143
+ 'Run `cdpn clone <url>` to clone an existing Pen or `cdpn new` to scaffold a brand-new Pen.');
119
144
  }
120
145
  const indexFile = scanned.get('/index.html');
121
146
  // 1. Check for index.html before pushing a local demo for the first time
@@ -144,14 +169,14 @@ export async function createPenFromDirectory(options) {
144
169
  selectProfile: selectImpl,
145
170
  });
146
171
  const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
147
- // 3. Determine title (defaulting to index.html's <title> when present)
148
- const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
149
- ? extractHtmlTitle(indexFile.textContent)
150
- : null;
151
- const fallbackTitle = path.basename(targetDir) || 'Untitled';
152
- const defaultTitle = htmlTitle ?? fallbackTitle;
153
- let title = options.title?.trim();
172
+ // 3. Determine title (explicit --title > retained info.title > index.html <title> > folder basename)
173
+ let title = options.title?.trim() || retainedInfo?.title?.trim();
154
174
  if (!title) {
175
+ const htmlTitle = indexFile && !indexFile.isBinary && indexFile.textContent
176
+ ? extractHtmlTitle(indexFile.textContent)
177
+ : null;
178
+ const fallbackTitle = path.basename(targetDir) || 'Untitled';
179
+ const defaultTitle = htmlTitle ?? fallbackTitle;
155
180
  if (interactive) {
156
181
  title = (await textImpl('Pen title', defaultTitle)).trim() || defaultTitle;
157
182
  }
@@ -159,9 +184,9 @@ export async function createPenFromDirectory(options) {
159
184
  title = defaultTitle;
160
185
  }
161
186
  }
162
- // 4. Ask for visibility (Public by default, Private, Protected, or Collaborators)
187
+ // 4. Resolve visibility (explicit --access > retained info.access > interactive picker / Public default)
163
188
  const { access, password } = await resolveVisibilityAndPassword({
164
- rawAccess: options.access,
189
+ rawAccess: effectiveRawAccess,
165
190
  rawPassword: options.password,
166
191
  interactive,
167
192
  prompts: options.prompts,
@@ -178,15 +203,18 @@ export async function createPenFromDirectory(options) {
178
203
  }
179
204
  const shouldWait = options.wait !== false;
180
205
  if (!silent) {
206
+ if (hasAnyPenInfoFields(retainedInfo)) {
207
+ console.log(fmt.dim(`Using saved Pen info from ${PROJECT_CONFIG_FILENAME}.`));
208
+ }
181
209
  console.log(`\nCreating new Pen from ${textFiles.length + binaryFiles.length} local file(s)…`);
182
210
  }
183
211
  const created = await client.createPen({
184
212
  ...(title ? { title } : {}),
185
- ...(options.description ? { description: options.description } : {}),
186
- ...(options.tags && options.tags.length > 0 ? { tags: options.tags } : {}),
213
+ ...(effectiveDescription ? { description: effectiveDescription } : {}),
214
+ ...(effectiveTags && effectiveTags.length > 0 ? { tags: effectiveTags } : {}),
187
215
  access,
188
216
  ...(password ? { password } : {}),
189
- ...(options.template ? { template: true } : {}),
217
+ ...(effectiveTemplate ? { template: true } : {}),
190
218
  files: textFiles,
191
219
  wait: shouldWait ? 45 : 0,
192
220
  }, binaryFiles);
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import { CodePenClient } from '../api/client.js';
3
- import { PROJECT_CONFIG_FILENAME, requireProjectInDir, } from '../config/project.js';
3
+ import { PROJECT_CONFIG_FILENAME, requireProjectInDir, writeUnlinkedProjectInfo, } from '../config/project.js';
4
+ import { analyzeInfoSync, extractPenInfo, normalizePartialPenInfo } from '../sync/info.js';
4
5
  import { fmt } from '../utils/format.js';
5
6
  import { CliError, printJsonResponse } from '../utils/json.js';
6
7
  import { isInteractive, promptConfirm, promptSelect, } from '../utils/prompts.js';
@@ -9,12 +10,14 @@ export const CODEPEN_DELETED_ITEMS_URL = 'https://codepen.io/your-work?item_type
9
10
  /**
10
11
  * Deletes the online Pen linked to `.cdpn.json` directly inside `options.cwd`
11
12
  * (moves it to CodePen Deleted Items, restorable for 3 days) and removes `.cdpn.json`
12
- * only after the remote deletion succeeds. Local project files are kept untouched.
13
+ * (or retains only its `info` section when `keepInfo` is true) only after the remote
14
+ * deletion succeeds. Local project files are kept untouched.
13
15
  *
14
16
  * Returns `null` if the user cancels at the confirmation prompt.
15
17
  */
16
18
  export async function deletePenCommand(options = {}) {
17
19
  const cwd = options.cwd ?? process.cwd();
20
+ const keepInfo = Boolean(options.keepInfo);
18
21
  const interactive = (options.interactive ?? isInteractive()) && !options.json;
19
22
  const confirmImpl = options.prompts?.confirm ?? promptConfirm;
20
23
  const selectImpl = options.prompts?.select ?? promptSelect;
@@ -44,40 +47,83 @@ export async function deletePenCommand(options = {}) {
44
47
  if (pen.deployment) {
45
48
  console.log(` Live: ${fmt.yellow(pen.deployment.url)} ${fmt.dim('(will also be taken down)')}`);
46
49
  }
47
- console.log(fmt.dim(`\nLocal files will stay untouched; ${PROJECT_CONFIG_FILENAME} will be removed after deletion succeeds.`));
48
- const ok = await confirmImpl(`Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME}?`, false);
50
+ console.log(fmt.dim(keepInfo
51
+ ? `\nLocal files will stay untouched; only the "info" section will be kept in ${PROJECT_CONFIG_FILENAME} after deletion succeeds.`
52
+ : `\nLocal files will stay untouched; ${PROJECT_CONFIG_FILENAME} will be removed after deletion succeeds.`));
53
+ const ok = await confirmImpl(keepInfo
54
+ ? `Delete this Pen on CodePen (moves to Deleted Items for 3 days) and keep only "info" in ${PROJECT_CONFIG_FILENAME}?`
55
+ : `Delete this Pen on CodePen (moves to Deleted Items for 3 days) and remove ${PROJECT_CONFIG_FILENAME}?`, false);
49
56
  if (!ok) {
50
57
  console.log('Aborted.');
51
58
  return null;
52
59
  }
53
60
  }
54
61
  await client.deletePen(project.config.pen_id);
55
- // Remove `.cdpn.json` only after remote deletion succeeded
56
- await fs.unlink(project.configPath);
62
+ // Modify or remove `.cdpn.json` only after remote deletion succeeded
63
+ let retainedInfo;
64
+ if (keepInfo) {
65
+ const remoteInfo = extractPenInfo(pen);
66
+ const infoAnalysis = analyzeInfoSync(project.config.info, project.config.last_synced_info_hash, pen);
67
+ retainedInfo =
68
+ infoAnalysis.localChanged && project.config.info
69
+ ? { ...remoteInfo, ...normalizePartialPenInfo(project.config.info) }
70
+ : remoteInfo;
71
+ await writeUnlinkedProjectInfo(project.rootDir, retainedInfo);
72
+ }
73
+ else {
74
+ await fs.unlink(project.configPath);
75
+ }
57
76
  if (options.json) {
58
- printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${PROJECT_CONFIG_FILENAME}.`, {
59
- pen_id: pen.id,
60
- title: pen.title,
61
- profile: auth.profile,
62
- editor_url: pen.urls.editor,
63
- deleted: true,
64
- config_removed: true,
65
- restore_url: CODEPEN_DELETED_ITEMS_URL,
66
- });
77
+ if (keepInfo) {
78
+ printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and retained info in ${PROJECT_CONFIG_FILENAME}.`, {
79
+ pen_id: pen.id,
80
+ title: pen.title,
81
+ profile: auth.profile,
82
+ editor_url: pen.urls.editor,
83
+ deleted: true,
84
+ config_removed: false,
85
+ info_retained: true,
86
+ info: retainedInfo,
87
+ restore_url: CODEPEN_DELETED_ITEMS_URL,
88
+ });
89
+ }
90
+ else {
91
+ printJsonResponse(200, `Deleted ${pen.title || 'Untitled'} (${pen.id}) on CodePen and removed ${PROJECT_CONFIG_FILENAME}.`, {
92
+ pen_id: pen.id,
93
+ title: pen.title,
94
+ profile: auth.profile,
95
+ editor_url: pen.urls.editor,
96
+ deleted: true,
97
+ config_removed: true,
98
+ info_retained: false,
99
+ restore_url: CODEPEN_DELETED_ITEMS_URL,
100
+ });
101
+ }
67
102
  }
68
103
  else {
69
104
  console.log(`\n${fmt.green('✓')} Deleted ${fmt.bold(pen.title || 'Untitled')} ${fmt.dim(`(${pen.id})`)} on CodePen ${fmt.dim('(moved to Deleted Items; restorable for 3 days)')}`);
70
- if (auth.profile) {
71
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
105
+ if (keepInfo) {
106
+ if (auth.profile) {
107
+ console.log(` Profile: ${fmt.cyan(auth.profile)}`);
108
+ }
109
+ console.log(` Retained: ${fmt.cyan(`info in ${PROJECT_CONFIG_FILENAME}`)} ${fmt.dim('(unlinked; local files were kept untouched)')}`);
110
+ console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
111
+ }
112
+ else {
113
+ if (auth.profile) {
114
+ console.log(` Profile: ${fmt.cyan(auth.profile)}`);
115
+ }
116
+ console.log(` Removed: ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(local files were kept untouched)')}`);
117
+ console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
72
118
  }
73
- console.log(` Removed: ${fmt.cyan(PROJECT_CONFIG_FILENAME)} ${fmt.dim('(local files were kept untouched)')}`);
74
- console.log(` Restore: ${fmt.dim(CODEPEN_DELETED_ITEMS_URL)}`);
75
119
  }
76
120
  return {
77
121
  pen,
78
122
  project,
79
123
  auth,
80
- configRemoved: true,
124
+ configRemoved: !keepInfo,
125
+ infoRetained: keepInfo,
126
+ ...(retainedInfo ? { retainedInfo } : {}),
81
127
  };
82
128
  }
83
129
  export function registerDeleteCommand(program) {
@@ -86,11 +132,13 @@ export function registerDeleteCommand(program) {
86
132
  .aliases(['del', 'rm'])
87
133
  .allowExcessArguments(false)
88
134
  .description(`Delete the online Pen on CodePen (moves to Deleted Items) and remove ${PROJECT_CONFIG_FILENAME}`)
135
+ .option('--keep-info', `Keep Pen info in ${PROJECT_CONFIG_FILENAME} so it is reused on the next push`)
89
136
  .option('-y, --yes', 'Skip confirmation prompt')
90
137
  .option('--json', 'Output deletion result as JSON')
91
138
  .action(async (options, command) => {
92
139
  await deletePenCommand({
93
140
  yes: options.yes,
141
+ keepInfo: options.keepInfo,
94
142
  json: options.json,
95
143
  explicitProfile: getGlobalProfileOption(command),
96
144
  });
@@ -1,5 +1,6 @@
1
+ import path from 'node:path';
1
2
  import { CodePenClient } from '../api/client.js';
2
- import { findProject, PROJECT_CONFIG_FILENAME, requireProject } from '../config/project.js';
3
+ import { findNearestConfig, PROJECT_CONFIG_FILENAME, requireProject, } from '../config/project.js';
3
4
  import { fmt, shortId } from '../utils/format.js';
4
5
  import { CliError, printJsonResponse } from '../utils/json.js';
5
6
  import { isInteractive, promptConfirm } from '../utils/prompts.js';
@@ -23,7 +24,14 @@ export function registerDeployCommands(program) {
23
24
  throw new CliError(400, 'Version label must be at most 80 characters.');
24
25
  }
25
26
  const explicitProfile = getGlobalProfileOption(command);
26
- let project = await findProject(process.cwd());
27
+ const nearest = await findNearestConfig(process.cwd());
28
+ let project = nearest?.linked
29
+ ? {
30
+ rootDir: nearest.rootDir,
31
+ configPath: nearest.configPath,
32
+ config: nearest.config,
33
+ }
34
+ : null;
27
35
  let versionIdToDeploy = options.version;
28
36
  let client;
29
37
  let activeProfile;
@@ -31,15 +39,22 @@ export function registerDeployCommands(program) {
31
39
  let pushedChanges = false;
32
40
  if (!project) {
33
41
  if (options.push === false || options.version) {
34
- throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\n` +
35
- 'Run `cdpn clone <url>` to clone a Pen or run `cdpn deploy` without --no-push/--version to create one first.');
42
+ throw new CliError(404, nearest
43
+ ? `${PROJECT_CONFIG_FILENAME} in ${nearest.rootDir} only contains Pen info and is not linked to an online Pen yet.\n` +
44
+ 'Run `cdpn deploy` without --no-push/--version to create and link it first.'
45
+ : `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\n` +
46
+ 'Run `cdpn clone <url>` to clone a Pen or run `cdpn deploy` without --no-push/--version to create one first.');
36
47
  }
48
+ const targetDir = nearest ? nearest.rootDir : process.cwd();
49
+ const folderDisplay = path.relative(process.cwd(), targetDir) || '.';
37
50
  if (!options.json) {
38
- console.log(fmt.dim(`No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen before deploying.`));
51
+ console.log(fmt.dim(nearest
52
+ ? `Found unlinked ${PROJECT_CONFIG_FILENAME} with saved Pen info — pushing this local folder as a new CodePen 2.0 Pen before deploying.`
53
+ : `No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen before deploying.`));
39
54
  }
40
55
  const created = await createPenFromDirectory({
41
- targetDir: process.cwd(),
42
- folderDisplay: '.',
56
+ targetDir,
57
+ folderDisplay,
43
58
  explicitProfile,
44
59
  title: options.title,
45
60
  access: options.access,
package/commands/push.js CHANGED
@@ -1,5 +1,6 @@
1
+ import path from 'node:path';
1
2
  import { CodePenClient } from '../api/client.js';
2
- import { buildSyncedFileMap, findProject, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
3
+ import { buildSyncedFileMap, findNearestConfig, PROJECT_CONFIG_FILENAME, writeProjectConfig, } from '../config/project.js';
3
4
  import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
4
5
  import { createPenFromDirectory } from './create-pen.js';
5
6
  import { computeSyncDiff, hasDiffChanges } from '../sync/diff.js';
@@ -307,18 +308,24 @@ export function registerPushCommand(program) {
307
308
  throw new CliError(400, 'Version label must be at most 80 characters.');
308
309
  }
309
310
  const explicitProfile = getGlobalProfileOption(command);
310
- const project = await findProject(process.cwd());
311
- // First-time push: no .cdpn.json found -> push local folder as a brand-new CodePen 2.0 Pen
312
- if (!project) {
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) {
313
314
  if (options.dryRun) {
314
- throw new CliError(400, `No ${PROJECT_CONFIG_FILENAME} found. --dry-run is only supported for an existing synced Pen.`);
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.`);
315
318
  }
319
+ const targetDir = nearest ? nearest.rootDir : process.cwd();
320
+ const folderDisplay = path.relative(process.cwd(), targetDir) || '.';
316
321
  if (!options.json) {
317
- console.log(fmt.dim(`No ${PROJECT_CONFIG_FILENAME} found — pushing this local folder as a new CodePen 2.0 Pen.`));
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.`));
318
325
  }
319
326
  const created = await createPenFromDirectory({
320
- targetDir: process.cwd(),
321
- folderDisplay: '.',
327
+ targetDir,
328
+ folderDisplay,
322
329
  explicitProfile,
323
330
  title: options.title,
324
331
  access: options.access,
@@ -341,7 +348,7 @@ export function registerPushCommand(program) {
341
348
  dry_run: false,
342
349
  pen: created.pen,
343
350
  profile: created.auth.profile,
344
- folder: '.',
351
+ folder: folderDisplay,
345
352
  root_dir: created.project.rootDir,
346
353
  config_path: created.project.configPath,
347
354
  version_id: created.versionId,
@@ -350,6 +357,11 @@ export function registerPushCommand(program) {
350
357
  }
351
358
  return;
352
359
  }
360
+ const project = {
361
+ rootDir: nearest.rootDir,
362
+ configPath: nearest.configPath,
363
+ config: nearest.config,
364
+ };
353
365
  const auth = await resolveCommandAuth({
354
366
  explicitProfile,
355
367
  project,
package/config/project.js CHANGED
@@ -3,18 +3,26 @@ import path from 'node:path';
3
3
  import { normalizePartialPenInfo, parsePenInfoInput } from '../sync/info.js';
4
4
  import { CliError } from '../utils/json.js';
5
5
  export const PROJECT_CONFIG_FILENAME = '.cdpn.json';
6
+ function createUnlinkedProjectError(rootDir) {
7
+ return new CliError(404, `${PROJECT_CONFIG_FILENAME} in ${rootDir} only contains Pen info and is not linked to an online Pen yet.\n` +
8
+ 'Run `cdpn push` to push this folder as a new Pen on CodePen.');
9
+ }
6
10
  /**
7
- * Walks upward from `startDir` looking for `.cdpn.json` (similar to how git locates `.git`).
11
+ * Walks upward from `startDir` looking for the nearest `.cdpn.json` (linked or unlinked info-only).
12
+ * Stops at the first `.cdpn.json` encountered so nested unlinked folders never leak to a parent Pen.
8
13
  */
9
- export async function findProject(startDir = process.cwd()) {
14
+ export async function findNearestConfig(startDir = process.cwd()) {
10
15
  let current = path.resolve(startDir);
11
16
  for (;;) {
12
17
  const configPath = path.join(current, PROJECT_CONFIG_FILENAME);
13
18
  try {
14
19
  const stat = await fs.lstat(configPath);
15
20
  if (stat.isFile()) {
16
- const config = await readProjectConfig(current);
17
- return { rootDir: current, configPath, config };
21
+ const parsed = await readProjectConfigFile(current);
22
+ if (parsed.linked) {
23
+ return { linked: true, rootDir: current, configPath, config: parsed.config };
24
+ }
25
+ return { linked: false, rootDir: current, configPath, config: parsed.config };
18
26
  }
19
27
  }
20
28
  catch (error) {
@@ -29,15 +37,37 @@ export async function findProject(startDir = process.cwd()) {
29
37
  current = parent;
30
38
  }
31
39
  }
40
+ /**
41
+ * Walks upward from `startDir` looking for a linked `.cdpn.json` (similar to how git locates `.git`).
42
+ * Returns `null` if no `.cdpn.json` is found or if the nearest `.cdpn.json` is unlinked (info-only).
43
+ */
44
+ export async function findProject(startDir = process.cwd()) {
45
+ const nearest = await findNearestConfig(startDir);
46
+ if (!nearest || !nearest.linked) {
47
+ return null;
48
+ }
49
+ return {
50
+ rootDir: nearest.rootDir,
51
+ configPath: nearest.configPath,
52
+ config: nearest.config,
53
+ };
54
+ }
32
55
  export async function requireProject(startDir = process.cwd()) {
33
- const project = await findProject(startDir);
34
- if (!project) {
56
+ const nearest = await findNearestConfig(startDir);
57
+ if (!nearest) {
35
58
  throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\nRun \`cdpn clone <url>\` to clone a Pen or \`cdpn new\` to create one.`);
36
59
  }
37
- return project;
60
+ if (!nearest.linked) {
61
+ throw createUnlinkedProjectError(nearest.rootDir);
62
+ }
63
+ return {
64
+ rootDir: nearest.rootDir,
65
+ configPath: nearest.configPath,
66
+ config: nearest.config,
67
+ };
38
68
  }
39
69
  /**
40
- * Requires `.cdpn.json` to exist directly inside `dir` (does NOT walk upward to parent directories).
70
+ * Requires a linked `.cdpn.json` to exist directly inside `dir` (does NOT walk upward to parent directories).
41
71
  */
42
72
  export async function requireProjectInDir(dir = process.cwd()) {
43
73
  const resolvedDir = path.resolve(dir);
@@ -72,8 +102,13 @@ export async function hasProjectConfigInDir(dir) {
72
102
  throw error;
73
103
  }
74
104
  }
75
- export async function readProjectConfig(rootDir) {
76
- const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
105
+ /**
106
+ * Reads and validates `.cdpn.json` from `rootDir`, supporting both linked Pen configs
107
+ * and unlinked info-only configs (e.g. retained via `cdpn delete --keep-info`).
108
+ */
109
+ export async function readProjectConfigFile(rootDir) {
110
+ const resolvedDir = path.resolve(rootDir);
111
+ const configPath = path.join(resolvedDir, PROJECT_CONFIG_FILENAME);
77
112
  const raw = await fs.readFile(configPath, 'utf8');
78
113
  let parsed;
79
114
  try {
@@ -86,6 +121,17 @@ export async function readProjectConfig(rootDir) {
86
121
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: expected a JSON object.`);
87
122
  }
88
123
  const record = parsed;
124
+ // Unlinked info-only `.cdpn.json`: no pen_id or url, only `info`
125
+ if (record.pen_id === undefined && record.url === undefined && record.info !== undefined) {
126
+ if (record.info === null) {
127
+ throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: "info" must be a JSON object.`);
128
+ }
129
+ const info = parsePenInfoInput(record.info, PROJECT_CONFIG_FILENAME);
130
+ return {
131
+ linked: false,
132
+ config: { info },
133
+ };
134
+ }
89
135
  if (typeof record.pen_id !== 'string' || !record.pen_id.trim()) {
90
136
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "pen_id" string.`);
91
137
  }
@@ -123,16 +169,26 @@ export async function readProjectConfig(rootDir) {
123
169
  }
124
170
  }
125
171
  return {
126
- url: record.url.trim(),
127
- pen_id: record.pen_id.trim(),
128
- ...(profile ? { profile } : {}),
129
- last_synced_version_id: lastSynced,
130
- ...(lastSyncedInfoHash ? { last_synced_info_hash: lastSyncedInfoHash } : {}),
131
- ...(editor ? { editor } : {}),
132
- ...(info !== undefined ? { info } : {}),
133
- ...(files ? { files } : {}),
172
+ linked: true,
173
+ config: {
174
+ url: record.url.trim(),
175
+ pen_id: record.pen_id.trim(),
176
+ ...(profile ? { profile } : {}),
177
+ last_synced_version_id: lastSynced,
178
+ ...(lastSyncedInfoHash ? { last_synced_info_hash: lastSyncedInfoHash } : {}),
179
+ ...(editor ? { editor } : {}),
180
+ ...(info !== undefined ? { info } : {}),
181
+ ...(files ? { files } : {}),
182
+ },
134
183
  };
135
184
  }
185
+ export async function readProjectConfig(rootDir) {
186
+ const parsed = await readProjectConfigFile(rootDir);
187
+ if (!parsed.linked) {
188
+ throw createUnlinkedProjectError(path.resolve(rootDir));
189
+ }
190
+ return parsed.config;
191
+ }
136
192
  export async function writeProjectConfig(rootDir, config) {
137
193
  const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
138
194
  const trimmedProfile = config.profile?.trim();
@@ -151,6 +207,17 @@ export async function writeProjectConfig(rootDir, config) {
151
207
  await fs.writeFile(configPath, `${JSON.stringify(ordered, null, 2)}\n`, 'utf8');
152
208
  return configPath;
153
209
  }
210
+ /**
211
+ * Writes an unlinked `.cdpn.json` containing only the normalized `info` section
212
+ * (used by `cdpn delete --keep-info` so a later first-time push reuses the Pen metadata).
213
+ */
214
+ export async function writeUnlinkedProjectInfo(rootDir, info) {
215
+ const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
216
+ const normalizedInfo = normalizePartialPenInfo(info);
217
+ const payload = { info: normalizedInfo };
218
+ await fs.writeFile(configPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
219
+ return configPath;
220
+ }
154
221
  function sortRecordKeys(record) {
155
222
  const sorted = {};
156
223
  for (const key of Object.keys(record).sort()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codepen-commander",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Sync local folders with CodePen 2.0 Pens via the CodePen API v2",
5
5
  "license": "MIT",
6
6
  "type": "module",