@gallop.software/studio 0.1.93 → 0.1.95

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.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getAllThumbnailPaths,
3
3
  getThumbnailPath
4
- } from "../chunk-DTVEVFQ2.mjs";
4
+ } from "../chunk-IHXG2EE4.mjs";
5
5
 
6
6
  // src/handlers/index.ts
7
7
  import { NextResponse as NextResponse4 } from "next/server";
@@ -29,6 +29,35 @@ async function saveMeta(meta) {
29
29
  const metaPath = path.join(dataDir, "_meta.json");
30
30
  await fs.writeFile(metaPath, JSON.stringify(meta, null, 2));
31
31
  }
32
+ function getCdnUrls(meta) {
33
+ return meta._cdns || [];
34
+ }
35
+ function getOrAddCdnIndex(meta, cdnUrl) {
36
+ if (!meta._cdns) {
37
+ meta._cdns = [];
38
+ }
39
+ const normalizedUrl = cdnUrl.replace(/\/$/, "");
40
+ const existingIndex = meta._cdns.indexOf(normalizedUrl);
41
+ if (existingIndex >= 0) {
42
+ return existingIndex;
43
+ }
44
+ meta._cdns.push(normalizedUrl);
45
+ return meta._cdns.length - 1;
46
+ }
47
+ function getMetaEntry(meta, key) {
48
+ if (key.startsWith("_")) return void 0;
49
+ const value = meta[key];
50
+ if (Array.isArray(value)) return void 0;
51
+ return value;
52
+ }
53
+ function setMetaEntry(meta, key, entry) {
54
+ meta[key] = entry;
55
+ }
56
+ function getFileEntries(meta) {
57
+ return Object.entries(meta).filter(
58
+ ([key, value]) => !key.startsWith("_") && !Array.isArray(value)
59
+ );
60
+ }
32
61
 
33
62
  // src/handlers/utils/files.ts
34
63
  import path2 from "path";
