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/README.md CHANGED
@@ -5,6 +5,7 @@ Sync local folders with [CodePen 2.0](https://codepen.io) Pens using the [CodePe
5
5
  - Clone Pens (text & binary files) to a local folder and pull remote updates
6
6
  - Track diffs between local files and the online saved head
7
7
  - Push additions, edits, and deletions as a single version — waiting for builds and syncing compiler patches back locally
8
+ - Serve and build local Pens (with CodePen `classic` & `packages` Blocks support) or whole directories of Pens with an automatic, customizable index shell
8
9
  - Deploy, undeploy, manage custom domains, browse versions & roll back, inspect/edit metadata & settings
9
10
 
10
11
  ## Installation
@@ -97,21 +98,43 @@ The `info` section tracks the Pen’s editable metadata (`title`, `description`,
97
98
 
98
99
  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
100
 
101
+ By default, `cdpn delete` moves the online Pen to CodePen’s Deleted Items (Trash, restorable for 3 days) and keeps both `.cdpn.json` (still linked) and `.codepen/` untouched—so running `cdpn status` afterwards detects the Pen in Trash and lets you restore it, or you can restore it directly with `cdpn restore`. Pass `--cleanup` to remove `.codepen/` while keeping only the unlinked `info` section in `.cdpn.json`, or pass `--full-cleanup` to remove both `.codepen/` and `.cdpn.json` (local source files always stay untouched). To unlink a folder locally without touching the online Pen on CodePen, run `cdpn unlink`. When you later push an unlinked folder 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`).
102
+
103
+ If a synced Pen was deleted on CodePen, commands like `cdpn status`, `cdpn pull`, `cdpn push`, `cdpn delete`, etc. automatically check CodePen’s Trash (`GET /v2/trash`):
104
+ - **Found in Deleted Items (Trash):** interactively offers to **restore the Pen** (`POST /v2/pens/{id}/restore`) and continue, **delete it permanently** (`DELETE /v2/trash/pens/{id}`) and unlink `.cdpn.json`, or **unlink the local copy** (keeping `info` so you can re-push as a new Pen). You can also run `cdpn restore` directly inside the folder (or `cdpn restore [url|id]` from anywhere).
105
+ - **Permanently deleted:** explains that the Pen no longer exists on CodePen and offers to unlink `.cdpn.json` (and `cdpn delete` unlinks it cleanly—or removes `.codepen/` and keeps only `info` with `--cleanup`, or removes both `.codepen/` and `.cdpn.json` with `--full-cleanup`—instead of failing with `404`).
106
+
100
107
  > **Why `.cdpn.json` instead of `.codepen`?**
101
108
  > 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
109
 
103
110
  You can also add an optional `.cdpnignore` file in a Pen folder to exclude extra local files from syncing (`.cdpn.json`, `.cdpnignore`, `.git`, `node_modules`, and `.DS_Store` are ignored automatically).
104
111
 
105
- ## Scaffolding & Templates (`cdpn new`)
112
+ ## Initializing & Scaffolding (`cdpn init` & `cdpn new`)
113
+
114
+ ### Initialize an existing local folder (`cdpn init`)
106
115
 
107
- `cdpn new [folder]` is dedicated to scaffolding a brand-new CodePen 2.0 Pen from a CodePen Template into a new or empty local folder (for pushing an existing local demo folder, run `cdpn push` inside that folder instead).
116
+ Run `cdpn init [dir]` inside any local folder to mark it as a CodePen demo by creating an unlinked `.cdpn.json` metadata file and `.codepen/pen.config.json` (plus a starter `.codepen/classic.config.json` if the `classic` block is selected):
117
+
118
+ ```bash
119
+ cdpn init # Interactive: asks for title, visibility, and blocks (multi-select)
120
+ cdpn init ./my-demo -t "Scroll Demo" --visibility Public --blocks packages
121
+ cdpn init -t "Template" -d "Starter pen" --tags css,layout --as-template
122
+ ```
123
+
124
+ - Interactively prompts for **Pen title**, **Pen visibility**, and **CodePen blocks** (multi-select; `validate` and `fingerprint` are required and cannot be unselected), then offers to push the demo to CodePen right away (defaults to `No`).
125
+ - Optional CLI flags let you bypass prompts (`-t/--title`, `--visibility`/`--access`, `--blocks`) and set extra metadata (`-d/--description`, `--tags`, `--template [bool]` / `--as-template`) without prompting.
126
+ - Once initialized, the folder is immediately discovered by `cdpn serve` / `cdpn build` and ready for `cdpn push`.
127
+
128
+ ### Scaffold from a CodePen Template (`cdpn new`)
129
+
130
+ `cdpn new [folder]` scaffolds a brand-new CodePen 2.0 Pen from a CodePen Template into a new or empty local folder. Running `cdpn new` in a directory that already has files is disallowed (use `cdpn init` to convert an existing local demo into a CodePen demo, or pass a new folder name like `cdpn new my-demo`).
108
131
 
109
132
  CodePen stores your reusable scaffolds as **Templates** (any Pen marked with `template: true` on CodePen or via `cdpn info --template true` / `cdpn new --as-template`), alongside CodePen's built-in 2.0 starter. When you run `cdpn new` interactively, it fetches your account's Templates from CodePen and lets you pick one (or use CodePen's default starter):
110
133
 
111
134
  ```bash
112
135
  cdpn new my-demo # Interactive picker (your CodePen Templates + CodePen default starter)
113
136
  cdpn new my-demo --template "CSS Demo Base" # Scaffold from a CodePen Template by title, ID, or URL
114
- cdpn new my-starter --as-template # Create a new reusable Template on CodePen
137
+ cdpn new my-starter --as-template --blocks packages -d "Reusable starter" --tags css,starter
115
138
  ```
116
139
 
117
140
  To fork one of your own 2.0 Pens into a new local folder, use `cdpn fork`:
@@ -123,9 +146,70 @@ cdpn fork https://codepen.io/username/pen/abcde my-fork # Forks directly in
123
146
 
124
147
  > **Note:** CodePen API v2 keys can only access and fork Pens owned by the key's account (other users' Pens return `404`, even when public). When you run `cdpn fork` or `cdpn clone` on another user's Pen URL interactively, `cdpn` offers to open the Pen in your browser so you can fork it on `codepen.io` and paste your forked URL back to clone immediately.
125
148
 
149
+ ## Local Serving, Static Builds & Custom Shells
150
+
151
+ `cdpn` can preview and statically build both individual Pens and multi-Pen directories locally—supporting CodePen 2.0 `classic` (`.pen.html` + `.codepen/classic.config.json`) and `packages` (`package.json` importmaps via `esm.sh`) blocks on the fly:
152
+
153
+ ```bash
154
+ # Serve a single Pen or a directory of Pens on http://127.0.0.1:3000
155
+ cdpn serve
156
+ cdpn serve my-demos --port 8080 --open
157
+
158
+ # Build a Pen (prompts for destination, defaults to ./build, updates .cdpnignore & offers .gitignore)
159
+ cdpn build
160
+ cdpn build --out dist --yes --watch
161
+
162
+ # Customize the demo index shell used for multi-Pen directories
163
+ cdpn shell show # Show active shell (built-in or custom ~/.cdpn path)
164
+ cdpn shell export ./my-shell --set # Export built-in shell files to edit & set as default in ~/.cdpn
165
+ cdpn shell set ./my-shell # Point ~/.cdpn to a custom shell directory
166
+ cdpn shell reset # Revert back to the built-in shell
167
+
168
+ # Override shell or index metadata per invocation
169
+ cdpn serve --shell ./my-shell --title "CSS Demos" --subtitle "Handcrafted experiments"
170
+ cdpn build --out dist --shell ./my-shell --title "CSS Demos"
171
+ ```
172
+
173
+ - **Pen folder** (contains `.cdpn.json`): serves or builds the Pen directly (if `.codepen/` is missing, `cdpn serve` serves it as plain static files with a helpful tip). When building a Pen into a subfolder of itself, `cdpn build` automatically adds that subfolder to `.cdpnignore` and offers to create/update `.gitignore`.
174
+ - **Directory of Pens** (no `.cdpn.json` at the root): recursively discovers subdirectories containing `.cdpn.json` and generates an in-memory `demos.json` (on `serve`) or static `demos.json` (on `build`) with the index shell—preserving an existing root `index.html` if present. Subdirectories without a `.cdpn.json` file are not indexed or served; during `cdpn serve`, the shell displays a hint to run `cdpn init` in any missing demo folder to mark it as a CodePen demo (omitted from static `cdpn build` output).
175
+
176
+ ## Batch Operations Across Multiple Pens (`all`)
177
+
178
+ To prevent accidental tree walking, batch operations across subdirectories are gated behind the **`all`** keyword on `status`, `push`, `pull`, `sync`, `delete`, and `unlink`. Without `all`, each command stays scoped to the current directory (or an explicit `[dir]` path like `cdpn pull my-demo`):
179
+
180
+ ```bash
181
+ # Target a single Pen by directory path
182
+ cdpn pull my-demo
183
+ cdpn status css/grid-demo
184
+
185
+ # Inspect sync status across all discovered Pens in subdirectories
186
+ cdpn status all
187
+
188
+ # Preview batch operations across all Pens without making any changes
189
+ cdpn sync all --dry-run
190
+ cdpn push all --dry-run
191
+ cdpn pull all --dry-run
192
+ cdpn delete all --dry-run
193
+ cdpn unlink all --dry-run
194
+
195
+ # Sync every discovered Pen bidirectionally (creates unlinked Pens, pushes local-ahead, pulls remote-ahead, flags conflicts)
196
+ cdpn sync all
197
+
198
+ # Destructive batch actions ask for an upfront yes/No confirmation followed by "Are you really sure?"
199
+ cdpn delete all # Moves all discovered linked Pens to Deleted Items (keeps .cdpn.json & .codepen/)
200
+ cdpn delete all --cleanup # Deletes on CodePen, removes .codepen/, keeps only unlinked info in .cdpn.json
201
+ cdpn delete all --full-cleanup # Deletes on CodePen and removes both .codepen/ and .cdpn.json
202
+ cdpn unlink all # Unlinks all discovered Pens locally (leaves online Pens untouched)
203
+ ```
204
+
205
+ - **Directory named `all`:** if a directory named `all` exists in `cwd`, running `cdpn pull all` interactively asks whether to target `./all` or walk all Pens (and `cdpn pull ./all` always targets the `./all` directory unambiguously).
206
+ - **Helpful fallback:** running `cdpn pull` (or `status`, `push`, `sync`, `delete`, `unlink`) interactively in a non-Pen directory with subdirectories immediately offers to run `cdpn <cmd> all` instead (yes/No, defaulting to `No`) without prescanning the tree first.
207
+ - Subdirectory walking enforces strict root containment, skips symlinks, hidden folders (`.git`, etc.), `node_modules`, `.cdpnignore`d paths, and built static outputs, and treats each Pen folder as a leaf.
208
+ - For batch `delete all` and `unlink all`, an upfront **yes/No** confirmation lists every targeted Pen (declining aborts immediately), followed by a second **"Are you really sure?"** confirmation before proceeding with all discovered Pens (pass `--yes` for non-interactive scripts, or `--dry-run` for a safe preview).
209
+
126
210
  ## Commands
127
211
 
128
- All commands accept the global `--profile <name>` flag to override the active profile. Every data/state command also accepts `--json` (everything except interactive-only `cdpn auth login` and browser-opening `cdpn open`).
212
+ All commands accept the global `--profile <name>` flag to override the active profile. Every data/state command also accepts `--json` (everything except interactive-only `cdpn auth login`, browser-opening `cdpn open`, and long-running `cdpn serve`).
129
213
 
130
214
  | Command | Description |
131
215
  | --- | --- |
@@ -133,13 +217,15 @@ All commands accept the global `--profile <name>` flag to override the active pr
133
217
  | `cdpn auth login [profile] [--default] [--no-open]` | Open CodePen API settings, verify key, and save a profile to `~/.cdpn` or print shell export lines |
134
218
  | `cdpn auth list [--json]` | List stored profiles in `~/.cdpn` (alias: `cdpn auth ls`) |
135
219
  | `cdpn auth default [profile] [--json]` | Set the default profile in `~/.cdpn` |
136
- | `cdpn auth logout [profile] [--all] [--json]` | Remove a specific profile or delete `~/.cdpn` completely |
137
- | `cdpn new [folder] [--template <id\|url\|title>] [--as-template] [--json]` | Scaffold a brand-new 2.0 Pen from a CodePen Template (or CodePen default starter) into a new or empty folder |
220
+ | `cdpn auth logout [profile] [--all] [--json]` | Remove a specific profile or clear all profiles from `~/.cdpn` (preserves global config if set) |
221
+ | `cdpn init [dir] [-t ...] [--visibility ...] [--blocks ...] [-d ...] [--tags ...] [--template [bool]\|--as-template] [-f\|-y] [--json]` | Initialize a local directory as a CodePen demo by creating `.cdpn.json` and `.codepen/pen.config.json` |
222
+ | `cdpn new [folder] [-t ...] [-d ...] [--tags ...] [--access\|--visibility ...] [--blocks ...] [--template <id\|url\|title>] [--as-template] [--json]` | Scaffold a brand-new 2.0 Pen from a CodePen Template (or CodePen default starter) into a new or empty folder |
138
223
  | `cdpn fork <url> [folder] [--title ...] [--access ...] [--json]` | Fork one of your own 2.0 Pens into a local folder (for other users' Pens, offers to open in browser to fork and clone back) |
139
224
  | `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
- | `cdpn pull [--force] [--json]` | Pull latest remote file and Pen info changes into an existing cloned folder (requires `.cdpn.json`) |
141
- | `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) |
225
+ | `cdpn pull [dir\|all] [--force] [--dry-run] [--json]` | Pull latest remote file and Pen info changes into a cloned folder, or pass `all` to walk subdirectories |
226
+ | `cdpn status [dir\|all] [--json]` | Show active profile, file and Pen info diffs, remote head, build & deployment status, or pass `all` to walk subdirectories |
227
+ | `cdpn push [dir\|all] [-m <label>] [--force] [--dry-run] [--no-wait] [--json]` | Push local file and `.cdpn.json` Pen info changes (text & binary + deletions), pass `all` to walk subdirectories, or push an unlinked local demo folder as a new Pen |
228
+ | `cdpn sync [dir\|all] [-m <label>] [--force] [--dry-run] [--no-wait] [--access\|--visibility ...] [--json]` | Bidirectionally sync a Pen (create unlinked, push local-ahead, pull remote-ahead, detect conflicts), or pass `all` to walk subdirectories |
143
229
  | `cdpn deploy [--no-push] [--version <id>] [--force] [--json]` | Push local changes (creating a Pen first if unlinked) and deploy to CodePen Hosting |
144
230
  | `cdpn undeploy [--yes] [--json]` | Take down the live deployment (Pen & versions remain intact) |
145
231
  | `cdpn domains [list] [--json]` | Show the default deployed URL, custom domains, verification status, and required DNS records |
@@ -150,9 +236,17 @@ All commands accept the global `--profile <name>` flag to override the active pr
150
236
  | `cdpn versions [--limit <n>] [--json]` | List saved versions with build status, labels, and markers (`head`, `local`, `deployed`) |
151
237
  | `cdpn rollback [version-id] [-m <label>] [--yes] [--json]` | Restore an older saved version to head and sync files locally |
152
238
  | `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`) |
239
+ | `cdpn delete [dir\|all] [--cleanup\|--full-cleanup] [--dry-run] [--yes] [--json]` | Delete the online Pen on CodePen (pass `all` to walk subdirectories with upfront double confirmation; moves to Deleted Items for 3 days, keeps `.cdpn.json` & `.codepen/` by default; `--cleanup` removes `.codepen/` and keeps unlinked `info`; `--full-cleanup` removes both; aliases: `cdpn del`, `cdpn rm`) |
240
+ | `cdpn restore [pen] [--json]` | Restore a deleted Pen from CodePen Deleted Items (Trash) — uses the linked `.cdpn.json` in the current folder, an explicit Pen URL/ID, or an interactive Trash picker outside a Pen folder |
241
+ | `cdpn unlink [dir\|all] [--dry-run] [--yes] [--json]` | Unlink a local folder from its online Pen (pass `all` to walk subdirectories with upfront double confirmation; keeps online Pens, `.codepen/`, Pen `info`, and local source files untouched) |
154
242
  | `cdpn info [--title ...] [--tags ...] [--access ...] [--template true\|false] [--json]` | View or update Pen metadata |
155
243
  | `cdpn settings [--auto-deploy ...] [--indent-with ...] [--json]` | View or update Pen editor & deployment settings |
244
+ | `cdpn serve [dir] [-p <port>] [-o] [--shell <dir>] [--title ...] [--subtitle ...] [--footer ...]` | Serve a local Pen (`.cdpn.json`) or directory of `.cdpn.json` Pens on `127.0.0.1` with live in-memory `demos.json` and `classic`/`packages` Blocks support |
245
+ | `cdpn build [dir] [-o <dir>] [-y\|-f] [-w] [--shell <dir>] [--title ...] [--subtitle ...] [--footer ...] [--json]` | Build a local Pen or directory of `.cdpn.json` Pens into a static deployable folder (auto-updates `.cdpnignore` and offers `.gitignore` when building inside a Pen) |
246
+ | `cdpn shell [show] [--json]` | Show the active demo index shell (custom `~/.cdpn` path or built-in) |
247
+ | `cdpn shell export [dir] [--set] [-y\|-f] [--json]` | Copy the built-in shell files into a local directory for customization (aliases: `eject`, `init`) |
248
+ | `cdpn shell set <dir> [--json]` | Set a custom default shell directory in `~/.cdpn` |
249
+ | `cdpn shell reset [--json]` | Reset the global shell in `~/.cdpn` back to the built-in shell (aliases: `unset`, `clear`) |
156
250
 
157
251
  ## JSON Output (`--json`)
158
252
 
package/api/client.js CHANGED
@@ -1,29 +1,56 @@
1
1
  import path from 'node:path';
2
- import { extractPenIdFromUrl } from '../config/project.js';
2
+ import { MAX_FILE_BYTES, MAX_MULTIPART_BYTES } from '../constants.js';
3
+ import { CliError } from '../errors.js';
4
+ import { extractPenIdFromUrl } from '../utils/codepen-url.js';
5
+ import { isLoopbackHost } from '../utils/strings.js';
3
6
  import { CodePenApiError } from './errors.js';
4
7
  export const DEFAULT_API_BASE_URL = 'https://api.codepen.io';
5
8
  /** Conservative threshold (12 MB) under CodePen's 16 MB JSON body limit before switching to multipart. */
6
9
  const JSON_BODY_LIMIT_BYTES = 12 * 1024 * 1024;
7
- /** CodePen's documented max multipart request size (120 MB). */
8
- export const MAX_MULTIPART_BYTES = 120 * 1024 * 1024;
9
- /** CodePen's documented max single file size (30 MB). */
10
- export const MAX_FILE_BYTES = 30 * 1024 * 1024;
11
- function isLocalLoopbackHost(hostname) {
12
- return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]';
13
- }
14
10
  function validateApiBaseUrl(rawUrl) {
15
11
  let parsed;
16
12
  try {
17
13
  parsed = new URL(rawUrl);
18
14
  }
19
15
  catch {
20
- throw new Error(`Invalid API base URL: ${rawUrl}`);
16
+ throw new CliError(400, `Invalid API base URL: ${rawUrl}`);
21
17
  }
22
- if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLocalLoopbackHost(parsed.hostname))) {
23
- throw new Error(`Refusing non-HTTPS API base URL: ${rawUrl}`);
18
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname))) {
19
+ throw new CliError(400, `Refusing non-HTTPS API base URL: ${rawUrl}`);
24
20
  }
25
21
  return parsed;
26
22
  }
23
+ async function throwApiError(response) {
24
+ let parsedBody = {};
25
+ try {
26
+ const text = await response.text();
27
+ if (text) {
28
+ parsedBody = JSON.parse(text);
29
+ }
30
+ }
31
+ catch {
32
+ // Non-JSON error body; keep fallback status message
33
+ }
34
+ throw new CodePenApiError(response.status, parsedBody);
35
+ }
36
+ function appendBinaryPartsToForm(form, binaryFiles, initialBytes) {
37
+ let totalBytes = initialBytes;
38
+ for (const part of binaryFiles) {
39
+ if (part.content.length === 0) {
40
+ throw new CliError(400, `Empty binary upload part is not allowed for ${part.path}; send empty files as text.`);
41
+ }
42
+ if (part.content.length > MAX_FILE_BYTES) {
43
+ throw new CliError(400, `File ${part.path} exceeds CodePen's 30 MB per-file limit.`);
44
+ }
45
+ totalBytes += part.content.length;
46
+ if (totalBytes > MAX_MULTIPART_BYTES) {
47
+ throw new CliError(400, `Upload exceeds CodePen's 120 MB multipart request limit.`);
48
+ }
49
+ const normalizedPath = part.path.startsWith('/') ? part.path : `/${part.path}`;
50
+ const filename = path.posix.basename(normalizedPath);
51
+ form.append(normalizedPath, new Blob([new Uint8Array(part.content)], { type: 'application/octet-stream' }), filename);
52
+ }
53
+ }
27
54
  export function parseLinkHeader(header) {
28
55
  const links = {};
29
56
  if (!header)
@@ -48,7 +75,7 @@ export class CodePenClient {
48
75
  fetchImpl;
49
76
  constructor(options) {
50
77
  if (!options.apiKey || !options.apiKey.trim()) {
51
- throw new Error('A CodePen API key is required.');
78
+ throw new CliError(401, 'A CodePen API key is required.');
52
79
  }
53
80
  this.apiKey = options.apiKey.trim();
54
81
  this.baseUrl = validateApiBaseUrl(options.baseUrl ?? DEFAULT_API_BASE_URL);
@@ -70,7 +97,7 @@ export class CodePenClient {
70
97
  if (endpointOrUrl.startsWith('http://') || endpointOrUrl.startsWith('https://')) {
71
98
  const parsed = new URL(endpointOrUrl);
72
99
  if (parsed.origin !== this.baseUrl.origin) {
73
- throw new Error(`Refusing to send API credentials to unexpected origin: ${parsed.origin}`);
100
+ throw new CliError(400, `Refusing to send API credentials to unexpected origin: ${parsed.origin}`);
74
101
  }
75
102
  targetUrl = parsed.toString();
76
103
  }
@@ -95,17 +122,7 @@ export class CodePenClient {
95
122
  body,
96
123
  });
97
124
  if (!response.ok) {
98
- let parsedBody = {};
99
- try {
100
- const text = await response.text();
101
- if (text) {
102
- parsedBody = JSON.parse(text);
103
- }
104
- }
105
- catch {
106
- // Non-JSON error body; keep fallback status message
107
- }
108
- throw new CodePenApiError(response.status, parsedBody);
125
+ await throwApiError(response);
109
126
  }
110
127
  return response;
111
128
  }
@@ -113,6 +130,12 @@ export class CodePenClient {
113
130
  const response = await this.requestRaw(method, endpointOrUrl, options);
114
131
  return (await response.json());
115
132
  }
133
+ async requestPaginated(endpointOrUrl, query) {
134
+ const response = await this.requestRaw('GET', endpointOrUrl, { query });
135
+ const items = (await response.json());
136
+ const links = parseLinkHeader(response.headers.get('link'));
137
+ return { items, links };
138
+ }
116
139
  /**
117
140
  * Verifies that the configured API key is accepted by CodePen API v2.
118
141
  * CodePen API v2 does not expose a `/me` endpoint; listing 1 Pen validates auth
@@ -132,33 +155,25 @@ export class CodePenClient {
132
155
  return null;
133
156
  }
134
157
  async listPens(params = {}) {
135
- const response = await this.requestRaw('GET', '/v2/pens', {
136
- query: {
137
- page: params.page,
138
- per_page: params.per_page,
139
- sort: params.sort,
140
- direction: params.direction,
141
- access: params.access,
142
- deployed: params.deployed,
143
- template: params.template,
144
- forks: params.forks,
145
- editor: params.editor,
146
- tags: params.tags,
147
- search_term: params.search_term,
148
- untitled: params.untitled,
149
- block: params.block,
150
- cursor: params.cursor,
151
- },
158
+ return this.requestPaginated('/v2/pens', {
159
+ page: params.page,
160
+ per_page: params.per_page,
161
+ sort: params.sort,
162
+ direction: params.direction,
163
+ access: params.access,
164
+ deployed: params.deployed,
165
+ template: params.template,
166
+ forks: params.forks,
167
+ editor: params.editor,
168
+ tags: params.tags,
169
+ search_term: params.search_term,
170
+ untitled: params.untitled,
171
+ block: params.block,
172
+ cursor: params.cursor,
152
173
  });
153
- const items = (await response.json());
154
- const links = parseLinkHeader(response.headers.get('link'));
155
- return { items, links };
156
174
  }
157
175
  async listPensPageByUrl(nextUrl) {
158
- const response = await this.requestRaw('GET', nextUrl);
159
- const items = (await response.json());
160
- const links = parseLinkHeader(response.headers.get('link'));
161
- return { items, links };
176
+ return this.requestPaginated(nextUrl);
162
177
  }
163
178
  async getPen(penIdOrUrl) {
164
179
  return this.requestJson('GET', `/v2/pens/${encodePenId(penIdOrUrl)}`);
@@ -172,22 +187,7 @@ export class CodePenClient {
172
187
  const form = new FormData();
173
188
  const { wait, ...penBody } = payload;
174
189
  form.append('pen', JSON.stringify(penBody));
175
- let totalBytes = Buffer.byteLength(jsonString, 'utf8');
176
- for (const part of binaryFiles) {
177
- if (part.content.length === 0) {
178
- throw new Error(`Empty binary upload part is not allowed for ${part.path}; send empty files as text.`);
179
- }
180
- if (part.content.length > MAX_FILE_BYTES) {
181
- throw new Error(`File ${part.path} exceeds CodePen's 30 MB per-file limit.`);
182
- }
183
- totalBytes += part.content.length;
184
- if (totalBytes > MAX_MULTIPART_BYTES) {
185
- throw new Error(`Upload exceeds CodePen's 120 MB multipart request limit.`);
186
- }
187
- const normalizedPath = part.path.startsWith('/') ? part.path : `/${part.path}`;
188
- const filename = path.posix.basename(normalizedPath);
189
- form.append(normalizedPath, new Blob([new Uint8Array(part.content)], { type: 'application/octet-stream' }), filename);
190
- }
190
+ appendBinaryPartsToForm(form, binaryFiles, Buffer.byteLength(jsonString, 'utf8'));
191
191
  return this.requestJson('POST', '/v2/pens', {
192
192
  query: wait !== undefined ? { wait } : undefined,
193
193
  formData: form,
@@ -204,6 +204,58 @@ export class CodePenClient {
204
204
  async deletePen(penId) {
205
205
  await this.requestRaw('DELETE', `/v2/pens/${encodePenId(penId)}`);
206
206
  }
207
+ async listTrash(params = {}) {
208
+ return this.requestPaginated('/v2/trash', {
209
+ page: params.page,
210
+ per_page: params.per_page,
211
+ sort: params.sort,
212
+ direction: params.direction,
213
+ });
214
+ }
215
+ async listTrashPageByUrl(nextUrl) {
216
+ return this.requestPaginated(nextUrl);
217
+ }
218
+ /**
219
+ * Searches CodePen Trash (`GET /v2/trash`) for a trashed Pen matching any of the given IDs.
220
+ * Returns `null` if not found.
221
+ */
222
+ async findTrashedPen(penIdOrIds, maxPages = 10) {
223
+ const candidates = new Set((Array.isArray(penIdOrIds) ? penIdOrIds : [penIdOrIds])
224
+ .map((id) => id.trim())
225
+ .filter(Boolean));
226
+ if (candidates.size === 0)
227
+ return null;
228
+ let page = await this.listTrash({ per_page: 100 });
229
+ let pagesRead = 1;
230
+ for (;;) {
231
+ for (const item of page.items) {
232
+ if (item.type === 'Pen' && (candidates.has(item.item_id) || candidates.has(item.id))) {
233
+ return item;
234
+ }
235
+ }
236
+ if (!page.links.next || pagesRead >= maxPages) {
237
+ return null;
238
+ }
239
+ page = await this.listTrashPageByUrl(page.links.next);
240
+ pagesRead++;
241
+ }
242
+ }
243
+ /** Restores a trashed Pen via `POST /v2/pens/{id}/restore` (`id` is the trash item's `item_id`). */
244
+ async restorePen(penId) {
245
+ return this.requestJson('POST', `/v2/pens/${encodePenId(penId)}/restore`);
246
+ }
247
+ /** Permanently deletes a trashed Pen via `DELETE /v2/trash/pens/{id}`. */
248
+ async purgeTrashedPen(penId) {
249
+ const response = await this.requestRaw('DELETE', `/v2/trash/pens/${encodePenId(penId)}`);
250
+ if (response.status === 204) {
251
+ return null;
252
+ }
253
+ const text = await response.text();
254
+ if (!text.trim()) {
255
+ return null;
256
+ }
257
+ return JSON.parse(text);
258
+ }
207
259
  async updateSettings(penId, payload) {
208
260
  return this.requestJson('PATCH', `/v2/pens/${encodePenId(penId)}/settings`, {
209
261
  json: payload,
@@ -226,26 +278,12 @@ export class CodePenClient {
226
278
  ...changesRest,
227
279
  ...(expected_version_id ? { expected_version_id } : {}),
228
280
  };
229
- form.append('changes', JSON.stringify(changesBody));
281
+ const changesJson = JSON.stringify(changesBody);
282
+ form.append('changes', changesJson);
230
283
  if (expected_version_id) {
231
284
  form.append('expected_version_id', expected_version_id);
232
285
  }
233
- let totalBytes = Buffer.byteLength(JSON.stringify(changesBody), 'utf8');
234
- for (const part of binaryFiles) {
235
- if (part.content.length === 0) {
236
- throw new Error(`Empty binary upload part is not allowed for ${part.path}; send empty files as text.`);
237
- }
238
- if (part.content.length > MAX_FILE_BYTES) {
239
- throw new Error(`File ${part.path} exceeds CodePen's 30 MB per-file limit.`);
240
- }
241
- totalBytes += part.content.length;
242
- if (totalBytes > MAX_MULTIPART_BYTES) {
243
- throw new Error(`Upload exceeds CodePen's 120 MB multipart request limit.`);
244
- }
245
- const normalizedPath = part.path.startsWith('/') ? part.path : `/${part.path}`;
246
- const filename = path.posix.basename(normalizedPath);
247
- form.append(normalizedPath, new Blob([new Uint8Array(part.content)], { type: 'application/octet-stream' }), filename);
248
- }
286
+ appendBinaryPartsToForm(form, binaryFiles, Buffer.byteLength(changesJson, 'utf8'));
249
287
  return this.requestJson('PUT', `/v2/pens/${encodePenId(penId)}/files`, {
250
288
  query: {
251
289
  wait,
@@ -264,29 +302,19 @@ export class CodePenClient {
264
302
  parsed = new URL(downloadUrl);
265
303
  }
266
304
  catch {
267
- throw new Error(`Invalid download URL: ${downloadUrl}`);
305
+ throw new CliError(400, `Invalid download URL: ${downloadUrl}`);
268
306
  }
269
307
  const isAllowedLocalMock = this.baseUrl.protocol === 'http:' &&
270
- isLocalLoopbackHost(this.baseUrl.hostname) &&
308
+ isLoopbackHost(this.baseUrl.hostname) &&
271
309
  parsed.origin === this.baseUrl.origin;
272
310
  if (parsed.protocol !== 'https:' && !isAllowedLocalMock) {
273
- throw new Error(`Refusing to download file over insecure protocol: ${parsed.protocol}`);
311
+ throw new CliError(400, `Refusing to download file over insecure protocol: ${parsed.protocol}`);
274
312
  }
275
313
  const response = await this.fetchImpl(parsed.toString(), {
276
314
  method: 'GET',
277
315
  });
278
316
  if (!response.ok) {
279
- let parsedBody = {};
280
- try {
281
- const text = await response.text();
282
- if (text) {
283
- parsedBody = JSON.parse(text);
284
- }
285
- }
286
- catch {
287
- // Ignore non-JSON error
288
- }
289
- throw new CodePenApiError(response.status, parsedBody);
317
+ await throwApiError(response);
290
318
  }
291
319
  const arrayBuffer = await response.arrayBuffer();
292
320
  return Buffer.from(arrayBuffer);
@@ -295,17 +323,12 @@ export class CodePenClient {
295
323
  return this.requestJson('GET', `/v2/versions/${encodeURIComponent(versionId)}`);
296
324
  }
297
325
  async listVersions(penId, params = {}) {
298
- const response = await this.requestRaw('GET', `/v2/pens/${encodePenId(penId)}/versions`, {
299
- query: {
300
- page: params.page,
301
- per_page: params.per_page,
302
- sort: params.sort,
303
- direction: params.direction,
304
- },
326
+ return this.requestPaginated(`/v2/pens/${encodePenId(penId)}/versions`, {
327
+ page: params.page,
328
+ per_page: params.per_page,
329
+ sort: params.sort,
330
+ direction: params.direction,
305
331
  });
306
- const items = (await response.json());
307
- const links = parseLinkHeader(response.headers.get('link'));
308
- return { items, links };
309
332
  }
310
333
  async restoreVersion(penId, versionId, label) {
311
334
  return this.requestJson('POST', `/v2/pens/${encodePenId(penId)}/versions/${encodeURIComponent(versionId)}/restore`, {
@@ -334,7 +357,7 @@ export class CodePenClient {
334
357
  return current;
335
358
  }
336
359
  if (Date.now() - started > maxPollTimeMs) {
337
- throw new Error(`Timed out waiting for build ${current.id} to settle (last status: ${current.status}).`);
360
+ throw new CliError(504, `Timed out waiting for build ${current.id} to settle (last status: ${current.status}).`);
338
361
  }
339
362
  await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
340
363
  const targetBuildId = nextId ?? current.id;
package/cli.js CHANGED
@@ -1,46 +1,37 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from 'node:fs';
3
- import path from 'node:path';
4
3
  import { fileURLToPath } from 'node:url';
5
4
  import { Command, CommanderError } from 'commander';
6
5
  import { isCodePenApiError } from './api/errors.js';
7
- import { registerAuthCommands } from './commands/auth.js';
6
+ import { registerAuthCommand } from './commands/auth/index.js';
7
+ import { registerBuildCommand } from './commands/build.js';
8
8
  import { registerCloneCommand } from './commands/clone.js';
9
9
  import { registerDeleteCommand } from './commands/delete.js';
10
- import { registerDeployCommands } from './commands/deploy.js';
10
+ import { registerDeployCommand } from './commands/deploy.js';
11
11
  import { registerDomainsCommand } from './commands/domains.js';
12
12
  import { registerForkCommand } from './commands/fork.js';
13
+ import { registerInfoCommand } from './commands/info.js';
14
+ import { registerInitCommand } from './commands/init.js';
13
15
  import { registerListCommand } from './commands/list.js';
14
- import { registerMetaCommands } from './commands/meta.js';
15
16
  import { registerNewCommand } from './commands/new.js';
16
17
  import { registerOpenCommand } from './commands/open.js';
17
18
  import { registerPrivacyCommand } from './commands/privacy.js';
18
19
  import { registerPullCommand } from './commands/pull.js';
19
20
  import { registerPushCommand } from './commands/push.js';
21
+ import { registerRestoreCommand } from './commands/restore.js';
22
+ import { registerRollbackCommand } from './commands/rollback.js';
23
+ import { registerServeCommand } from './commands/serve.js';
24
+ import { registerSettingsCommand } from './commands/settings.js';
25
+ import { registerShellCommand } from './commands/shell.js';
20
26
  import { registerStatusCommand } from './commands/status.js';
21
- import { registerVersionCommands } from './commands/versions.js';
27
+ import { registerSyncCommand } from './commands/sync.js';
28
+ import { registerUndeployCommand } from './commands/undeploy.js';
29
+ import { registerUnlinkCommand } from './commands/unlink.js';
30
+ import { registerVersionsCommand } from './commands/versions.js';
22
31
  import { fmt } from './utils/format.js';
23
32
  import { errorToJsonEnvelope, wantsJsonOutput } from './utils/json.js';
24
- function readPackageVersion() {
25
- const __filename = fileURLToPath(import.meta.url);
26
- const __dirname = path.dirname(__filename);
27
- // Works both in published dist/ (package.json beside cli.js) and local dev (../package.json)
28
- const candidates = [
29
- path.join(__dirname, 'package.json'),
30
- path.join(__dirname, '..', 'package.json'),
31
- ];
32
- for (const candidate of candidates) {
33
- try {
34
- const pkg = JSON.parse(fs.readFileSync(candidate, 'utf8'));
35
- if (pkg.version)
36
- return pkg.version;
37
- }
38
- catch {
39
- // Try next candidate
40
- }
41
- }
42
- return '0.0.0';
43
- }
33
+ import { readPackageVersion } from './utils/package-paths.js';
34
+ import { isPromptCanceledError } from './utils/prompts/index.js';
44
35
  export function createProgram() {
45
36
  const program = new Command();
46
37
  program
@@ -48,21 +39,31 @@ export function createProgram() {
48
39
  .description('Sync local folders with CodePen 2.0 Pens via the CodePen API v2')
49
40
  .version(readPackageVersion(), '-v, --version')
50
41
  .option('--profile <name>', 'Use a specific API key profile from ~/.cdpn');
51
- registerAuthCommands(program);
42
+ registerAuthCommand(program);
43
+ registerInitCommand(program);
52
44
  registerCloneCommand(program);
53
45
  registerForkCommand(program);
54
46
  registerPullCommand(program);
55
47
  registerStatusCommand(program);
56
48
  registerPushCommand(program);
57
- registerDeployCommands(program);
49
+ registerSyncCommand(program);
50
+ registerDeployCommand(program);
51
+ registerUndeployCommand(program);
58
52
  registerDomainsCommand(program);
59
53
  registerNewCommand(program);
60
54
  registerPrivacyCommand(program);
61
55
  registerDeleteCommand(program);
56
+ registerRestoreCommand(program);
57
+ registerUnlinkCommand(program);
62
58
  registerOpenCommand(program);
63
59
  registerListCommand(program);
64
- registerVersionCommands(program);
65
- registerMetaCommands(program);
60
+ registerVersionsCommand(program);
61
+ registerRollbackCommand(program);
62
+ registerInfoCommand(program);
63
+ registerSettingsCommand(program);
64
+ registerServeCommand(program);
65
+ registerBuildCommand(program);
66
+ registerShellCommand(program);
66
67
  return program;
67
68
  }
68
69
  function configureJsonErrorMode(cmd) {
@@ -95,6 +96,10 @@ async function main() {
95
96
  process.exitCode = 1;
96
97
  return;
97
98
  }
99
+ if (isPromptCanceledError(error)) {
100
+ process.exitCode = 130;
101
+ return;
102
+ }
98
103
  if (isCodePenApiError(error)) {
99
104
  console.error(`\n${fmt.red('Error:')} ${error.formatForUser()}`);
100
105
  }