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
package/commands/new.js CHANGED
@@ -1,50 +1,65 @@
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, slugifyTitle, writeProjectConfig, } from '../config/project.js';
5
- import { isDirectoryNonEmpty } from '../sync/fs.js';
4
+ import { buildPenConfigObject, buildStarterClassicConfigFromPaths, normalizePenBlocksList, parseBlocksOption, } from '../config/pen-blocks.js';
5
+ import { buildSyncedFileMap, writeProjectConfig, } from '../config/project.js';
6
+ import { CLASSIC_CONFIG_FILENAME, CODEPEN_DIR, PEN_CONFIG_FILENAME, } from '../constants.js';
6
7
  import { buildPenInfoConfigFields } from '../sync/info.js';
7
8
  import { syncRemoteFilesToDisk } from '../sync/materialize.js';
9
+ import { assertValidProtectedPassword, assertValidTagCount, parseTagsOption, resolveAccessOrVisibility, } from '../utils/cli-options.js';
8
10
  import { fmt, formatDate, printBuildSummary, shortId } from '../utils/format.js';
9
- import { CliError, printJsonResponse } from '../utils/json.js';
10
- import { isInteractive, promptSecret, promptSelect, promptText, } from '../utils/prompts.js';
11
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
12
- import { normalizeAccess, resolveVisibilityAndPassword } from './create-pen.js';
13
- import { assertEmptyTargetDirectory, fetchPenFilesAsUploadPayload, listAccountTemplates, resolveTemplatePen, } from './scaffold.js';
14
- const NEW_NON_EMPTY_HINT = 'To push an existing local demo folder to CodePen, run `cdpn push` inside that folder, or pass a new folder name (e.g. `cdpn new my-pen`).';
11
+ import { printJsonResponse } from '../utils/json.js';
12
+ import { defaultOutput } from '../utils/output.js';
13
+ import { isInteractive, promptSecret, promptSelect, promptText, } from '../utils/prompts/index.js';
14
+ import { isPlainObject } from '../utils/strings.js';
15
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
16
+ import { resolveVisibilityAndPassword } from '../workflows/create-pen.js';
17
+ import { assertEmptyTargetDirectory, fetchPenFilesAsUploadPayload, listAccountTemplates, resolveTemplatePen, } from '../workflows/scaffold.js';
18
+ const NEW_NON_EMPTY_HINT = 'To convert an existing local demo into a CodePen demo, run `cdpn init` inside that folder — or pass a new folder name (e.g. `cdpn new my-pen`).';
19
+ const PEN_CONFIG_PEN_PATH = `/${CODEPEN_DIR}/${PEN_CONFIG_FILENAME}`;
20
+ const CLASSIC_CONFIG_PEN_PATH = `/${CODEPEN_DIR}/${CLASSIC_CONFIG_FILENAME}`;
21
+ function parseJsonObjectSafe(raw) {
22
+ if (!raw)
23
+ return null;
24
+ try {
25
+ const parsed = JSON.parse(raw);
26
+ return isPlainObject(parsed) ? parsed : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
15
32
  /**
16
33
  * Scaffolds a brand-new CodePen 2.0 Pen strictly from CodePen's built-in default starter
17
34
  * or one of your CodePen Templates, and materializes it into a new/empty local folder
18
35
  * linked with `.cdpn.json`.
19
36
  */
20
- export async function scaffoldNewPen(options = {}) {
37
+ export async function runNewCommand(options = {}) {
38
+ const output = options.output ?? defaultOutput;
21
39
  const cwd = path.resolve(options.cwd ?? process.cwd());
22
40
  const jsonMode = Boolean(options.json);
23
41
  const interactive = (options.interactive ?? isInteractive()) && !jsonMode;
24
42
  const textImpl = options.prompts?.text ?? promptText;
25
43
  const selectImpl = options.prompts?.select ?? promptSelect;
26
44
  const secretImpl = options.prompts?.secret ?? promptSecret;
27
- if (options.tags && options.tags.length > 5) {
28
- throw new CliError(400, 'CodePen allows at most 5 tags per Pen.');
29
- }
30
- // Pre-validate --access and --password before hitting the network
31
- const prevalidatedAccess = normalizeAccess(options.access);
32
- if (prevalidatedAccess === 'Protected' && options.password !== undefined && options.password.length < 8) {
33
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
34
- }
35
- if (prevalidatedAccess === 'Protected' && !options.password && !interactive) {
36
- throw new CliError(400, 'Protected Pens require --password with at least 8 characters.');
37
- }
38
- // If the user passed an explicit folder argument, validate immediately that it is empty/new
39
- let targetDir = null;
40
- let folderDisplay = options.folderArg?.trim() || '';
41
- if (folderDisplay) {
42
- targetDir = path.resolve(cwd, folderDisplay);
43
- await assertEmptyTargetDirectory(targetDir, folderDisplay, {
44
- commandName: 'new',
45
- nonEmptyHint: NEW_NON_EMPTY_HINT,
46
- });
45
+ assertValidTagCount(options.tags);
46
+ // Pre-validate --access / --visibility, --blocks, and --password before hitting the network
47
+ const prevalidatedAccess = resolveAccessOrVisibility(options.access, options.visibility);
48
+ let resolvedBlocks;
49
+ if (options.blocks !== undefined) {
50
+ resolvedBlocks =
51
+ typeof options.blocks === 'string'
52
+ ? parseBlocksOption(options.blocks)
53
+ : normalizePenBlocksList(options.blocks);
47
54
  }
55
+ assertValidProtectedPassword(prevalidatedAccess, options.password, interactive);
56
+ // Validate target directory immediately (defaults to current directory `.` when omitted)
57
+ const folderDisplay = options.folderArg?.trim() || '.';
58
+ const targetDir = path.resolve(cwd, folderDisplay);
59
+ await assertEmptyTargetDirectory(targetDir, folderDisplay, {
60
+ commandName: 'new',
61
+ nonEmptyHint: NEW_NON_EMPTY_HINT,
62
+ });
48
63
  const urlHint = options.template && /^https?:\/\//i.test(options.template.trim())
49
64
  ? options.template.trim()
50
65
  : undefined;
@@ -54,6 +69,7 @@ export async function scaffoldNewPen(options = {}) {
54
69
  urlHint,
55
70
  promptMessage: 'Which CodePen account/profile would you like to scaffold under?',
56
71
  interactive,
72
+ output,
57
73
  env: options.env,
58
74
  homeDir: options.homeDir,
59
75
  selectProfile: selectImpl,
@@ -70,10 +86,10 @@ export async function scaffoldNewPen(options = {}) {
70
86
  };
71
87
  }
72
88
  else if (interactive) {
73
- console.log(fmt.dim('Fetching your CodePen templates…'));
89
+ output.log(fmt.dim('Fetching your CodePen templates…'));
74
90
  const templates = await listAccountTemplates(client, 25);
75
91
  if (templates.length === 0) {
76
- console.log(fmt.dim('No custom CodePen templates found — using CodePen’s default 2.0 starter.\n' +
92
+ output.log(fmt.dim('No custom CodePen templates found — using CodePen’s default 2.0 starter.\n' +
77
93
  'Tip: Mark any Pen as a template on CodePen (or run `cdpn info --template true`) to choose it here.'));
78
94
  selected = { kind: 'default-starter', label: 'CodePen default starter' };
79
95
  }
@@ -109,12 +125,7 @@ export async function scaffoldNewPen(options = {}) {
109
125
  selected = { kind: 'default-starter', label: 'CodePen default starter' };
110
126
  }
111
127
  // 3. Determine Pen title
112
- const cwdIsEmpty = !(await isDirectoryNonEmpty(cwd));
113
- const defaultTitle = targetDir && folderDisplay !== '.'
114
- ? path.basename(targetDir) || 'Untitled'
115
- : cwdIsEmpty
116
- ? path.basename(cwd) || 'Untitled'
117
- : 'Untitled';
128
+ const defaultTitle = path.basename(targetDir) || 'Untitled';
118
129
  let title = options.title?.trim();
119
130
  if (!title) {
120
131
  if (interactive) {
@@ -126,46 +137,56 @@ export async function scaffoldNewPen(options = {}) {
126
137
  }
127
138
  // 4. Determine visibility (Public default, Private, Protected, Collaborators)
128
139
  const { access, password } = await resolveVisibilityAndPassword({
129
- rawAccess: options.access,
140
+ rawAccess: prevalidatedAccess,
130
141
  rawPassword: options.password,
131
142
  interactive,
143
+ output,
132
144
  prompts: {
133
145
  select: selectImpl,
134
146
  secret: secretImpl,
135
147
  },
136
148
  });
137
- // 5. Resolve & validate target folder (if omitted on CLI) BEFORE creating the Pen on CodePen
138
- if (!targetDir) {
139
- const defaultFolder = cwdIsEmpty ? '.' : (slugifyTitle(title) ?? 'new-pen');
140
- if (interactive) {
141
- const chosenFolder = (await textImpl('Local folder to scaffold into', defaultFolder)).trim();
142
- folderDisplay = chosenFolder || defaultFolder;
143
- }
144
- else {
145
- folderDisplay = defaultFolder;
146
- }
147
- targetDir = path.resolve(cwd, folderDisplay);
148
- await assertEmptyTargetDirectory(targetDir, folderDisplay, {
149
- commandName: 'new',
150
- nonEmptyHint: NEW_NON_EMPTY_HINT,
151
- });
152
- }
153
- // 6. Fetch template files (if using a custom CodePen Template) and create Pen
149
+ // 5. Fetch template files (if using a custom CodePen Template) and create Pen
154
150
  const shouldWait = options.wait !== false;
155
151
  let textFiles;
156
152
  let binaryFiles = [];
157
153
  if (selected.kind === 'template') {
158
154
  if (!jsonMode) {
159
- console.log(fmt.dim(`\nReading template files from ${selected.pen.title || 'Untitled'} (${selected.pen.id})…`));
155
+ output.log(fmt.dim(`\nReading template files from ${selected.pen.title || 'Untitled'} (${selected.pen.id})…`));
160
156
  }
161
157
  const payload = await fetchPenFilesAsUploadPayload(client, selected.pen.id);
162
158
  if (payload.textFiles.length > 0 || payload.binaryFiles.length > 0) {
163
159
  textFiles = payload.textFiles;
164
160
  binaryFiles = payload.binaryFiles;
165
161
  }
162
+ if (resolvedBlocks !== undefined) {
163
+ const mergedFiles = textFiles ? [...textFiles] : [];
164
+ const existingPenConfigIdx = mergedFiles.findIndex((file) => (file.path.startsWith('/') ? file.path : `/${file.path}`) === PEN_CONFIG_PEN_PATH);
165
+ const existingPenConfig = existingPenConfigIdx >= 0
166
+ ? parseJsonObjectSafe(mergedFiles[existingPenConfigIdx]?.content)
167
+ : null;
168
+ const penConfigJson = `${JSON.stringify(buildPenConfigObject(resolvedBlocks, { existing: existingPenConfig }), null, 2)}\n`;
169
+ if (existingPenConfigIdx >= 0) {
170
+ mergedFiles[existingPenConfigIdx] = { path: PEN_CONFIG_PEN_PATH, content: penConfigJson };
171
+ }
172
+ else {
173
+ mergedFiles.push({ path: PEN_CONFIG_PEN_PATH, content: penConfigJson });
174
+ }
175
+ const hasClassicConfig = mergedFiles.some((file) => (file.path.startsWith('/') ? file.path : `/${file.path}`) === CLASSIC_CONFIG_PEN_PATH);
176
+ if (resolvedBlocks.includes('classic-1') && !hasClassicConfig) {
177
+ mergedFiles.push({
178
+ path: CLASSIC_CONFIG_PEN_PATH,
179
+ content: `${JSON.stringify(buildStarterClassicConfigFromPaths([
180
+ ...mergedFiles.map((file) => file.path),
181
+ ...binaryFiles.map((file) => file.path),
182
+ ]), null, 2)}\n`,
183
+ });
184
+ }
185
+ textFiles = mergedFiles;
186
+ }
166
187
  }
167
188
  if (!jsonMode) {
168
- console.log(selected.kind === 'default-starter'
189
+ output.log(selected.kind === 'default-starter'
169
190
  ? '\nCreating new CodePen 2.0 Pen with CodePen default starter files…'
170
191
  : `\nCreating new CodePen 2.0 Pen from ${selected.label}…`);
171
192
  }
@@ -183,14 +204,61 @@ export async function scaffoldNewPen(options = {}) {
183
204
  if (finalBuild && shouldWait) {
184
205
  finalBuild = await client.settleBuild(finalBuild);
185
206
  if (!jsonMode) {
186
- printBuildSummary(finalBuild);
207
+ printBuildSummary(finalBuild, output);
187
208
  }
188
209
  }
189
- await fs.mkdir(targetDir, { recursive: true });
190
- const finalVersionId = finalBuild?.version_id ?? created.saved_version?.id ?? null;
191
- const remoteFiles = finalVersionId
210
+ let finalVersionId = finalBuild?.version_id ?? created.saved_version?.id ?? null;
211
+ let remoteFiles = finalVersionId
192
212
  ? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(created.id))
193
213
  : await client.getPenFiles(created.id);
214
+ // When scaffolding from CodePen's default starter with explicit --blocks, apply the
215
+ // block configuration in a follow-up file write so CodePen's starter files are preserved.
216
+ if (selected.kind === 'default-starter' && resolvedBlocks !== undefined) {
217
+ const existingPenConfigFile = remoteFiles.find((file) => (file.path.startsWith('/') ? file.path : `/${file.path}`) === PEN_CONFIG_PEN_PATH);
218
+ let existingPenConfigRaw = null;
219
+ if (existingPenConfigFile && !existingPenConfigFile.is_binary) {
220
+ if (existingPenConfigFile.content !== null) {
221
+ existingPenConfigRaw = existingPenConfigFile.content;
222
+ }
223
+ else if (existingPenConfigFile.download_url) {
224
+ existingPenConfigRaw = (await client.downloadFile(existingPenConfigFile.download_url)).toString('utf8');
225
+ }
226
+ }
227
+ const penConfigJson = `${JSON.stringify(buildPenConfigObject(resolvedBlocks, { existing: parseJsonObjectSafe(existingPenConfigRaw) }), null, 2)}\n`;
228
+ const blockChanges = [
229
+ {
230
+ ...(existingPenConfigFile ? { id: existingPenConfigFile.id } : {}),
231
+ path: PEN_CONFIG_PEN_PATH,
232
+ content: penConfigJson,
233
+ },
234
+ ];
235
+ const hasClassicConfig = remoteFiles.some((file) => (file.path.startsWith('/') ? file.path : `/${file.path}`) === CLASSIC_CONFIG_PEN_PATH);
236
+ if (resolvedBlocks.includes('classic-1') && !hasClassicConfig) {
237
+ blockChanges.push({
238
+ path: CLASSIC_CONFIG_PEN_PATH,
239
+ content: `${JSON.stringify(buildStarterClassicConfigFromPaths(remoteFiles.map((file) => file.path)), null, 2)}\n`,
240
+ });
241
+ }
242
+ if (!jsonMode) {
243
+ output.log(fmt.dim(`Configuring CodePen blocks (${resolvedBlocks.join(', ')})…`));
244
+ }
245
+ const writeResult = await client.writePenFiles(created.id, {
246
+ files: blockChanges,
247
+ ...(finalVersionId ? { expected_version_id: finalVersionId } : {}),
248
+ wait: shouldWait ? 45 : 0,
249
+ });
250
+ if (writeResult.build) {
251
+ finalBuild = shouldWait ? await client.settleBuild(writeResult.build) : writeResult.build;
252
+ if (shouldWait && !jsonMode) {
253
+ printBuildSummary(finalBuild, output);
254
+ }
255
+ }
256
+ finalVersionId = finalBuild?.version_id ?? writeResult.version?.id ?? finalVersionId;
257
+ remoteFiles = finalVersionId
258
+ ? (await client.getVersion(finalVersionId)).files ?? (await client.getPenFiles(created.id))
259
+ : await client.getPenFiles(created.id);
260
+ }
261
+ await fs.mkdir(targetDir, { recursive: true });
194
262
  const materialized = await syncRemoteFilesToDisk({
195
263
  client,
196
264
  rootDir: targetDir,
@@ -208,9 +276,6 @@ export async function scaffoldNewPen(options = {}) {
208
276
  };
209
277
  const configPath = await writeProjectConfig(targetDir, config);
210
278
  const buildFailed = finalBuild?.status === 'Failed';
211
- if (buildFailed) {
212
- process.exitCode = 1;
213
- }
214
279
  if (jsonMode) {
215
280
  const code = buildFailed ? 422 : 201;
216
281
  const message = buildFailed
@@ -226,25 +291,29 @@ export async function scaffoldNewPen(options = {}) {
226
291
  version_id: finalVersionId,
227
292
  build: finalBuild,
228
293
  written_paths: materialized.writtenPaths,
229
- });
294
+ ...(resolvedBlocks ? { blocks: resolvedBlocks } : {}),
295
+ }, output);
230
296
  }
231
297
  else {
232
298
  if (buildFailed) {
233
- console.log(`\n${fmt.yellow('!')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
299
+ output.log(`\n${fmt.yellow('!')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}, but the initial build failed.`);
234
300
  }
235
301
  else {
236
- console.log(`\n${fmt.green('✓')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
302
+ output.log(`\n${fmt.green('✓')} Scaffolded Pen ${fmt.bold(created.title || 'Untitled')} ${fmt.dim(`(${created.id})`)}`);
237
303
  }
238
- console.log(` Template: ${selected.label}`);
304
+ output.log(` Template: ${selected.label}`);
239
305
  if (auth.profile) {
240
- console.log(` Profile: ${fmt.cyan(auth.profile)}`);
306
+ output.log(` Profile: ${fmt.cyan(auth.profile)}`);
241
307
  }
242
- console.log(` Visibility: ${created.access}${created.template ? fmt.dim(' · Template') : ''}`);
243
- console.log(` Folder: ${fmt.cyan(folderDisplay)}`);
244
- console.log(` Files: ${materialized.writtenPaths.length} written`);
245
- console.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
246
- console.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
247
- console.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
308
+ output.log(` Visibility: ${created.access}${created.template ? fmt.dim(' · Template') : ''}`);
309
+ if (resolvedBlocks) {
310
+ output.log(` Blocks: ${fmt.cyan(resolvedBlocks.join(', '))}`);
311
+ }
312
+ output.log(` Folder: ${fmt.cyan(folderDisplay)}`);
313
+ output.log(` Files: ${materialized.writtenPaths.length} written`);
314
+ output.log(` Editor: ${fmt.cyan(created.urls.editor)}`);
315
+ output.log(` Preview: ${fmt.cyan(created.urls.preview)}`);
316
+ output.log(` Version: ${fmt.dim(shortId(finalVersionId))}`);
248
317
  }
249
318
  return {
250
319
  pen: created,
@@ -257,6 +326,8 @@ export async function scaffoldNewPen(options = {}) {
257
326
  config,
258
327
  },
259
328
  templateLabel: selected.label,
329
+ ...(resolvedBlocks ? { blocks: resolvedBlocks } : {}),
330
+ ...(buildFailed ? { exitCode: 1 } : {}),
260
331
  };
261
332
  }
262
333
  export function registerNewCommand(program) {
@@ -267,30 +338,31 @@ export function registerNewCommand(program) {
267
338
  .option('-d, --description <text>', 'Description for the new Pen')
268
339
  .option('--tags <tags>', 'Comma-separated tags (up to 5)')
269
340
  .option('--access <level>', 'Privacy: Public, Private, Protected, or Collaborators')
341
+ .option('--visibility <level>', 'Alias for --access (Public, Private, Protected, or Collaborators)')
342
+ .option('--blocks <blocks>', 'Comma-separated CodePen blocks to enable (e.g. packages,classic; validate and fingerprint are always included)')
270
343
  .option('--password <password>', 'Password (min 8 chars; required with --access Protected)')
271
344
  .option('--template <id-or-name>', 'Scaffold from one of your CodePen Templates (ID, URL, or title)')
272
345
  .option('--as-template', 'Mark the newly created Pen as a Template on CodePen')
273
346
  .option('--no-wait', 'Return as soon as files are saved without waiting for the build')
274
347
  .option('--json', 'Output scaffolded Pen result as JSON')
275
348
  .action(async (folderArg, options, command) => {
276
- const tags = options.tags
277
- ? options.tags
278
- .split(',')
279
- .map((t) => t.trim())
280
- .filter(Boolean)
281
- : undefined;
282
- await scaffoldNewPen({
349
+ const result = await runNewCommand({
283
350
  folderArg,
284
351
  explicitProfile: getGlobalProfileOption(command),
285
352
  title: options.title,
286
353
  description: options.description,
287
- tags,
354
+ tags: parseTagsOption(options.tags),
288
355
  access: options.access,
356
+ visibility: options.visibility,
357
+ blocks: options.blocks,
289
358
  password: options.password,
290
359
  template: options.template,
291
360
  asTemplate: options.asTemplate,
292
361
  wait: options.wait,
293
362
  json: options.json,
294
363
  });
364
+ if (result.exitCode !== undefined) {
365
+ process.exitCode = result.exitCode;
366
+ }
295
367
  });
296
368
  }
package/commands/open.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { CodePenClient } from '../api/client.js';
2
2
  import { requireProject } from '../config/project.js';
3
+ import { CliError } from '../errors.js';
3
4
  import { openBrowser } from '../utils/browser.js';
4
5
  import { fmt } from '../utils/format.js';
5
- import { isInteractive, promptSelect } from '../utils/prompts.js';
6
- import { getGlobalProfileOption, resolveCommandAuth } from './auth-context.js';
6
+ import { defaultOutput } from '../utils/output.js';
7
+ import { isInteractive, promptSelect } from '../utils/prompts/index.js';
8
+ import { getGlobalProfileOption, resolveCommandAuth } from '../workflows/auth-context.js';
9
+ import { fetchLinkedPenOrHandleMissing, } from '../workflows/missing-pen.js';
7
10
  function normalizeDeployedHostToUrl(rawHostOrUrl) {
8
11
  const trimmed = rawHostOrUrl.trim();
9
12
  if (!trimmed)
@@ -76,10 +79,11 @@ export function buildDeployedDomainChoices(deployment, domains = []) {
76
79
  }
77
80
  return choices;
78
81
  }
79
- export async function openPenCommand(options = {}) {
82
+ export async function runOpenCommand(options = {}) {
83
+ const output = options.output ?? defaultOutput;
80
84
  const openDeployed = Boolean(options.deploy || options.live);
81
85
  if (options.preview && openDeployed) {
82
- throw new Error('Specify at most one of --preview or --deploy / --live.');
86
+ throw new CliError(400, 'Specify at most one of --preview or --deploy / --live.');
83
87
  }
84
88
  const cwd = options.cwd ?? process.cwd();
85
89
  const interactive = options.interactive ?? isInteractive();
@@ -90,26 +94,32 @@ export async function openPenCommand(options = {}) {
90
94
  explicitProfile: options.explicitProfile,
91
95
  project,
92
96
  interactive,
97
+ output,
93
98
  env: options.env,
94
99
  homeDir: options.homeDir,
95
100
  });
96
101
  const client = new CodePenClient({ apiKey: auth.apiKey, baseUrl: options.baseUrl });
97
- let pen;
98
- let domains = [];
99
- if (openDeployed) {
100
- [pen, domains] = await Promise.all([
101
- client.getPen(project.config.pen_id),
102
- client.listDomains(project.config.pen_id).catch(() => []),
103
- ]);
104
- }
105
- else {
106
- pen = await client.getPen(project.config.pen_id);
102
+ const penLookup = await fetchLinkedPenOrHandleMissing({
103
+ client,
104
+ project,
105
+ auth,
106
+ commandName: 'open',
107
+ interactive,
108
+ output,
109
+ prompts: options.prompts ?? { select: selectImpl },
110
+ });
111
+ if (!penLookup.found) {
112
+ return null;
107
113
  }
114
+ const pen = penLookup.pen;
115
+ const domains = openDeployed
116
+ ? await client.listDomains(project.config.pen_id).catch(() => [])
117
+ : [];
108
118
  let targetUrl;
109
119
  let label;
110
120
  if (openDeployed) {
111
121
  if (!pen.deployment) {
112
- throw new Error('This Pen is not deployed yet. Run `cdpn deploy` first.');
122
+ throw new CliError(404, 'This Pen is not deployed yet. Run `cdpn deploy` first.');
113
123
  }
114
124
  const choices = buildDeployedDomainChoices(pen.deployment, domains);
115
125
  if (choices.length > 1) {
@@ -126,7 +136,7 @@ export async function openPenCommand(options = {}) {
126
136
  .slice(1)
127
137
  .map((c) => c.url)
128
138
  .join(', ');
129
- console.log(fmt.dim(`Deployed to multiple domains; opening default URL (other domains: ${otherUrls}).`));
139
+ output.log(fmt.dim(`Deployed to multiple domains; opening default URL (other domains: ${otherUrls}).`));
130
140
  }
131
141
  }
132
142
  else {
@@ -142,10 +152,10 @@ export async function openPenCommand(options = {}) {
142
152
  targetUrl = pen.urls.editor || project.config.url;
143
153
  label = 'editor';
144
154
  }
145
- console.log(`Opening ${label}: ${fmt.cyan(targetUrl)}`);
155
+ output.log(`Opening ${label}: ${fmt.cyan(targetUrl)}`);
146
156
  const launched = await openBrowserImpl(targetUrl);
147
157
  if (!launched) {
148
- console.log(fmt.yellow('Could not launch browser automatically. Open the URL above manually.'));
158
+ output.log(fmt.yellow('Could not launch browser automatically. Open the URL above manually.'));
149
159
  }
150
160
  return {
151
161
  url: targetUrl,
@@ -164,7 +174,7 @@ export function registerOpenCommand(program) {
164
174
  .option('-d, --deploy', 'Open the deployed URL (prompts to choose when multiple domains exist)')
165
175
  .option('-l, --live', 'Alias for --deploy')
166
176
  .action(async (options, command) => {
167
- await openPenCommand({
177
+ await runOpenCommand({
168
178
  preview: options.preview,
169
179
  deploy: options.deploy,
170
180
  live: options.live,