@@ -188,16 +217,17 @@ async function handleList(request) {
188
217
  const requestedPath = searchParams.get("path") || "public";
189
218
  try {
190
219
  const meta = await loadMeta();
191
- const metaKeys = Object.keys(meta);
192
- if (metaKeys.length === 0) {
220
+ const fileEntries = getFileEntries(meta);
221
+ const cdnUrls = getCdnUrls(meta);
222
+ if (fileEntries.length === 0) {
193
223
  return NextResponse.json({ items: [], isEmpty: true });
194
224
  }
195
225
  const relativePath = requestedPath.replace(/^public\/?/, "");
196
226
  const pathPrefix = relativePath ? `/${relativePath}/` : "/";
197
227
  const items = [];
198
228
  const seenFolders = /* @__PURE__ */ new Set();
199
- for (const key of metaKeys) {
200
- const entry = meta[key];
229
+ const metaKeys = fileEntries.map(([key]) => key);
230
+ for (const [key, entry] of fileEntries) {
201
231
  if (!key.startsWith(pathPrefix) && pathPrefix !== "/") continue;
202
232
  if (pathPrefix === "/" && !key.startsWith("/")) continue;
203
233
  const remaining = pathPrefix === "/" ? key.slice(1) : key.slice(pathPrefix.length);
@@ -222,14 +252,14 @@ async function handleList(request) {
222
252
  } else {
223
253
  const fileName = remaining;
224
254
  const isImage = isImageFile(fileName);
225
- const isPushedToCloud = entry.c === 1;
255
+ const isPushedToCloud = entry.c !== void 0;
226
256
  let thumbnail;
227
257
  let hasThumbnail = false;
228
258
  let fileSize;
229
- if (isImage && (entry.w || entry.b)) {
259
+ if (isImage && entry.p === 1) {
230
260
  const thumbPath = getThumbnailPath(key, "sm");
231
- if (isPushedToCloud) {
232
- const cdnUrl = process.env.CLOUDFLARE_R2_PUBLIC_URL || process.env.NEXT_PUBLIC_CLOUDFLARE_R2_PUBLIC_URL;
261
+ if (isPushedToCloud && entry.c !== void 0) {
262
+ const cdnUrl = cdnUrls[entry.c];
233
263
  if (cdnUrl) {
234
264
  thumbnail = `${cdnUrl}${thumbPath}`;
235
265
  hasThumbnail = true;
@@ -246,7 +276,12 @@ async function handleList(request) {
246
276
  }
247
277
  }
248
278
  } else if (isImage) {
249
- thumbnail = key;
279
+ if (isPushedToCloud && entry.c !== void 0) {
280
+ const cdnUrl = cdnUrls[entry.c];
281
+ thumbnail = cdnUrl ? `${cdnUrl}${key}` : key;
282
+ } else {
283
+ thumbnail = key;
284
+ }
250
285
  hasThumbnail = false;
251
286
  }
252
287
  if (!isPushedToCloud) {
@@ -284,19 +319,21 @@ async function handleSearch(request) {
284
319
  }
285
320
  try {
286
321
  const meta = await loadMeta();
322
+ const fileEntries = getFileEntries(meta);
323
+ const cdnUrls = getCdnUrls(meta);
287
324
  const items = [];
288
- for (const [key, entry] of Object.entries(meta)) {
325
+ for (const [key, entry] of fileEntries) {
289
326
  if (!key.toLowerCase().includes(query)) continue;
290
327
  const fileName = path5.basename(key);
291
328
  const relativePath = key.slice(1);
292
329
  const isImage = isImageFile(fileName);
293
- const isPushedToCloud = entry.c === 1;
330
+ const isPushedToCloud = entry.c !== void 0;
294
331
  let thumbnail;
295
332
  let hasThumbnail = false;
296
- if (isImage && (entry.w || entry.b)) {
333
+ if (isImage && entry.p === 1) {
297
334
  const thumbPath = getThumbnailPath(key, "sm");
298
- if (isPushedToCloud) {
299
- const cdnUrl = process.env.CLOUDFLARE_R2_PUBLIC_URL || process.env.NEXT_PUBLIC_CLOUDFLARE_R2_PUBLIC_URL;
335
+ if (isPushedToCloud && entry.c !== void 0) {
336
+ const cdnUrl = cdnUrls[entry.c];
300
337
  if (cdnUrl) {
301
338
  thumbnail = `${cdnUrl}${thumbPath}`;
302
339
  hasThumbnail = true;
@@ -313,7 +350,12 @@ async function handleSearch(request) {
313
350
  }
314
351
  }
315
352
  } else if (isImage) {
316
- thumbnail = key;
353
+ if (isPushedToCloud && entry.c !== void 0) {
354
+ const cdnUrl = cdnUrls[entry.c];
355
+ thumbnail = cdnUrl ? `${cdnUrl}${key}` : key;
356
+ } else {
357
+ thumbnail = key;
358
+ }
317
359
  hasThumbnail = false;
318
360
  }
319
361
  items.push({
@@ -336,8 +378,9 @@ async function handleSearch(request) {
336
378
  async function handleListFolders() {
337
379
  try {
338
380
  const meta = await loadMeta();
381
+ const fileEntries = getFileEntries(meta);
339
382
  const folderSet = /* @__PURE__ */ new Set();
340
- for (const key of Object.keys(meta)) {
383
+ for (const [key] of fileEntries) {
341
384
  const parts = key.split("/");
342
385
  let current = "";
343
386
  for (let i = 1; i < parts.length - 1; i++) {
@@ -366,8 +409,9 @@ async function handleListFolders() {
366
409
  async function handleCountImages() {
367
410
  try {
368
411
  const meta = await loadMeta();
412
+ const fileEntries = getFileEntries(meta);
369
413
  const allImages = [];
370
- for (const key of Object.keys(meta)) {
414
+ for (const [key] of fileEntries) {
371
415
  const fileName = path5.basename(key);
372
416
  if (isImageFile(fileName)) {
373
417
  allImages.push(key.slice(1));
@@ -391,12 +435,13 @@ async function handleFolderImages(request) {
391
435
  }
392
436
  const folders = foldersParam.split(",");
393
437
  const meta = await loadMeta();
438
+ const fileEntries = getFileEntries(meta);
394
439
  const allImages = [];
395
440
  const prefixes = folders.map((f) => {
396
441
  const rel = f.replace(/^public\/?/, "");
397
442
  return rel ? `/${rel}/` : "/";
398
443
  });
399
- for (const key of Object.keys(meta)) {
444
+ for (const [key] of fileEntries) {
400
445
  const fileName = path5.basename(key);
401
446
  if (!isImageFile(fileName)) continue;
402
447
  for (const prefix of prefixes) {
@@ -790,6 +835,7 @@ async function handleSync(request) {
790
835
  return NextResponse3.json({ error: "No image keys provided" }, { status: 400 });
791
836
  }
792
837
  const meta = await loadMeta();
838
+ const cdnIndex = getOrAddCdnIndex(meta, publicUrl);
793
839
  const r2 = new S3Client2({
794
840
  region: "auto",
795
841
  endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
@@ -798,12 +844,12 @@ async function handleSync(request) {
798
844
  const pushed = [];
799
845
  const errors = [];
800
846
  for (const imageKey of imageKeys) {
801
- const entry = meta[imageKey];
847
+ const entry = getMetaEntry(meta, imageKey);
802
848
  if (!entry) {
803
849
  errors.push(`Image not found in meta: ${imageKey}. Run Scan first.`);
804
850
  continue;
805
851
  }
806
- if (entry.c) {
852
+ if (entry.c !== void 0) {
807
853
  pushed.push(imageKey);
808
854
  continue;
809
855
  }
@@ -842,7 +888,7 @@ async function handleSync(request) {
842
888
  } catch {
843
889
  }
844
890
  }
845
- entry.c = 1;
891
+ entry.c = cdnIndex;
846
892
  for (const thumbPath of getAllThumbnailPaths(imageKey)) {
847
893
  const localPath = path7.join(process.cwd(), "public", thumbPath);
848
894
  try {
@@ -883,8 +929,9 @@ async function handleReprocess(request) {
883
929
  for (const imageKey of imageKeys) {
884
930
  try {
885
931
  let buffer;
886
- const entry = meta[imageKey];
887
- const isPushedToCloud = entry?.c === 1;
932
+ const entry = getMetaEntry(meta, imageKey);
933
+ const isPushedToCloud = entry?.c !== void 0;
934
+ const existingCdnIndex = entry?.c;
888
935
  const originalPath = path7.join(process.cwd(), "public", imageKey);
889
936
  try {
890
937
  buffer = await fs6.readFile(originalPath);
@@ -900,7 +947,7 @@ async function handleReprocess(request) {
900
947
  }
901
948
  const updatedEntry = await processImage(buffer, imageKey);
902
949
  if (isPushedToCloud) {
903
- updatedEntry.c = 1;
950
+ updatedEntry.c = existingCdnIndex;
904
951
  await uploadToCdn(imageKey);
905
952
  await deleteLocalThumbnails(imageKey);
906
953
  try {
@@ -942,7 +989,7 @@ async function handleProcessAllStream() {
942
989
  const orphansRemoved = [];
943
990
  let alreadyProcessed = 0;
944
991
  const imagesToProcess = [];
945
- for (const [key, entry] of Object.entries(meta)) {
992
+ for (const [key, entry] of getFileEntries(meta)) {
946
993
  const fileName = path7.basename(key);
947
994
  if (!isImageFile(fileName)) continue;
948
995
  if (!entry.p) {
@@ -956,7 +1003,8 @@ async function handleProcessAllStream() {
956
1003
  for (let i = 0; i < imagesToProcess.length; i++) {
957
1004
  const { key, entry } = imagesToProcess[i];
958
1005
  const fullPath = path7.join(process.cwd(), "public", key);
959
- const isInCloud = entry.c === 1;
1006
+ const isInCloud = entry.c !== void 0;
1007
+ const existingCdnIndex = entry.c;
960
1008
  sendEvent({
961
1009
  type: "progress",
962
1010
  current: i + 1,
@@ -996,7 +1044,7 @@ async function handleProcessAllStream() {
996
1044
  meta[key] = {
997
1045
  ...processedEntry,
998
1046
  p: 1,
999
- ...isInCloud ? { c: 1 } : {}
1047
+ ...isInCloud ? { c: existingCdnIndex } : {}
1000
1048
  };
1001
1049
  }
1002
1050
  if (isInCloud) {
@@ -1015,8 +1063,8 @@ async function handleProcessAllStream() {
1015
1063
  }
1016
1064
  sendEvent({ type: "cleanup", message: "Removing orphaned thumbnails..." });
1017
1065
  const trackedPaths = /* @__PURE__ */ new Set();
1018
- for (const imageKey of Object.keys(meta)) {
1019
- if (!meta[imageKey].c) {
1066
+ for (const [imageKey, entry] of getFileEntries(meta)) {
1067
+ if (entry.c === void 0) {
1020
1068
  for (const thumbPath of getAllThumbnailPaths(imageKey)) {
1021
1069
  trackedPaths.add(thumbPath);
1022
1070
  }
@@ -1236,6 +1284,132 @@ async function handleScanStream() {
1236
1284
  });
1237
1285
  }
1238
1286
 
1287
+ // src/handlers/import.ts
1288
+ import sharp4 from "sharp";
1289
+ import { encode as encode3 } from "blurhash";
1290
+ function parseImageUrl(url) {
1291
+ const parsed = new URL(url);
1292
+ const base = `${parsed.protocol}//${parsed.host}`;
1293
+ const path9 = parsed.pathname;
1294
+ return { base, path: path9 };
1295
+ }
1296
+ async function processRemoteImage(url) {
1297
+ const response = await fetch(url);
1298
+ if (!response.ok) {
1299
+ throw new Error(`Failed to fetch: ${response.status}`);
1300
+ }
1301
+ const buffer = Buffer.from(await response.arrayBuffer());
1302
+ const metadata = await sharp4(buffer).metadata();
1303
+ const { data, info } = await sharp4(buffer).resize(32, 32, { fit: "inside" }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1304
+ const blurhash = encode3(new Uint8ClampedArray(data), info.width, info.height, 4, 4);
1305
+ return {
1306
+ w: metadata.width || 0,
1307
+ h: metadata.height || 0,
1308
+ b: blurhash
1309
+ };
1310
+ }
1311
+ async function handleImportUrls(request) {
1312
+ const encoder = new TextEncoder();
1313
+ const stream = new ReadableStream({
1314
+ async start(controller) {
1315
+ const sendEvent = (data) => {
1316
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}
1317
+
1318
+ `));
1319
+ };
1320
+ try {
1321
+ const { urls } = await request.json();
1322
+ if (!urls || !Array.isArray(urls) || urls.length === 0) {
1323
+ sendEvent({ type: "error", message: "No URLs provided" });
1324
+ controller.close();
1325
+ return;
1326
+ }
1327
+ const meta = await loadMeta();
1328
+ const added = [];
1329
+ const skipped = [];
1330
+ const errors = [];
1331
+ const total = urls.length;
1332
+ sendEvent({ type: "start", total });
1333
+ for (let i = 0; i < urls.length; i++) {
1334
+ const url = urls[i].trim();
1335
+ if (!url) continue;
1336
+ sendEvent({
1337
+ type: "progress",
1338
+ current: i + 1,
1339
+ total,
1340
+ percent: Math.round((i + 1) / total * 100),
1341
+ currentFile: url
1342
+ });
1343
+ try {
1344
+ const { base, path: path9 } = parseImageUrl(url);
1345
+ const existingEntry = getMetaEntry(meta, path9);
1346
+ if (existingEntry) {
1347
+ skipped.push(path9);
1348
+ continue;
1349
+ }
1350
+ const cdnIndex = getOrAddCdnIndex(meta, base);
1351
+ const imageData = await processRemoteImage(url);
1352
+ setMetaEntry(meta, path9, {
1353
+ w: imageData.w,
1354
+ h: imageData.h,
1355
+ b: imageData.b,
1356
+ c: cdnIndex
1357
+ });
1358
+ added.push(path9);
1359
+ } catch (error) {
1360
+ console.error(`Failed to import ${url}:`, error);
1361
+ errors.push(url);
1362
+ }
1363
+ }
1364
+ await saveMeta(meta);
1365
+ sendEvent({
1366
+ type: "complete",
1367
+ added: added.length,
1368
+ skipped: skipped.length,
1369
+ errors: errors.length
1370
+ });
1371
+ } catch (error) {
1372
+ console.error("Import failed:", error);
1373
+ sendEvent({ type: "error", message: "Import failed" });
1374
+ } finally {
1375
+ controller.close();
1376
+ }
1377
+ }
1378
+ });
1379
+ return new Response(stream, {
1380
+ headers: {
1381
+ "Content-Type": "text/event-stream",
1382
+ "Cache-Control": "no-cache",
1383
+ "Connection": "keep-alive"
1384
+ }
1385
+ });
1386
+ }
1387
+ async function handleGetCdns() {
1388
+ try {
1389
+ const meta = await loadMeta();
1390
+ const cdns = meta._cdns || [];
1391
+ return Response.json({ cdns });
1392
+ } catch (error) {
1393
+ console.error("Failed to get CDNs:", error);
1394
+ return Response.json({ error: "Failed to get CDNs" }, { status: 500 });
1395
+ }
1396
+ }
1397
+ async function handleUpdateCdns(request) {
1398
+ try {
1399
+ const { cdns } = await request.json();
1400
+ if (!Array.isArray(cdns)) {
1401
+ return Response.json({ error: "Invalid CDN array" }, { status: 400 });
1402
+ }
1403
+ const meta = await loadMeta();
1404
+ meta._cdns = cdns.map((url) => url.replace(/\/$/, ""));
1405
+ await saveMeta(meta);
1406
+ return Response.json({ success: true, cdns: meta._cdns });
1407
+ } catch (error) {
1408
+ console.error("Failed to update CDNs:", error);
1409
+ return Response.json({ error: "Failed to update CDNs" }, { status: 500 });
1410
+ }
1411
+ }
1412
+
1239
1413
  // src/handlers/index.ts
1240
1414
  async function GET(request) {
1241
1415
  if (process.env.NODE_ENV !== "development") {
@@ -1258,6 +1432,9 @@ async function GET(request) {
1258
1432
  if (route === "search") {
1259
1433
  return handleSearch(request);
1260
1434
  }
1435
+ if (route === "cdns") {
1436
+ return handleGetCdns();
1437
+ }
1261
1438
  return NextResponse4.json({ error: "Not found" }, { status: 404 });
1262
1439
  }
1263
1440
  async function POST(request) {
@@ -1293,6 +1470,12 @@ async function POST(request) {
1293
1470
  if (route === "scan") {
1294
1471
  return handleScanStream();
1295
1472
  }
1473
+ if (route === "import") {
1474
+ return handleImportUrls(request);
1475
+ }
1476
+ if (route === "cdns") {
1477
+ return handleUpdateCdns(request);
1478
+ }
1296
1479
  return NextResponse4.json({ error: "Not found" }, { status: 404 });
1297
1480
  }
1298
1481
  async function DELETE(request) {