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
@@ -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,9 +1,80 @@
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';
6
- function createUnlinkedProjectError(rootDir) {
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 };
8
+ /**
9
+ * Orders defined keys of a (potentially partial) `PenInfo` object consistently for writing `.cdpn.json`.
10
+ */
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) {
7
78
  return new CliError(404, `${PROJECT_CONFIG_FILENAME} in ${rootDir} only contains Pen info and is not linked to an online Pen yet.\n` +
8
79
  'Run `cdpn push` to push this folder as a new Pen on CodePen.');
9
80
  }
@@ -104,7 +175,7 @@ export async function hasProjectConfigInDir(dir) {
104
175
  }
105
176
  /**
106
177
  * 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`).
178
+ * and unlinked info-only configs (e.g. retained via `cdpn delete --cleanup` or `cdpn init`).
108
179
  */
109
180
  export async function readProjectConfigFile(rootDir) {
110
181
  const resolvedDir = path.resolve(rootDir);
@@ -117,52 +188,50 @@ export async function readProjectConfigFile(rootDir) {
117
188
  catch {
118
189
  throw new CliError(400, `Invalid JSON in ${configPath}`);
119
190
  }
120
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
191
+ if (!isPlainObject(parsed)) {
121
192
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: expected a JSON object.`);
122
193
  }
123
- const record = parsed;
124
194
  // 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) {
195
+ if (parsed.pen_id === undefined && parsed.url === undefined && parsed.info !== undefined) {
196
+ if (parsed.info === null) {
127
197
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: "info" must be a JSON object.`);
128
198
  }
129
- const info = parsePenInfoInput(record.info, PROJECT_CONFIG_FILENAME);
199
+ const info = parsePenInfoInput(parsed.info, PROJECT_CONFIG_FILENAME);
130
200
  return {
131
201
  linked: false,
132
202
  config: { info },
133
203
  };
134
204
  }
135
- if (typeof record.pen_id !== 'string' || !record.pen_id.trim()) {
205
+ if (typeof parsed.pen_id !== 'string' || !parsed.pen_id.trim()) {
136
206
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "pen_id" string.`);
137
207
  }
138
- if (typeof record.url !== 'string' || !record.url.trim()) {
208
+ if (typeof parsed.url !== 'string' || !parsed.url.trim()) {
139
209
  throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "url" string.`);
140
210
  }
141
- const profile = typeof record.profile === 'string' && record.profile.trim()
142
- ? record.profile.trim()
211
+ const profile = typeof parsed.profile === 'string' && parsed.profile.trim()
212
+ ? parsed.profile.trim()
143
213
  : undefined;
144
- const lastSynced = record.last_synced_version_id === null || typeof record.last_synced_version_id === 'string'
145
- ? 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
146
216
  : null;
147
- const lastSyncedInfoHash = typeof record.last_synced_info_hash === 'string' && record.last_synced_info_hash.trim()
148
- ? 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()
149
219
  : undefined;
150
- const editor = record.editor === 'V2' || record.editor === 'Classic' ? record.editor : undefined;
151
- 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);
152
222
  let files;
