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,166 @@
1
+ import path from 'node:path';
2
+ import { CLASSIC_CONFIG_FILENAME, CODEPEN_DIR, PEN_CONFIG_FILENAME, } from '../constants.js';
3
+ import { CliError } from '../errors.js';
4
+ import { fileExistsRegular } from '../utils/fs-safe.js';
5
+ import { hasControlChars, isPlainObject } from '../utils/strings.js';
6
+ export { CLASSIC_CONFIG_FILENAME, CODEPEN_DIR, PEN_CONFIG_FILENAME };
7
+ export const REQUIRED_PEN_BLOCKS = ['validate-1', 'fingerprint-1'];
8
+ export const INIT_BLOCK_CHOICES = Object.freeze([
9
+ {
10
+ id: 'validate',
11
+ blockName: 'validate-1',
12
+ label: 'validate',
13
+ description: 'HTML/CSS/JS validation · required',
14
+ locked: true,
15
+ },
16
+ {
17
+ id: 'fingerprint',
18
+ blockName: 'fingerprint-1',
19
+ label: 'fingerprint',
20
+ description: 'asset fingerprinting · required',
21
+ locked: true,
22
+ },
23
+ {
24
+ id: 'packages',
25
+ blockName: 'packages-1',
26
+ label: 'packages',
27
+ description: 'npm packages via package.json importmap',
28
+ locked: false,
29
+ },
30
+ {
31
+ id: 'classic',
32
+ blockName: 'classic-1',
33
+ label: 'classic',
34
+ description: 'CodePen Classic mode (.pen.html + classic.config.json)',
35
+ locked: false,
36
+ },
37
+ ]);
38
+ const KNOWN_BLOCK_MAP = new Map(INIT_BLOCK_CHOICES.map((c) => [c.id, c.blockName]));
39
+ const EXPLICIT_BLOCK_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,60}-\d+$/;
40
+ const SHORT_BLOCK_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,60}$/;
41
+ export function normalizeBlockType(rawName) {
42
+ return String(rawName).trim().toLowerCase().replace(/-\d+$/, '');
43
+ }
44
+ /**
45
+ * Normalizes a single user-supplied block identifier (e.g. `"packages"`, `"classic"`,
46
+ * `"packages-1"`, `"markdown-it-14"`) into a CodePen 2.0 block name.
47
+ */
48
+ export function normalizeBlockIdentifier(raw) {
49
+ const cleaned = raw.trim().toLowerCase();
50
+ if (!cleaned || hasControlChars(cleaned)) {
51
+ throw new CliError(400, `Invalid block name "${raw}".`);
52
+ }
53
+ const known = KNOWN_BLOCK_MAP.get(cleaned);
54
+ if (known)
55
+ return known;
56
+ if (EXPLICIT_BLOCK_NAME_PATTERN.test(cleaned)) {
57
+ return cleaned;
58
+ }
59
+ if (SHORT_BLOCK_NAME_PATTERN.test(cleaned)) {
60
+ return `${cleaned}-1`;
61
+ }
62
+ throw new CliError(400, `Invalid block name "${raw}". Use lowercase letters, numbers, and hyphens (e.g. packages, classic).`);
63
+ }
64
+ /**
65
+ * Normalizes a list of block identifiers, deduplicating, sorting alphabetically,
66
+ * and always guaranteeing `validate-1` and `fingerprint-1` are included.
67
+ */
68
+ export function normalizePenBlocksList(rawBlocks) {
69
+ const byType = new Map();
70
+ for (const required of REQUIRED_PEN_BLOCKS) {
71
+ byType.set(normalizeBlockType(required), required);
72
+ }
73
+ for (const raw of rawBlocks) {
74
+ const trimmed = raw.trim();
75
+ if (!trimmed || trimmed.toLowerCase() === 'none')
76
+ continue;
77
+ const normalized = normalizeBlockIdentifier(trimmed);
78
+ const blockType = normalizeBlockType(normalized);
79
+ if (blockType === 'validate') {
80
+ byType.set('validate', 'validate-1');
81
+ }
82
+ else if (blockType === 'fingerprint') {
83
+ byType.set('fingerprint', 'fingerprint-1');
84
+ }
85
+ else {
86
+ byType.set(blockType, normalized);
87
+ }
88
+ }
89
+ return [...byType.values()].sort((a, b) => a.localeCompare(b));
90
+ }
91
+ /**
92
+ * Parses a comma-separated `--blocks` CLI flag into normalized CodePen 2.0 block names,
93
+ * always including `validate-1` and `fingerprint-1`.
94
+ */
95
+ export function parseBlocksOption(raw) {
96
+ const parts = raw
97
+ .split(',')
98
+ .map((p) => p.trim())
99
+ .filter(Boolean);
100
+ return normalizePenBlocksList(parts);
101
+ }
102
+ /**
103
+ * Builds a `.codepen/pen.config.json` object for the given block names, optionally
104
+ * merging onto an existing `pen.config.json` object.
105
+ */
106
+ export function buildPenConfigObject(rawBlocks, options = {}) {
107
+ const blockNames = normalizePenBlocksList(rawBlocks);
108
+ const nowIso = options.nowIso ?? new Date().toISOString();
109
+ const existingBlocks = options.existing && isPlainObject(options.existing.blocks) ? options.existing.blocks : {};
110
+ const blocks = {};
111
+ if (options.existing) {
112
+ for (const [key, entry] of Object.entries(existingBlocks)) {
113
+ if (!isPlainObject(entry))
114
+ continue;
115
+ const name = typeof entry.name === 'string' && entry.name.trim() ? entry.name.trim() : key;
116
+ const createdAt = typeof entry.createdAt === 'string' && entry.createdAt.trim() ? entry.createdAt.trim() : nowIso;
117
+ const version = typeof entry.version === 'string' && entry.version.trim() ? entry.version.trim() : 'latest';
118
+ blocks[key] = {
119
+ createdAt,
120
+ disabled: Boolean(entry.disabled),
121
+ name,
122
+ version,
123
+ };
124
+ }
125
+ }
126
+ for (const name of blockNames) {
127
+ const prev = blocks[name];
128
+ blocks[name] = {
129
+ createdAt: prev?.createdAt ?? nowIso,
130
+ disabled: false,
131
+ name,
132
+ version: prev?.version ?? 'latest',
133
+ };
134
+ }
135
+ const sortedBlocks = {};
136
+ for (const key of Object.keys(blocks).sort((a, b) => a.localeCompare(b))) {
137
+ sortedBlocks[key] = blocks[key];
138
+ }
139
+ return { blocks: sortedBlocks };
140
+ }
141
+ export function buildStarterClassicConfigFromPaths(filePaths) {
142
+ const pathSet = new Set(filePaths.map((p) => (p.startsWith('/') ? p : `/${p}`)));
143
+ return {
144
+ head: '<meta name="viewport" content="width=device-width" />',
145
+ htmlClasses: '',
146
+ scripts: pathSet.has('/script.js') ? ['/script.js'] : [],
147
+ styles: pathSet.has('/style.css') ? ['/style.css'] : [],
148
+ };
149
+ }
150
+ /**
151
+ * Generates a starter `.codepen/classic.config.json` payload, auto-linking `/style.css`
152
+ * and `/script.js` when those files exist in `penDir`.
153
+ */
154
+ export async function buildStarterClassicConfig(penDir) {
155
+ const resolved = path.resolve(penDir);
156
+ const [hasStyleCss, hasScriptJs] = await Promise.all([
157
+ fileExistsRegular(path.join(resolved, 'style.css')),
158
+ fileExistsRegular(path.join(resolved, 'script.js')),
159
+ ]);
160
+ return {
161
+ head: '<meta name="viewport" content="width=device-width" />',
162
+ htmlClasses: '',
163
+ scripts: hasScriptJs ? ['/script.js'] : [],
164
+ styles: hasStyleCss ? ['/style.css'] : [],
165
+ };
166
+ }
package/config/project.js CHANGED
@@ -1,20 +1,99 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { normalizePartialPenInfo, parsePenInfoInput } from '../sync/info.js';
4
- import { CliError } from '../utils/json.js';
5
- export const PROJECT_CONFIG_FILENAME = '.cdpn.json';
3
+ import { PROJECT_CONFIG_FILENAME } from '../constants.js';
4
+ import { CliError } from '../errors.js';
5
+ import { parseAccessValue } from '../utils/cli-options.js';
6
+ import { isPlainObject } from '../utils/strings.js';
7
+ export { PROJECT_CONFIG_FILENAME };
6
8
  /**
7
- * Walks upward from `startDir` looking for `.cdpn.json` (similar to how git locates `.git`).
9
+ * Orders defined keys of a (potentially partial) `PenInfo` object consistently for writing `.cdpn.json`.
8
10
  */
