codepen-commander 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/api/client.js +364 -0
- package/api/errors.js +49 -0
- package/cli.js +125 -0
- package/commands/auth-context.js +139 -0
- package/commands/auth.js +593 -0
- package/commands/clone.js +598 -0
- package/commands/create-pen.js +249 -0
- package/commands/delete.js +98 -0
- package/commands/deploy.js +176 -0
- package/commands/domains.js +197 -0
- package/commands/fork.js +342 -0
- package/commands/list.js +103 -0
- package/commands/meta.js +164 -0
- package/commands/new.js +294 -0
- package/commands/open.js +174 -0
- package/commands/privacy.js +234 -0
- package/commands/pull.js +128 -0
- package/commands/push.js +294 -0
- package/commands/scaffold.js +127 -0
- package/commands/status.js +131 -0
- package/commands/unowned-pen.js +153 -0
- package/commands/versions.js +172 -0
- package/config/auth.js +470 -0
- package/config/project.js +365 -0
- package/package.json +21 -4
- package/sync/diff.js +105 -0
- package/sync/fs.js +253 -0
- package/sync/materialize.js +81 -0
- package/types.js +1 -0
- package/utils/browser.js +47 -0
- package/utils/format.js +107 -0
- package/utils/html.js +51 -0
- package/utils/json.js +122 -0
- package/utils/prompts.js +316 -0
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError } from '../utils/json.js';
|
|
4
|
+
export const PROJECT_CONFIG_FILENAME = '.cdpn.json';
|
|
5
|
+
/**
|
|
6
|
+
* Walks upward from `startDir` looking for `.cdpn.json` (similar to how git locates `.git`).
|
|
7
|
+
*/
|
|
8
|
+
export async function findProject(startDir = process.cwd()) {
|
|
9
|
+
let current = path.resolve(startDir);
|
|
10
|
+
for (;;) {
|
|
11
|
+
const configPath = path.join(current, PROJECT_CONFIG_FILENAME);
|
|
12
|
+
try {
|
|
13
|
+
const stat = await fs.lstat(configPath);
|
|
14
|
+
if (stat.isFile()) {
|
|
15
|
+
const config = await readProjectConfig(current);
|
|
16
|
+
return { rootDir: current, configPath, config };
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error.code !== 'ENOENT') {
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const parent = path.dirname(current);
|
|
25
|
+
if (parent === current) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
current = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export async function requireProject(startDir = process.cwd()) {
|
|
32
|
+
const project = await findProject(startDir);
|
|
33
|
+
if (!project) {
|
|
34
|
+
throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in this directory or any parent directory.\nRun \`cdpn clone <url>\` to clone a Pen or \`cdpn new\` to create one.`);
|
|
35
|
+
}
|
|
36
|
+
return project;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Requires `.cdpn.json` to exist directly inside `dir` (does NOT walk upward to parent directories).
|
|
40
|
+
*/
|
|
41
|
+
export async function requireProjectInDir(dir = process.cwd()) {
|
|
42
|
+
const resolvedDir = path.resolve(dir);
|
|
43
|
+
if (await hasProjectConfigInDir(resolvedDir)) {
|
|
44
|
+
const config = await readProjectConfig(resolvedDir);
|
|
45
|
+
return {
|
|
46
|
+
rootDir: resolvedDir,
|
|
47
|
+
configPath: path.join(resolvedDir, PROJECT_CONFIG_FILENAME),
|
|
48
|
+
config,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
const parentDir = path.dirname(resolvedDir);
|
|
52
|
+
if (parentDir !== resolvedDir) {
|
|
53
|
+
const parentProject = await findProject(parentDir);
|
|
54
|
+
if (parentProject) {
|
|
55
|
+
throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in ${resolvedDir}.\n` +
|
|
56
|
+
`This command only works directly inside a folder containing ${PROJECT_CONFIG_FILENAME} (found one in parent folder: ${parentProject.rootDir}).`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
throw new CliError(404, `No ${PROJECT_CONFIG_FILENAME} found in ${resolvedDir}.\n` +
|
|
60
|
+
`This command only works in a folder with a ${PROJECT_CONFIG_FILENAME} file in it.`);
|
|
61
|
+
}
|
|
62
|
+
export async function hasProjectConfigInDir(dir) {
|
|
63
|
+
try {
|
|
64
|
+
const stat = await fs.lstat(path.join(path.resolve(dir), PROJECT_CONFIG_FILENAME));
|
|
65
|
+
return stat.isFile();
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error.code === 'ENOENT') {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export async function readProjectConfig(rootDir) {
|
|
75
|
+
const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
|
|
76
|
+
const raw = await fs.readFile(configPath, 'utf8');
|
|
77
|
+
let parsed;
|
|
78
|
+
try {
|
|
79
|
+
parsed = JSON.parse(raw);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new CliError(400, `Invalid JSON in ${configPath}`);
|
|
83
|
+
}
|
|
84
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
85
|
+
throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: expected a JSON object.`);
|
|
86
|
+
}
|
|
87
|
+
const record = parsed;
|
|
88
|
+
if (typeof record.pen_id !== 'string' || !record.pen_id.trim()) {
|
|
89
|
+
throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "pen_id" string.`);
|
|
90
|
+
}
|
|
91
|
+
if (typeof record.url !== 'string' || !record.url.trim()) {
|
|
92
|
+
throw new CliError(400, `Invalid ${PROJECT_CONFIG_FILENAME}: missing required "url" string.`);
|
|
93
|
+
}
|
|
94
|
+
const profile = typeof record.profile === 'string' && record.profile.trim()
|
|
95
|
+
? record.profile.trim()
|
|
96
|
+
: undefined;
|
|
97
|
+
const lastSynced = record.last_synced_version_id === null || typeof record.last_synced_version_id === 'string'
|
|
98
|
+
? record.last_synced_version_id
|
|
99
|
+
: null;
|
|
100
|
+
const editor = record.editor === 'V2' || record.editor === 'Classic' ? record.editor : undefined;
|
|
101
|
+
let files;
|
|
102
|
+
if (record.files && typeof record.files === 'object' && !Array.isArray(record.files)) {
|
|
103
|
+
files = {};
|
|
104
|
+
for (const [filePath, entry] of Object.entries(record.files)) {
|
|
105
|
+
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
|
|
106
|
+
const e = entry;
|
|
107
|
+
if (typeof e.id === 'string' &&
|
|
108
|
+
typeof e.content_hash === 'string' &&
|
|
109
|
+
typeof e.local_sha256 === 'string') {
|
|
110
|
+
files[filePath] = {
|
|
111
|
+
id: e.id,
|
|
112
|
+
content_hash: e.content_hash,
|
|
113
|
+
local_sha256: e.local_sha256,
|
|
114
|
+
is_binary: Boolean(e.is_binary),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
url: record.url.trim(),
|
|
122
|
+
pen_id: record.pen_id.trim(),
|
|
123
|
+
...(profile ? { profile } : {}),
|
|
124
|
+
last_synced_version_id: lastSynced,
|
|
125
|
+
...(editor ? { editor } : {}),
|
|
126
|
+
...(files ? { files } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
export async function writeProjectConfig(rootDir, config) {
|
|
130
|
+
const configPath = path.join(path.resolve(rootDir), PROJECT_CONFIG_FILENAME);
|
|
131
|
+
const trimmedProfile = config.profile?.trim();
|
|
132
|
+
const ordered = {
|
|
133
|
+
url: config.url,
|
|
134
|
+
pen_id: config.pen_id,
|
|
135
|
+
...(trimmedProfile ? { profile: trimmedProfile } : {}),
|
|
136
|
+
last_synced_version_id: config.last_synced_version_id,
|
|
137
|
+
...(config.editor ? { editor: config.editor } : {}),
|
|
138
|
+
...(config.files ? { files: sortRecordKeys(config.files) } : {}),
|
|
139
|
+
};
|
|
140
|
+
await fs.writeFile(configPath, `${JSON.stringify(ordered, null, 2)}\n`, 'utf8');
|
|
141
|
+
return configPath;
|
|
142
|
+
}
|
|
143
|
+
function sortRecordKeys(record) {
|
|
144
|
+
const sorted = {};
|
|
145
|
+
for (const key of Object.keys(record).sort()) {
|
|
146
|
+
const val = record[key];
|
|
147
|
+
if (val !== undefined) {
|
|
148
|
+
sorted[key] = val;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return sorted;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Builds the baseline file manifest stored in `.cdpn.json` after a pull or push.
|
|
155
|
+
*/
|
|
156
|
+
export function buildSyncedFileMap(remoteFiles, localSha256ByPath) {
|
|
157
|
+
const map = {};
|
|
158
|
+
for (const file of remoteFiles) {
|
|
159
|
+
const normalizedPath = file.path.startsWith('/') ? file.path : `/${file.path}`;
|
|
160
|
+
const localHash = localSha256ByPath.get(normalizedPath) ?? file.content_hash;
|
|
161
|
+
map[normalizedPath] = {
|
|
162
|
+
id: file.id,
|
|
163
|
+
content_hash: file.content_hash,
|
|
164
|
+
local_sha256: localHash,
|
|
165
|
+
is_binary: file.is_binary,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return sortRecordKeys(map);
|
|
169
|
+
}
|
|
170
|
+
const PEN_ID_PATTERN = /^[A-Za-z0-9_-]{3,64}$/;
|
|
171
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
172
|
+
const PEN_VIEW_SEGMENTS = new Set(['pen', 'full', 'details', 'debug', 'live', 'embed']);
|
|
173
|
+
const CLASSIC_PEN_VIEW_SEGMENTS = new Set([...PEN_VIEW_SEGMENTS, 'editor']);
|
|
174
|
+
/**
|
|
175
|
+
* Extracts a Pen's cpid or hashid from a CodePen URL, when present in the URL path or host.
|
|
176
|
+
*
|
|
177
|
+
* Examples:
|
|
178
|
+
* - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
|
|
179
|
+
* - `https://codepen.io/editor/bramus/pen/01a11c78-9eba-777b-98a7-fa51e8b7cb08/89bb` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
|
|
180
|
+
* - `https://codepen.io/bramus/pen/abcde` -> `abcde`
|
|
181
|
+
* - `https://codepen.io/team/username/pen/abcde` -> `abcde`
|
|
182
|
+
* - `https://codepen.io/bramus/embed/preview/abcde` -> `abcde`
|
|
183
|
+
* - `https://01a11c78-9eba-777b-98a7-fa51e8b7cb08.codepenusercontent.com/index.html` -> `01a11c78-9eba-777b-98a7-fa51e8b7cb08`
|
|
184
|
+
*/
|
|
185
|
+
export function extractPenIdFromUrl(rawUrl) {
|
|
186
|
+
let parsed;
|
|
187
|
+
try {
|
|
188
|
+
parsed = new URL(rawUrl.trim());
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
const host = parsed.hostname.toLowerCase();
|
|
194
|
+
if (host === 'codepen.io' || host === 'www.codepen.io') {
|
|
195
|
+
const segments = parsed.pathname.split('/').filter(Boolean);
|
|
196
|
+
if (segments.length < 2) {
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
let idx = 0;
|
|
200
|
+
const isV2EditorPath = segments[0]?.toLowerCase() === 'editor';
|
|
201
|
+
const viewSegments = isV2EditorPath ? PEN_VIEW_SEGMENTS : CLASSIC_PEN_VIEW_SEGMENTS;
|
|
202
|
+
if (isV2EditorPath) {
|
|
203
|
+
idx++;
|
|
204
|
+
if (segments.length === 2 && segments[1] && UUID_PATTERN.test(segments[1])) {
|
|
205
|
+
return segments[1];
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (segments[idx]?.toLowerCase() === 'team') {
|
|
209
|
+
// Skip `team/<team-slug>`
|
|
210
|
+
idx += 2;
|
|
211
|
+
}
|
|
212
|
+
else if (segments[idx] && !viewSegments.has(segments[idx].toLowerCase())) {
|
|
213
|
+
// Skip `<username>`
|
|
214
|
+
idx += 1;
|
|
215
|
+
}
|
|
216
|
+
const view = segments[idx]?.toLowerCase();
|
|
217
|
+
if (!view || !viewSegments.has(view)) {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
idx++;
|
|
221
|
+
// Handle `/embed/preview/<id>`
|
|
222
|
+
if (view === 'embed' && segments[idx]?.toLowerCase() === 'preview') {
|
|
223
|
+
idx++;
|
|
224
|
+
}
|
|
225
|
+
const idCandidate = segments[idx]?.trim();
|
|
226
|
+
if (idCandidate && PEN_ID_PATTERN.test(idCandidate)) {
|
|
227
|
+
return idCandidate;
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
// Content or preview subdomains carrying a UUID cpid (e.g. `<cpid>.codepenusercontent.com`)
|
|
232
|
+
const firstLabel = host.split('.')[0];
|
|
233
|
+
if (firstLabel &&
|
|
234
|
+
UUID_PATTERN.test(firstLabel) &&
|
|
235
|
+
(host.endsWith('.codepen.dev') ||
|
|
236
|
+
host.endsWith('.codepen.app') ||
|
|
237
|
+
host.endsWith('.codepenusercontent.com'))) {
|
|
238
|
+
return firstLabel;
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Validates and normalizes a Pen identifier or CodePen URL passed by the user.
|
|
244
|
+
* Extracts the Pen's cpid or hashid from CodePen URLs when present (CodePen REST API v2
|
|
245
|
+
* `/v2/pens/:id` reliably resolves raw IDs and can return 404 on `%2F`-encoded editor URLs),
|
|
246
|
+
* while preserving `originalUrl` for owner matching and `.cdpn.json`.
|
|
247
|
+
*/
|
|
248
|
+
export function normalizePenReference(rawInput) {
|
|
249
|
+
const trimmed = rawInput.trim();
|
|
250
|
+
if (!trimmed) {
|
|
251
|
+
throw new CliError(400, 'Pen URL or ID cannot be empty.');
|
|
252
|
+
}
|
|
253
|
+
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
|
254
|
+
let parsed;
|
|
255
|
+
try {
|
|
256
|
+
parsed = new URL(trimmed);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
throw new CliError(400, `Invalid URL: ${trimmed}`);
|
|
260
|
+
}
|
|
261
|
+
const host = parsed.hostname.toLowerCase();
|
|
262
|
+
const isCodePenHost = host === 'codepen.io' ||
|
|
263
|
+
host.endsWith('.codepen.io') ||
|
|
264
|
+
host.endsWith('.codepen.dev') ||
|
|
265
|
+
host.endsWith('.codepen.app') ||
|
|
266
|
+
host.endsWith('.codepenusercontent.com');
|
|
267
|
+
if (!isCodePenHost) {
|
|
268
|
+
throw new CliError(400, `Expected a CodePen URL (codepen.io / codepen.dev / codepen.app), got: ${host}`);
|
|
269
|
+
}
|
|
270
|
+
const extractedId = extractPenIdFromUrl(trimmed);
|
|
271
|
+
return {
|
|
272
|
+
apiIdentifier: extractedId ?? trimmed,
|
|
273
|
+
originalUrl: trimmed,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// Raw cpid (UUID) or hashid
|
|
277
|
+
if (!PEN_ID_PATTERN.test(trimmed)) {
|
|
278
|
+
throw new CliError(400, `Invalid Pen ID: "${trimmed}". Provide a Pen URL, cpid, or hashid.`);
|
|
279
|
+
}
|
|
280
|
+
return { apiIdentifier: trimmed };
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Converts a Pen title into a safe directory-name slug, or returns null for empty / "Untitled".
|
|
284
|
+
*/
|
|
285
|
+
export function slugifyTitle(rawTitle) {
|
|
286
|
+
const title = (rawTitle ?? '').trim();
|
|
287
|
+
if (!title || title.toLowerCase() === 'untitled') {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
const slug = title
|
|
291
|
+
.normalize('NFKD')
|
|
292
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
293
|
+
.toLowerCase()
|
|
294
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
295
|
+
.replace(/^-+|-+$/g, '')
|
|
296
|
+
.slice(0, 64);
|
|
297
|
+
if (!slug || slug === '.' || slug === '..') {
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
return slug;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Produces a safe default local folder name for a Pen based on its title or ID.
|
|
304
|
+
*/
|
|
305
|
+
export function suggestFolderName(pen) {
|
|
306
|
+
return slugifyTitle(pen.title) ?? pen.id.replace(/[^A-Za-z0-9_-]/g, '-');
|
|
307
|
+
}
|
|
308
|
+
const RESERVED_CODEPEN_SEGMENTS = new Set([
|
|
309
|
+
'pen',
|
|
310
|
+
'editor',
|
|
311
|
+
'full',
|
|
312
|
+
'details',
|
|
313
|
+
'debug',
|
|
314
|
+
'live',
|
|
315
|
+
'embed',
|
|
316
|
+
'settings',
|
|
317
|
+
'trending',
|
|
318
|
+
'following',
|
|
319
|
+
'your-work',
|
|
320
|
+
'collections',
|
|
321
|
+
'project',
|
|
322
|
+
'projects',
|
|
323
|
+
'api',
|
|
324
|
+
]);
|
|
325
|
+
/**
|
|
326
|
+
* Extracts the CodePen username or team slug from a `codepen.io` URL, if present.
|
|
327
|
+
* Supports CodePen 2.0 editor URLs (`https://codepen.io/editor/bramus/pen/<cpid>`),
|
|
328
|
+
* Classic personal URLs (`https://codepen.io/bramus/pen/<slug>`), and team URLs
|
|
329
|
+
* (`https://codepen.io/team/username/pen/...`, `https://codepen.io/editor/team/username/pen/...`).
|
|
330
|
+
*/
|
|
331
|
+
export function extractCodePenOwnerFromUrl(rawUrl) {
|
|
332
|
+
let parsed;
|
|
333
|
+
try {
|
|
334
|
+
parsed = new URL(rawUrl.trim());
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const host = parsed.hostname.toLowerCase();
|
|
340
|
+
if (host !== 'codepen.io' && host !== 'www.codepen.io') {
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
const segments = parsed.pathname.split('/').filter(Boolean);
|
|
344
|
+
let idx = 0;
|
|
345
|
+
// CodePen 2.0 editor URLs place `/editor/` before the username/team slug
|
|
346
|
+
if (segments[idx]?.toLowerCase() === 'editor') {
|
|
347
|
+
idx++;
|
|
348
|
+
}
|
|
349
|
+
// Team URLs may include a `/team/` prefix before the team slug
|
|
350
|
+
if (segments[idx]?.toLowerCase() === 'team') {
|
|
351
|
+
idx++;
|
|
352
|
+
}
|
|
353
|
+
// Require at least `<owner>/<view-or-resource>` remaining (e.g. `bramus/pen/<id>`)
|
|
354
|
+
if (segments.length - idx < 2) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
const candidate = segments[idx]?.trim();
|
|
358
|
+
if (!candidate || RESERVED_CODEPEN_SEGMENTS.has(candidate.toLowerCase())) {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
if (/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(candidate)) {
|
|
362
|
+
return candidate;
|
|
363
|
+
}
|
|
364
|
+
return null;
|
|
365
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codepen-commander",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Sync local folders with CodePen 2.0 Pens via the CodePen API v2",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20.0.0"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"cdpn": "cli.js"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"codepen",
|
|
15
|
+
"cdpn",
|
|
16
|
+
"cli",
|
|
17
|
+
"sync",
|
|
18
|
+
"deploy"
|
|
19
|
+
],
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"commander": "^13.1.0"
|
|
22
|
+
}
|
|
23
|
+
}
|
package/sync/diff.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
function normalizeRemotePath(p) {
|
|
2
|
+
return p.startsWith('/') ? p : `/${p}`;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Compares local files against the remote Pen's saved head files.
|
|
6
|
+
* - `added`: exists locally, not on remote (push will create)
|
|
7
|
+
* - `modified`: exists on both, content differs (push will overwrite)
|
|
8
|
+
* - `deleted`: exists on remote, missing locally (push will delete)
|
|
9
|
+
* - `unchanged`: identical on local and remote
|
|
10
|
+
*/
|
|
11
|
+
export async function computeSyncDiff(options) {
|
|
12
|
+
const { localFiles, remoteFiles, baseline, downloadFile } = options;
|
|
13
|
+
const remoteByPath = new Map();
|
|
14
|
+
for (const rf of remoteFiles) {
|
|
15
|
+
remoteByPath.set(normalizeRemotePath(rf.path), rf);
|
|
16
|
+
}
|
|
17
|
+
const added = [];
|
|
18
|
+
const modified = [];
|
|
19
|
+
const deleted = [];
|
|
20
|
+
const unchanged = [];
|
|
21
|
+
const sortedLocalPaths = [...localFiles.keys()].sort();
|
|
22
|
+
for (const filePath of sortedLocalPaths) {
|
|
23
|
+
const local = localFiles.get(filePath);
|
|
24
|
+
const remote = remoteByPath.get(filePath);
|
|
25
|
+
if (!remote) {
|
|
26
|
+
added.push({ path: filePath, local });
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
const same = await areFilesIdentical(local, remote, baseline?.[filePath], downloadFile);
|
|
30
|
+
if (same) {
|
|
31
|
+
unchanged.push({ path: filePath, local, remote });
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
modified.push({ path: filePath, local, remote });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const sortedRemotePaths = [...remoteByPath.keys()].sort();
|
|
38
|
+
for (const filePath of sortedRemotePaths) {
|
|
39
|
+
if (!localFiles.has(filePath)) {
|
|
40
|
+
const remote = remoteByPath.get(filePath);
|
|
41
|
+
deleted.push({ path: filePath, remote });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { added, modified, deleted, unchanged };
|
|
45
|
+
}
|
|
46
|
+
async function areFilesIdentical(local, remote, baselineEntry, downloadFile) {
|
|
47
|
+
// Fast, exact comparison for UTF-8 text files
|
|
48
|
+
if (!remote.is_binary && !local.isBinary && remote.content !== null && local.textContent !== null) {
|
|
49
|
+
return local.textContent === remote.content;
|
|
50
|
+
}
|
|
51
|
+
// Binary comparison:
|
|
52
|
+
// 1. Direct SHA-256 match against remote content_hash
|
|
53
|
+
if (local.sha256 === remote.content_hash) {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
// 2. Baseline match from .cdpn.json (covers cases where remote uses a non-raw-SHA256 hash)
|
|
57
|
+
if (baselineEntry &&
|
|
58
|
+
baselineEntry.content_hash === remote.content_hash &&
|
|
59
|
+
baselineEntry.local_sha256 === local.sha256) {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
// 3. Different byte lengths definitely mean modified
|
|
63
|
+
if (local.buffer.length !== remote.bytes) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// 4. Fallback exact byte comparison via signed download_url when available
|
|
67
|
+
if (remote.download_url && downloadFile) {
|
|
68
|
+
const remoteBytes = await downloadFile(remote.download_url);
|
|
69
|
+
return Buffer.compare(local.buffer, remoteBytes) === 0;
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
export function hasDiffChanges(diff) {
|
|
74
|
+
return diff.added.length > 0 || diff.modified.length > 0 || diff.deleted.length > 0;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Checks whether local files have been modified/added/deleted relative to the `.cdpn.json` baseline.
|
|
78
|
+
* Used before `cdpn pull` to warn before clobbering uncommitted local edits.
|
|
79
|
+
*/
|
|
80
|
+
export function detectLocalChangesFromBaseline(localFiles, baseline) {
|
|
81
|
+
if (!baseline) {
|
|
82
|
+
return { added: [...localFiles.keys()].sort(), modified: [], deleted: [] };
|
|
83
|
+
}
|
|
84
|
+
const added = [];
|
|
85
|
+
const modified = [];
|
|
86
|
+
const deleted = [];
|
|
87
|
+
for (const [filePath, local] of localFiles) {
|
|
88
|
+
const base = baseline[filePath];
|
|
89
|
+
if (!base) {
|
|
90
|
+
added.push(filePath);
|
|
91
|
+
}
|
|
92
|
+
else if (base.local_sha256 !== local.sha256) {
|
|
93
|
+
modified.push(filePath);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
for (const filePath of Object.keys(baseline)) {
|
|
97
|
+
if (!localFiles.has(filePath)) {
|
|
98
|
+
deleted.push(filePath);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
added.sort();
|
|
102
|
+
modified.sort();
|
|
103
|
+
deleted.sort();
|
|
104
|
+
return { added, modified, deleted };
|
|
105
|
+
}
|