153
- if (record.files && typeof record.files === 'object' && !Array.isArray(record.files)) {
223
+ if (isPlainObject(parsed.files)) {
154
224
  files = {};
155
- for (const [filePath, entry] of Object.entries(record.files)) {
156
- if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
157
- const e = entry;
158
- if (typeof e.id === 'string' &&
159
- typeof e.content_hash === 'string' &&
160
- 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') {
161
230
  files[filePath] = {
162
- id: e.id,
163
- content_hash: e.content_hash,
164
- local_sha256: e.local_sha256,
165
- 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),
166
235
  };
167
236
  }
168
237
  }
@@ -171,8 +240,8 @@ export async function readProjectConfigFile(rootDir) {
171
240
  return {
172
241
  linked: true,
173
242
  config: {
174
- url: record.url.trim(),
175
- pen_id: record.pen_id.trim(),
243
+ url: parsed.url.trim(),
244
+ pen_id: parsed.pen_id.trim(),
176
245
  ...(profile ? { profile } : {}),
177
246
  last_synced_version_id: lastSynced,
178
247
  ...(lastSyncedInfoHash ? { last_synced_info_hash: lastSyncedInfoHash } : {}),
@@ -208,8 +277,7 @@ export async function writeProjectConfig(rootDir, config) {
208
277
  return configPath;
209
278
  }
210
279
  /**
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).
280
+ * Writes an unlinked `.cdpn.json` containing only the normalized `info` section.
213
281
  */
214
282
  export async function writeUnlinkedProjectInfo(rootDir, info) {
215
283
  const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
@@ -245,199 +313,3 @@ export function buildSyncedFileMap(remoteFiles, localSha256ByPath) {
245
313
  }
246
314
  return sortRecordKeys(map);
247
315
  }
248
- const PEN_ID_PATTERN = /^[A-Za-z0-9_-]{3,64}$/;
249
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
250
- const PEN_VIEW_SEGMENTS = new Set(['pen', 'full', 'details', 'debug', 'live', 'embed']);
251
- const CLASSIC_PEN_VIEW_SEGMENTS = new Set([...PEN_VIEW_SEGMENTS, 'editor']);
252
- /**
253
- * Extracts a Pen's cpid or hashid from a CodePen URL, when present in the URL path or host.
254
- *
255
- * Examples:
256
- * - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
257
- * - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08/89bb` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
258
- * - `https://codepen.io/bramus/pen/abcde` -> `abcde`
259
- * - `https://codepen.io/team/username/pen/abcde` -> `abcde`
260
- * - `https://codepen.io/bramus/embed/preview/abcde` -> `abcde`
261
- * - `https://01a11c78-9eba-777b-98a7-fa51e8b7cb08.codepenusercontent.com/index.html` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
262
- */
263
- export function extractPenIdFromUrl(rawUrl) {
264
- let parsed;
265
- try {
266
- parsed = new URL(rawUrl.trim());
267
- }
268
- catch {
269
- return null;
270
- }
271
- const host = parsed.hostname.toLowerCase();
272
- if (host === 'codepen.io' || host === 'www.codepen.io') {
273
- const segments = parsed.pathname.split('/').filter(Boolean);
274
- if (segments.length < 2) {
275
- return null;
276
- }
277
- let idx = 0;
278
- const isV2EditorPath = segments[0]?.toLowerCase() === 'editor';
279
- const viewSegments = isV2EditorPath ? PEN_VIEW_SEGMENTS : CLASSIC_PEN_VIEW_SEGMENTS;
280
- if (isV2EditorPath) {
281
- idx++;
282
- if (segments.length === 2 && segments[1] && UUID_PATTERN.test(segments[1])) {
283
- return segments[1];
284
- }
285
- }
286
- if (segments[idx]?.toLowerCase() === 'team') {
287
- // Skip `team/<team-slug>`
288
- idx += 2;
289
- }
290
- else if (segments[idx] && !viewSegments.has(segments[idx].toLowerCase())) {
291
- // Skip `<username>`
292
- idx += 1;
293
- }
294
- const view = segments[idx]?.toLowerCase();
295
- if (!view || !viewSegments.has(view)) {
296
- return null;
297
- }
298
- idx++;
299
- // Handle `/embed/preview/<id>`
300
- if (view === 'embed' && segments[idx]?.toLowerCase() === 'preview') {
301
- idx++;
302
- }
303
- const idCandidate = segments[idx]?.trim();
304
- if (idCandidate && PEN_ID_PATTERN.test(idCandidate)) {
305
- return idCandidate;
306
- }
307
- return null;
308
- }
309
- // Content or preview subdomains carrying a UUID cpid (e.g. `<cpid>.codepenusercontent.com`)
310
- const firstLabel = host.split('.')[0];
311
- if (firstLabel &&
312
- UUID_PATTERN.test(firstLabel) &&
313
- (host.endsWith('.codepen.dev') ||
314
- host.endsWith('.codepen.app') ||
315
- host.endsWith('.codepenusercontent.com'))) {
316
- return firstLabel;
317
- }
318
- return null;
319
- }
320
- /**
321
- * Validates and normalizes a Pen identifier or CodePen URL passed by the user.
322
- * Extracts the Pen's cpid or hashid from CodePen URLs when present (CodePen REST API v2
323
- * `/v2/pens/:id` reliably resolves raw IDs and can return 404 on `%2F`-encoded editor URLs),
324
- * while preserving `originalUrl` for owner matching and `.cdpn.json`.
325
- */
326
- export function normalizePenReference(rawInput) {
327
- const trimmed = rawInput.trim();
328
- if (!trimmed) {
329
- throw new CliError(400, 'Pen URL or ID cannot be empty.');
330
- }
331
- if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
332
- let parsed;
333
- try {
334
- parsed = new URL(trimmed);
335
- }
336
- catch {
337
- throw new CliError(400, `Invalid URL: ${trimmed}`);
338
- }
339
- const host = parsed.hostname.toLowerCase();
340
- const isCodePenHost = host === 'codepen.io' ||
341
- host.endsWith('.codepen.io') ||
342
- host.endsWith('.codepen.dev') ||
343
- host.endsWith('.codepen.app') ||
344
- host.endsWith('.codepenusercontent.com');
345
- if (!isCodePenHost) {
346
- throw new CliError(400, `Expected a CodePen URL (codepen.io / codepen.dev / codepen.app), got: ${host}`);
347
- }
348
- const extractedId = extractPenIdFromUrl(trimmed);
349
- return {
350
- apiIdentifier: extractedId ?? trimmed,
351
- originalUrl: trimmed,
352
- };
353
- }
354
- // Raw cpid (UUID) or hashid
355
- if (!PEN_ID_PATTERN.test(trimmed)) {
356
- throw new CliError(400, `Invalid Pen ID: "${trimmed}". Provide a Pen URL, cpid, or hashid.`);
357
- }
358
- return { apiIdentifier: trimmed };
359
- }
360
- /**
361
- * Converts a Pen title into a safe directory-name slug, or returns null for empty / "Untitled".
362
- */
363
- export function slugifyTitle(rawTitle) {
364
- const title = (rawTitle ?? '').trim();
365
- if (!title || title.toLowerCase() === 'untitled') {
366
- return null;
367
- }
368
- const slug = title
369
- .normalize('NFKD')
370
- .replace(/[\u0300-\u036f]/g, '')
371
- .toLowerCase()
372
- .replace(/[^a-z0-9]+/g, '-')
373
- .replace(/^-+|-+$/g, '')
374
- .slice(0, 64);
375
- if (!slug || slug === '.' || slug === '..') {
376
- return null;
377
- }
378
- return slug;
379
- }
380
- /**
381
- * Produces a safe default local folder name for a Pen based on its title or ID.
382
- */
383
- export function suggestFolderName(pen) {
384
- return slugifyTitle(pen.title) ?? pen.id.replace(/[^A-Za-z0-9_-]/g, '-');
385
- }
386
- const RESERVED_CODEPEN_SEGMENTS = new Set([
387
- 'pen',
388
- 'editor',
389
- 'full',
390
- 'details',
391
- 'debug',
392
- 'live',
393
- 'embed',
394
- 'settings',
395
- 'trending',
396
- 'following',
397
- 'your-work',
398
- 'collections',
399
- 'project',
400
- 'projects',
401
- 'api',
402
- ]);
403
- /**
404
- * Extracts the CodePen username or team slug from a `codepen.io` URL, if present.
405
- * Supports CodePen 2.0 editor URLs (`https://codepen.io/editor/bramus/pen/<cpid>`),
406
- * Classic personal URLs (`https://codepen.io/bramus/pen/<slug>`), and team URLs
407
- * (`https://codepen.io/team/username/pen/...`, `https://codepen.io/editor/team/username/pen/...`).
408
- */
409
- export function extractCodePenOwnerFromUrl(rawUrl) {
410
- let parsed;
411
- try {
412
- parsed = new URL(rawUrl.trim());
413
- }
414
- catch {
415
- return null;
416
- }
417
- const host = parsed.hostname.toLowerCase();
418
- if (host !== 'codepen.io' && host !== 'www.codepen.io') {
419
- return null;
420
- }
421
- const segments = parsed.pathname.split('/').filter(Boolean);
422
- let idx = 0;
423
- // CodePen 2.0 editor URLs place `/editor/` before the username/team slug
424
- if (segments[idx]?.toLowerCase() === 'editor') {
425
- idx++;
426
- }
427
- // Team URLs may include a `/team/` prefix before the team slug
428
- if (segments[idx]?.toLowerCase() === 'team') {
429
- idx++;
430
- }
431
- // Require at least `<owner>/<view-or-resource>` remaining (e.g. `bramus/pen/<id>`)
432
- if (segments.length - idx < 2) {
433
- return null;
434
- }
435
- const candidate = segments[idx]?.trim();
436
- if (!candidate || RESERVED_CODEPEN_SEGMENTS.has(candidate.toLowerCase())) {
437
- return null;
438
- }
439
- if (/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(candidate)) {
440
- return candidate;
441
- }
442
- return null;
443
- }