9
- export async function findProject(startDir = process.cwd()) {
11
+ export function normalizePartialPenInfo(info) {
12
+ const ordered = {};
13
+ if (info.title !== undefined)
14
+ ordered.title = info.title;
15
+ if (info.description !== undefined)
16
+ ordered.description = info.description;
17
+ if (info.tags !== undefined)
18
+ ordered.tags = [...info.tags];
19
+ if (info.access !== undefined)
20
+ ordered.access = info.access;
21
+ if (info.template !== undefined)
22
+ ordered.template = info.template;
23
+ return ordered;
24
+ }
25
+ /**
26
+ * Validates and normalizes the optional `info` object parsed from `.cdpn.json`.
27
+ * Returns `undefined` when absent (backwards-compatible with older `.cdpn.json` files).
28
+ */
29
+ export function parsePenInfoInput(raw, configLabel = PROJECT_CONFIG_FILENAME) {
30
+ if (raw === undefined || raw === null) {
31
+ return undefined;
32
+ }
33
+ if (!isPlainObject(raw)) {
34
+ throw new CliError(400, `Invalid ${configLabel}: "info" must be a JSON object.`);
35
+ }
36
+ if (Object.hasOwn(raw, 'password') && raw.password !== undefined) {
37
+ throw new CliError(400, `Invalid ${configLabel}: "info.password" is not supported (passwords must not be stored in ${configLabel}).\n` +
38
+ 'Use `cdpn privacy protected` or `cdpn info --access Protected --password <password>` instead.');
39
+ }
40
+ const parsed = {};
41
+ if (raw.title !== undefined) {
42
+ if (typeof raw.title !== 'string') {
43
+ throw new CliError(400, `Invalid ${configLabel}: "info.title" must be a string.`);
44
+ }
45
+ parsed.title = raw.title;
46
+ }
47
+ if (raw.description !== undefined) {
48
+ if (typeof raw.description !== 'string') {
49
+ throw new CliError(400, `Invalid ${configLabel}: "info.description" must be a string.`);
50
+ }
51
+ parsed.description = raw.description;
52
+ }
53
+ if (raw.tags !== undefined) {
54
+ if (!Array.isArray(raw.tags) || !raw.tags.every((t) => typeof t === 'string')) {
55
+ throw new CliError(400, `Invalid ${configLabel}: "info.tags" must be an array of strings.`);
56
+ }
57
+ parsed.tags = raw.tags.map((t) => t.trim()).filter(Boolean);
58
+ }
59
+ if (raw.access !== undefined) {
60
+ if (typeof raw.access !== 'string') {
61
+ throw new CliError(400, `Invalid ${configLabel}: "info.access" must be one of Public, Private, Protected, or Collaborators.`);
62
+ }
63
+ const normalizedAccess = parseAccessValue(raw.access);
64
+ if (!normalizedAccess) {
65
+ throw new CliError(400, `Invalid ${configLabel}: "info.access" value "${raw.access}" is invalid. Use: Public, Private, Protected, or Collaborators.`);
66
+ }
67
+ parsed.access = normalizedAccess;
68
+ }
69
+ if (raw.template !== undefined) {
70
+ if (typeof raw.template !== 'boolean') {
71
+ throw new CliError(400, `Invalid ${configLabel}: "info.template" must be a boolean.`);
72
+ }
73
+ parsed.template = raw.template;
74
+ }
75
+ return parsed;
76
+ }
77
+ export function createUnlinkedProjectError(rootDir) {
78
+ return new CliError(404, `${PROJECT_CONFIG_FILENAME} in ${rootDir} only contains Pen info and is not linked to an online Pen yet.\n` +
79
+ 'Run `cdpn push` to push this folder as a new Pen on CodePen.');
80
+ }
81
+ /**
82
+ * Walks upward from `startDir` looking for the nearest `.cdpn.json` (linked or unlinked info-only).
83
+ * Stops at the first `.cdpn.json` encountered so nested unlinked folders never leak to a parent Pen.
84
+ */
85
+ export async function findNearestConfig(startDir = process.cwd()) {
10
86
  let current = path.resolve(startDir);
11
87
  for (;;) {
12
88
  const configPath = path.join(current, PROJECT_CONFIG_FILENAME);
13
89
  try {
14
90
  const stat = await fs.lstat(configPath);
15
91
  if (stat.isFile()) {
16
- const config = await readProjectConfig(current);
17
- return { rootDir: current, configPath, config };
92
+ const parsed = await readProjectConfigFile(current);
93
+ if (parsed.linked) {
94
+ return { linked: true, rootDir: current, configPath, config: parsed.config };
95
+ }
96
+ return { linked: false, rootDir: current, configPath, config: parsed.config };
18
97
  }
19
98
  }
20
99
  catch (error) {
@@ -29,15 +108,37 @@ export async function findProject(startDir = process.cwd()) {
29
108
  current = parent;
30
109
  }
31
110
  }
111
+ /**
112
+ * Walks upward from `startDir` looking for a linked `.cdpn.json` (similar to how git locates `.git`).
113
+ * Returns `null` if no `.cdpn.json` is found or if the nearest `.cdpn.json` is unlinked (info-only).
114
+ */
115
+ export async function findProject(startDir = process.cwd()) {
116
+ const nearest = await findNearestConfig(startDir);
117
+ if (!nearest || !nearest.linked) {
118
+ return null;
119
+ }
120
+ return {
121
+ rootDir: nearest.rootDir,
122
+ configPath: nearest.configPath,
123
+ config: nearest.config,
124
+ };
125
+ }
32
126
  export async function requireProject(startDir = process.cwd()) {
33
- const project = await findProject(startDir);
34
- if (!project) {
127
+ const nearest = await findNearestConfig(startDir);
128
+ if (!nearest) {
35
129
  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
130
  }
37
- return project;
131
+ if (!nearest.linked) {
132
+ throw createUnlinkedProjectError(nearest.rootDir);
133
+ }
134
+ return {
135
+ rootDir: nearest.rootDir,
136
+ configPath: nearest.configPath,
137
+ config: nearest.config,
138
+ };
38
139
  }
39
140
  /**
40
- * Requires `.cdpn.json` to exist directly inside `dir` (does NOT walk upward to parent directories).
141
+ * Requires a linked `.cdpn.json` to exist directly inside `dir` (does NOT walk upward to parent directories).
41
142
  */
42
143
  export async function requireProjectInDir(dir = process.cwd()) {
43
144
  const resolvedDir = path.resolve(dir);
@@ -72,8 +173,13 @@ export async function hasProjectConfigInDir(dir) {
72
173
  throw error;
73
174
  }
74
175
  }
75
- export async function readProjectConfig(rootDir) {
76
- const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
176
+ /**
177
+ * Reads and validates `.cdpn.json` from `rootDir`, supporting both linked Pen configs
178
+ * and unlinked info-only configs (e.g. retained via `cdpn delete --cleanup` or `cdpn init`).
179
+ */
180
+ export async function readProjectConfigFile(rootDir) {
181
+ const resolvedDir = path.resolve(rootDir);
182
+ const configPath = path.join(resolvedDir, PROJECT_CONFIG_FILENAME);
77
183
  const raw = await fs.readFile(configPath, 'utf8');
78
184
  let parsed;
79
185
  try {
@@ -82,57 +188,76 @@ export async function readProjectConfig(rootDir) {
82
188
  catch {
83
189
  throw new CliError(400, `Invalid JSON in ${configPath}`);
84
190
  }
85
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
191
+ if (!isPlainObject(parsed)) {
86
192
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: expected a JSON object.`);
87
193
  }
88
- const record = parsed;
89
- if (typeof record.pen_id !== 'string' || !record.pen_id.trim()) {
194
+ // Unlinked info-only `.cdpn.json`: no pen_id or url, only `info`
195
+ if (parsed.pen_id === undefined && parsed.url === undefined && parsed.info !== undefined) {
196
+ if (parsed.info === null) {
197
+ throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: "info" must be a JSON object.`);
198
+ }
199
+ const info = parsePenInfoInput(parsed.info, PROJECT_CONFIG_FILENAME);
200
+ return {
201
+ linked: false,
202
+ config: { info },
203
+ };
204
+ }
205
+ if (typeof parsed.pen_id !== 'string' || !parsed.pen_id.trim()) {
90
206
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "pen_id" string.`);
91
207
  }
92
- if (typeof record.url !== 'string' || !record.url.trim()) {
208
+ if (typeof parsed.url !== 'string' || !parsed.url.trim()) {
93
209
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "url" string.`);
94
210
  }
95
- const profile = typeof record.profile === 'string' && record.profile.trim()
96
- ? record.profile.trim()
211
+ const profile = typeof parsed.profile === 'string' && parsed.profile.trim()
212
+ ? parsed.profile.trim()
97
213
  : undefined;
98
- const lastSynced = record.last_synced_version_id === null || typeof record.last_synced_version_id === 'string'
99
- ? record.last_synced_version_id
214
+ const lastSynced = parsed.last_synced_version_id === null || typeof parsed.last_synced_version_id === 'string'
215
+ ? parsed.last_synced_version_id
100
216
  : null;
101
- const lastSyncedInfoHash = typeof record.last_synced_info_hash === 'string' && record.last_synced_info_hash.trim()
102
- ? record.last_synced_info_hash.trim()
217
+ const lastSyncedInfoHash = typeof parsed.last_synced_info_hash === 'string' && parsed.last_synced_info_hash.trim()
218
+ ? parsed.last_synced_info_hash.trim()
103
219
  : undefined;
104
- const editor = record.editor === 'V2' || record.editor === 'Classic' ? record.editor : undefined;
105
- const info = parsePenInfoInput(record.info, PROJECT_CONFIG_FILENAME);
220
+ const editor = parsed.editor === 'V2' || parsed.editor === 'Classic' ? parsed.editor : undefined;
221
+ const info = parsePenInfoInput(parsed.info, PROJECT_CONFIG_FILENAME);
106
222
  let files;
107
- if (record.files && typeof record.files === 'object' && !Array.isArray(record.files)) {
223
+ if (isPlainObject(parsed.files)) {
108
224
  files = {};
109
- for (const [filePath, entry] of Object.entries(record.files)) {
110
- if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
111
- const e = entry;
112
- if (typeof e.id === 'string' &&
113
- typeof e.content_hash === 'string' &&
114
- typeof e.local_sha256 === 'string') {
225
+ for (const [filePath, entry] of Object.entries(parsed.files)) {
226
+ if (isPlainObject(entry)) {
227
+ if (typeof entry.id === 'string' &&
228
+ typeof entry.content_hash === 'string' &&
229
+ typeof entry.local_sha256 === 'string') {
115
230
  files[filePath] = {
116
- id: e.id,
117
- content_hash: e.content_hash,
118
- local_sha256: e.local_sha256,
119
- is_binary: Boolean(e.is_binary),
231
+ id: entry.id,
232
+ content_hash: entry.content_hash,
233
+ local_sha256: entry.local_sha256,
234
+ is_binary: Boolean(entry.is_binary),
120
235
  };
121
236
  }
122
237
  }
123
238
  }
124
239
  }
125
240
  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 } : {}),
241
+ linked: true,
242
+ config: {
243
+ url: parsed.url.trim(),
244
+ pen_id: parsed.pen_id.trim(),
245
+ ...(profile ? { profile } : {}),
246
+ last_synced_version_id: lastSynced,
247
+ ...(lastSyncedInfoHash ? { last_synced_info_hash: lastSyncedInfoHash } : {}),
248
+ ...(editor ? { editor } : {}),
249
+ ...(info !== undefined ? { info } : {}),
250
+ ...(files ? { files } : {}),
251
+ },
134
252
  };
135
253
  }
254
+ export async function readProjectConfig(rootDir) {
255
+ const parsed = await readProjectConfigFile(rootDir);
256
+ if (!parsed.linked) {
257
+ throw createUnlinkedProjectError(path.resolve(rootDir));
258
+ }
259
+ return parsed.config;
260
+ }
136
261
  export async function writeProjectConfig(rootDir, config) {
137
262
  const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
138
263
  const trimmedProfile = config.profile?.trim();
@@ -151,6 +276,16 @@ export async function writeProjectConfig(rootDir, config) {
151
276
  await fs.writeFile(configPath, `${JSON.stringify(ordered, null, 2)}\n`, 'utf8');
152
277
  return configPath;
153
278
  }
279
+ /**
280
+ * Writes an unlinked `.cdpn.json` containing only the normalized `info` section.
281
+ */
282
+ export async function writeUnlinkedProjectInfo(rootDir, info) {
283
+ const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
284
+ const normalizedInfo = normalizePartialPenInfo(info);
285
+ const payload = { info: normalizedInfo };
286
+ await fs.writeFile(configPath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
287
+ return configPath;
288
+ }
154
289
  function sortRecordKeys(record) {
155
290
  const sorted = {};
156
291
  for (const key of Object.keys(record).sort()) {
@@ -178,199 +313,3 @@ export function buildSyncedFileMap(remoteFiles, localSha256ByPath) {
178
313
  }
179
314
  return sortRecordKeys(map);
180
315
  }
181
- const PEN_ID_PATTERN = /^[A-Za-z0-9_-]{3,64}$/;
182
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
183
- const PEN_VIEW_SEGMENTS = new Set(['pen', 'full', 'details', 'debug', 'live', 'embed']);
184
- const CLASSIC_PEN_VIEW_SEGMENTS = new Set([...PEN_VIEW_SEGMENTS, 'editor']);
185
- /**
186
- * Extracts a Pen's cpid or hashid from a CodePen URL, when present in the URL path or host.
187
- *
188
- * Examples:
189
- * - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
190
- * - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08/89bb` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
191
- * - `https://codepen.io/bramus/pen/abcde` -> `abcde`
192
- * - `https://codepen.io/team/username/pen/abcde` -> `abcde`
193
- * - `https://codepen.io/bramus/embed/preview/abcde` -> `abcde`
194
- * - `https://01a11c78-9eba-777b-98a7-fa51e8b7cb08.codepenusercontent.com/index.html` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
195
- */
196
- export function extractPenIdFromUrl(rawUrl) {
197
- let parsed;
198
- try {
199
- parsed = new URL(rawUrl.trim());
200
- }
201
- catch {
202
- return null;
203
- }
204
- const host = parsed.hostname.toLowerCase();
205
- if (host === 'codepen.io' || host === 'www.codepen.io') {
206
- const segments = parsed.pathname.split('/').filter(Boolean);
207
- if (segments.length < 2) {
208
- return null;
209
- }
210
- let idx = 0;
211
- const isV2EditorPath = segments[0]?.toLowerCase() === 'editor';
212
- const viewSegments = isV2EditorPath ? PEN_VIEW_SEGMENTS : CLASSIC_PEN_VIEW_SEGMENTS;
213
- if (isV2EditorPath) {
214
- idx++;
215
- if (segments.length === 2 && segments[1] && UUID_PATTERN.test(segments[1])) {
216
- return segments[1];
217
- }
218
- }
219
- if (segments[idx]?.toLowerCase() === 'team') {
220
- // Skip `team/<team-slug>`
221
- idx += 2;
222
- }
223
- else if (segments[idx] && !viewSegments.has(segments[idx].toLowerCase())) {
224
- // Skip `<username>`
225
- idx += 1;
226
- }
227
- const view = segments[idx]?.toLowerCase();
228
- if (!view || !viewSegments.has(view)) {
229
- return null;
230
- }
231
- idx++;
232
- // Handle `/embed/preview/<id>`
233
- if (view === 'embed' && segments[idx]?.toLowerCase() === 'preview') {
234
- idx++;
235
- }
236
- const idCandidate = segments[idx]?.trim();
237
- if (idCandidate && PEN_ID_PATTERN.test(idCandidate)) {
238
- return idCandidate;
239
- }
240
- return null;
241
- }
242
- // Content or preview subdomains carrying a UUID cpid (e.g. `<cpid>.codepenusercontent.com`)
243
- const firstLabel = host.split('.')[0];
244
- if (firstLabel &&
245
- UUID_PATTERN.test(firstLabel) &&
246
- (host.endsWith('.codepen.dev') ||
247
- host.endsWith('.codepen.app') ||
248
- host.endsWith('.codepenusercontent.com'))) {
249
- return firstLabel;
250
- }
251
- return null;
252
- }
253
- /**
254
- * Validates and normalizes a Pen identifier or CodePen URL passed by the user.
255
- * Extracts the Pen's cpid or hashid from CodePen URLs when present (CodePen REST API v2
256
- * `/v2/pens/:id` reliably resolves raw IDs and can return 404 on `%2F`-encoded editor URLs),
257
- * while preserving `originalUrl` for owner matching and `.cdpn.json`.
258
- */
259
- export function normalizePenReference(rawInput) {
260
- const trimmed = rawInput.trim();
261
- if (!trimmed) {
262
- throw new CliError(400, 'Pen URL or ID cannot be empty.');
263
- }
264
- if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
265
- let parsed;
266
- try {
267
- parsed = new URL(trimmed);
268
- }
269
- catch {
270
- throw new CliError(400, `Invalid URL: ${trimmed}`);
271
- }
272
- const host = parsed.hostname.toLowerCase();
273
- const isCodePenHost = host === 'codepen.io' ||
274
- host.endsWith('.codepen.io') ||
275
- host.endsWith('.codepen.dev') ||
276
- host.endsWith('.codepen.app') ||
277
- host.endsWith('.codepenusercontent.com');
278
- if (!isCodePenHost) {
279
- throw new CliError(400, `Expected a CodePen URL (codepen.io / codepen.dev / codepen.app), got: ${host}`);
280
- }
281
- const extractedId = extractPenIdFromUrl(trimmed);
282
- return {
283
- apiIdentifier: extractedId ?? trimmed,
284
- originalUrl: trimmed,
285
- };
286
- }
287
- // Raw cpid (UUID) or hashid
288
- if (!PEN_ID_PATTERN.test(trimmed)) {
289
- throw new CliError(400, `Invalid Pen ID: "${trimmed}". Provide a Pen URL, cpid, or hashid.`);
290
- }
291
- return { apiIdentifier: trimmed };
292
- }
293
- /**
294
- * Converts a Pen title into a safe directory-name slug, or returns null for empty / "Untitled".
295
- */
296
- export function slugifyTitle(rawTitle) {
297
- const title = (rawTitle ?? '').trim();
298
- if (!title || title.toLowerCase() === 'untitled') {
299
- return null;
300
- }
301
- const slug = title
302
- .normalize('NFKD')
303
- .replace(/[\u0300-\u036f]/g, '')
304
- .toLowerCase()
305
- .replace(/[^a-z0-9]+/g, '-')
306
- .replace(/^-+|-+$/g, '')
307
- .slice(0, 64);
308
- if (!slug || slug === '.' || slug === '..') {
309
- return null;
310
- }
311
- return slug;
312
- }
313
- /**
314
- * Produces a safe default local folder name for a Pen based on its title or ID.
315
- */
316
- export function suggestFolderName(pen) {
317
- return slugifyTitle(pen.title) ?? pen.id.replace(/[^A-Za-z0-9_-]/g, '-');
318
- }
319
- const RESERVED_CODEPEN_SEGMENTS = new Set([
320
- 'pen',
321
- 'editor',
322
- 'full',
323
- 'details',
324
- 'debug',
325
- 'live',
326
- 'embed',
327
- 'settings',
328
- 'trending',
329
- 'following',
330
- 'your-work',
331
- 'collections',
332
- 'project',
333
- 'projects',
334
- 'api',
335
- ]);
336
- /**
337
- * Extracts the CodePen username or team slug from a `codepen.io` URL, if present.
338
- * Supports CodePen 2.0 editor URLs (`https://codepen.io/editor/bramus/pen/<cpid>`),
339
- * Classic personal URLs (`https://codepen.io/bramus/pen/<slug>`), and team URLs
340
- * (`https://codepen.io/team/username/pen/...`, `https://codepen.io/editor/team/username/pen/...`).
341
- */
342
- export function extractCodePenOwnerFromUrl(rawUrl) {
343
- let parsed;
344
- try {
345
- parsed = new URL(rawUrl.trim());
346
- }
347
- catch {
348
- return null;
349
- }
350
- const host = parsed.hostname.toLowerCase();
351
- if (host !== 'codepen.io' && host !== 'www.codepen.io') {
352
- return null;
353
- }
354
- const segments = parsed.pathname.split('/').filter(Boolean);
355
- let idx = 0;
356
- // CodePen 2.0 editor URLs place `/editor/` before the username/team slug
357
- if (segments[idx]?.toLowerCase() === 'editor') {
358
- idx++;
359
- }
360
- // Team URLs may include a `/team/` prefix before the team slug
361
- if (segments[idx]?.toLowerCase() === 'team') {
362
- idx++;
363
- }
364
- // Require at least `<owner>/<view-or-resource>` remaining (e.g. `bramus/pen/<id>`)
365
- if (segments.length - idx < 2) {
366
- return null;
367
- }
368
- const candidate = segments[idx]?.trim();
369
- if (!candidate || RESERVED_CODEPEN_SEGMENTS.has(candidate.toLowerCase())) {
370
- return null;
371
- }
372
- if (/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(candidate)) {
373
- return candidate;
374
- }
375
- return null;
376
- }