@conloca/content-api 0.1.12 → 0.1.14

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/dist/node.mjs CHANGED
@@ -2,11 +2,9 @@ import { C as normalizePathname, D as Blocks, E as serializeMdxWithFrontmatter,
2
2
  import sortKeys from "sort-keys";
3
3
  import { access, mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, extname, join, parse, resolve } from "node:path";
5
- import { existsSync } from "node:fs";
6
5
  import { imageSize } from "image-size";
7
6
  import { spawn } from "node:child_process";
8
7
  import { createRemoteJWKSet, jwtVerify } from "jose";
9
- import { mkdir as mkdir$1, readFile as readFile$1, rename as rename$1, unlink as unlink$1, writeFile as writeFile$1 } from "fs/promises";
10
8
  import { dirname as dirname$1, join as join$1, normalize, resolve as resolve$1 } from "path";
11
9
  import { xxh3 } from "@node-rs/xxhash";
12
10
  import matter from "gray-matter";
@@ -15,10 +13,31 @@ import { Hono } from "hono";
15
13
  import { cors } from "hono/cors";
16
14
  import { getRequestListener } from "@hono/node-server";
17
15
 
16
+ //#region src/utils/atomic-write.ts
17
+ /**
18
+ * Write file atomically via temp file + rename to prevent corruption on crash.
19
+ * Callers are responsible for ensuring the parent directory exists.
20
+ */
21
+ async function atomicWriteFile(filePath, content) {
22
+ const hrtime = process.hrtime.bigint();
23
+ const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;
24
+ try {
25
+ await writeFile(tempFile, content);
26
+ await rename(tempFile, filePath);
27
+ } catch (error) {
28
+ try {
29
+ await unlink(tempFile);
30
+ } catch {}
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ //#endregion
18
36
  //#region src/asset-manifest.ts
19
37
  const MANIFEST_FILENAME = ".asset-manifest.json";
20
38
  var AssetManifest = class {
21
39
  manifestPath;
40
+ _lock = Promise.resolve();
22
41
  constructor(assetsPath) {
23
42
  this.manifestPath = join(assetsPath, MANIFEST_FILENAME);
24
43
  }
@@ -31,19 +50,37 @@ var AssetManifest = class {
31
50
  }
32
51
  }
33
52
  async write(data) {
34
- await writeFile(this.manifestPath, JSON.stringify(data, null, 2), "utf-8");
53
+ await atomicWriteFile(this.manifestPath, JSON.stringify(data, null, 2));
54
+ }
55
+ /** Atomic read-modify-write with promise-based mutex to prevent concurrent corruption */
56
+ async withManifest(fn) {
57
+ const prev = this._lock;
58
+ let release;
59
+ this._lock = new Promise((r) => {
60
+ release = r;
61
+ });
62
+ await prev;
63
+ try {
64
+ const updated = fn(await this.read());
65
+ await this.write(updated);
66
+ } finally {
67
+ release();
68
+ }
35
69
  }
36
70
  async add(relativePath, data) {
37
- const manifest = await this.read();
38
- manifest[relativePath] = data;
39
- await this.write(manifest);
71
+ await this.withManifest((manifest) => {
72
+ manifest[relativePath] = data;
73
+ return manifest;
74
+ });
40
75
  }
41
76
  async remove(relativePath) {
42
- const manifest = await this.read();
43
- if (!(relativePath in manifest)) return false;
44
- delete manifest[relativePath];
45
- await this.write(manifest);
46
- return true;
77
+ let existed = false;
78
+ await this.withManifest((manifest) => {
79
+ existed = relativePath in manifest;
80
+ if (existed) delete manifest[relativePath];
81
+ return manifest;
82
+ });
83
+ return existed;
47
84
  }
48
85
  async get(relativePath) {
49
86
  return (await this.read())[relativePath];
@@ -106,10 +143,15 @@ async function resolveRepoRoot(contentPath) {
106
143
  */
107
144
  function createGitOperations(config) {
108
145
  const { contentPath, branch } = config;
146
+ let cachedRepoRoot;
147
+ async function getCachedRepoRoot() {
148
+ if (cachedRepoRoot === void 0) cachedRepoRoot = await resolveRepoRoot(contentPath);
149
+ return cachedRepoRoot;
150
+ }
109
151
  return {
110
152
  async getStatus() {
111
153
  try {
112
- const repoRoot = await resolveRepoRoot(contentPath);
154
+ const repoRoot = await getCachedRepoRoot();
113
155
  if (!repoRoot) return {
114
156
  isRepo: false,
115
157
  hasChanges: false,
@@ -124,7 +166,12 @@ function createGitOperations(config) {
124
166
  "HEAD"
125
167
  ]);
126
168
  const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : "unknown";
127
- const statusResult = await runGitCommand(repoRoot, ["status", "--porcelain"]);
169
+ const statusResult = await runGitCommand(repoRoot, [
170
+ "status",
171
+ "--porcelain",
172
+ "--",
173
+ contentPath
174
+ ]);
128
175
  const changedFiles = (statusResult.stdout ? statusResult.stdout.split("\n").filter((l) => l.trim()) : []).length;
129
176
  const hasChanges = changedFiles > 0;
130
177
  const remoteConfigured = (await runGitCommand(repoRoot, [
@@ -169,12 +216,17 @@ function createGitOperations(config) {
169
216
  },
170
217
  async commitAll(message, author) {
171
218
  try {
172
- const repoRoot = await resolveRepoRoot(contentPath);
219
+ const repoRoot = await getCachedRepoRoot();
173
220
  if (!repoRoot) return {
174
221
  success: false,
175
222
  error: "Not a git repository"
176
223
  };
177
- const addResult = await runGitCommand(repoRoot, ["add", "-A"]);
224
+ const addResult = await runGitCommand(repoRoot, [
225
+ "add",
226
+ "-A",
227
+ "--",
228
+ contentPath
229
+ ]);
178
230
  if (addResult.exitCode !== 0) return {
179
231
  success: false,
180
232
  error: addResult.stderr || "Failed to stage changes"
@@ -182,7 +234,9 @@ function createGitOperations(config) {
182
234
  if ((await runGitCommand(repoRoot, [
183
235
  "diff",
184
236
  "--cached",
185
- "--quiet"
237
+ "--quiet",
238
+ "--",
239
+ contentPath
186
240
  ])).exitCode === 0) return {
187
241
  success: false,
188
242
  error: "No changes to commit"
@@ -190,7 +244,9 @@ function createGitOperations(config) {
190
244
  const diffStatResult = await runGitCommand(repoRoot, [
191
245
  "diff",
192
246
  "--cached",
193
- "--numstat"
247
+ "--numstat",
248
+ "--",
249
+ contentPath
194
250
  ]);
195
251
  const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split("\n").filter((l) => l.trim()).length : 0;
196
252
  const commitArgs = [
@@ -218,7 +274,7 @@ function createGitOperations(config) {
218
274
  },
219
275
  async pushOrigin() {
220
276
  try {
221
- const repoRoot = await resolveRepoRoot(contentPath);
277
+ const repoRoot = await getCachedRepoRoot();
222
278
  if (!repoRoot) return {
223
279
  success: false,
224
280
  error: "Not a git repository"
@@ -271,7 +327,7 @@ function createGitOperations(config) {
271
327
  },
272
328
  async pull() {
273
329
  try {
274
- const repoRoot = await resolveRepoRoot(contentPath);
330
+ const repoRoot = await getCachedRepoRoot();
275
331
  if (!repoRoot) return {
276
332
  success: false,
277
333
  error: "Not a git repository"
@@ -332,6 +388,55 @@ async function setupGitLfsAttributes(contentRoot) {
332
388
  await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
333
389
  }
334
390
 
391
+ //#endregion
392
+ //#region src/url-validation.ts
393
+ /**
394
+ * URL validation for SSRF prevention in server-side fetch operations.
395
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
396
+ */
397
+ const BLOCKED_HOSTNAMES = new Set(["localhost"]);
398
+ /** Check if an IPv4 address string points to a private/reserved range */
399
+ function isPrivateIPv4(hostname) {
400
+ const parts = hostname.split(".");
401
+ if (parts.length !== 4) return false;
402
+ const octets = parts.map((p) => Number.parseInt(p, 10));
403
+ if (octets.some((o) => Number.isNaN(o) || o < 0 || o > 255)) return false;
404
+ const [first, second] = octets;
405
+ if (first === 0) return true;
406
+ if (first === 10) return true;
407
+ if (first === 127) return true;
408
+ if (first === 169 && second === 254) return true;
409
+ if (first === 172 && second >= 16 && second <= 31) return true;
410
+ if (first === 192 && second === 168) return true;
411
+ return false;
412
+ }
413
+ /** Check if an IPv6 address string points to a private/reserved range */
414
+ function isPrivateIPv6(hostname) {
415
+ const lower = hostname.toLowerCase();
416
+ if (lower === "::1") return true;
417
+ if (lower === "::") return true;
418
+ if (lower.startsWith("fe80:") || lower.startsWith("fe80%")) return true;
419
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
420
+ return false;
421
+ }
422
+ /**
423
+ * Validate that a URL is safe to fetch server-side.
424
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
425
+ *
426
+ * @param url The URL string to validate
427
+ * @returns The parsed URL object if valid
428
+ * @throws Error if the URL is invalid, uses a blocked scheme, or points to a private IP
429
+ */
430
+ function validateFetchUrl(url) {
431
+ const parsed = new URL(url);
432
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("URL scheme must be http or https");
433
+ const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
434
+ if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) throw new Error("URL points to a private/reserved IP address");
435
+ if (isPrivateIPv4(hostname)) throw new Error("URL points to a private/reserved IP address");
436
+ if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
437
+ return parsed;
438
+ }
439
+
335
440
  //#endregion
336
441
  //#region src/asset-operations.ts
337
442
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -397,6 +502,13 @@ var AssetOperations = class {
397
502
  };
398
503
  this.manifest = new AssetManifest(config.assetsPath);
399
504
  }
505
+ /** Resolve folder from manifest when only filename is known */
506
+ async resolveFolder(filename) {
507
+ const entry = await this.manifest.getByFilename(filename);
508
+ if (!entry) return "/";
509
+ const lastSlash = entry.relativePath.lastIndexOf("/");
510
+ return lastSlash > 0 ? `/${entry.relativePath.slice(0, lastSlash)}` : "/";
511
+ }
400
512
  async ensureDir(subpath) {
401
513
  const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
402
514
  if (!subpath && this.dirEnsured) return;
@@ -419,16 +531,19 @@ var AssetOperations = class {
419
531
  * @param originalName Original filename
420
532
  * @param folder Optional folder path (relative to assets root)
421
533
  */
422
- resolveFilename(originalName, folder) {
534
+ async resolveFilename(originalName, folder) {
423
535
  const { name, ext } = parse(originalName);
424
536
  const sanitized = name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
425
537
  const safeExt = ext.toLowerCase();
426
538
  const baseDir = folder && folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, "")) : this.config.assetsPath;
427
539
  let candidate = `${sanitized}${safeExt}`;
428
540
  let counter = 0;
429
- while (existsSync(join(baseDir, candidate))) {
541
+ while (true) try {
542
+ await access(join(baseDir, candidate));
430
543
  counter++;
431
544
  candidate = `${sanitized}-${counter}${safeExt}`;
545
+ } catch {
546
+ break;
432
547
  }
433
548
  return candidate;
434
549
  }
@@ -518,7 +633,7 @@ var AssetOperations = class {
518
633
  await setupGitLfsAttributes(this.config.assetsPath);
519
634
  this.lfsSetup = true;
520
635
  }
521
- const filename = this.resolveFilename(file.name, folder);
636
+ const filename = await this.resolveFilename(file.name, folder);
522
637
  const filePath = folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\//, ""), filename) : join(this.config.assetsPath, filename);
523
638
  const arrayBuffer = await file.arrayBuffer();
524
639
  await writeFile(filePath, new Uint8Array(arrayBuffer));
@@ -579,6 +694,7 @@ var AssetOperations = class {
579
694
  * Get asset by filename and optional folder
580
695
  */
581
696
  async getAsset(filename, folder = "/") {
697
+ if (folder === "/") folder = await this.resolveFolder(filename);
582
698
  const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
583
699
  const fullPath = this.getAssetPath(filename, folder);
584
700
  let stats;
@@ -615,6 +731,7 @@ var AssetOperations = class {
615
731
  * Delete asset file and manifest entry
616
732
  */
617
733
  async delete(filename, folder = "/") {
734
+ if (folder === "/") folder = await this.resolveFolder(filename);
618
735
  const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
619
736
  const filePath = this.getAssetPath(filename, folder);
620
737
  try {
@@ -625,24 +742,46 @@ var AssetOperations = class {
625
742
  }
626
743
  /**
627
744
  * Import an image from a URL (server-side fetch, no CORS issues)
745
+ * Validates URL against SSRF, enforces 30s timeout, and checks response size.
628
746
  */
629
747
  async importFromUrl(url, metadata) {
748
+ try {
749
+ validateFetchUrl(url);
750
+ } catch (err) {
751
+ return {
752
+ success: false,
753
+ error: err instanceof Error ? err.message : "Invalid URL"
754
+ };
755
+ }
756
+ const controller = new AbortController();
757
+ const timeout = setTimeout(() => controller.abort(), 3e4);
630
758
  let response;
631
759
  try {
632
- response = await fetch(url);
760
+ response = await fetch(url, { signal: controller.signal });
633
761
  } catch {
634
762
  return {
635
763
  success: false,
636
764
  error: "Failed to fetch URL"
637
765
  };
766
+ } finally {
767
+ clearTimeout(timeout);
638
768
  }
639
769
  if (!response.ok) return {
640
770
  success: false,
641
771
  error: `Fetch failed with status ${response.status}`
642
772
  };
773
+ const contentLength = response.headers.get("content-length");
774
+ if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) return {
775
+ success: false,
776
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
777
+ };
643
778
  const contentType = response.headers.get("content-type") || "";
644
779
  const urlFilename = new URL(url).pathname.split("/").pop() || "imported-image.jpg";
645
780
  const arrayBuffer = await response.arrayBuffer();
781
+ if (arrayBuffer.byteLength > this.config.maxFileSize) return {
782
+ success: false,
783
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
784
+ };
646
785
  const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
647
786
  return this.upload(file, metadata);
648
787
  }
@@ -710,6 +849,7 @@ var AssetOperations = class {
710
849
  * @param folder Optional folder path (default '/')
711
850
  */
712
851
  async updateMetadata(filename, updates, folder = "/") {
852
+ if (folder === "/") folder = await this.resolveFolder(filename);
713
853
  const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
714
854
  const fullPath = this.getAssetPath(filename, folder);
715
855
  try {
@@ -789,7 +929,8 @@ var AssetOperations = class {
789
929
  */
790
930
  getAssetPath(filename, folder) {
791
931
  const subpath = folder && folder !== "/" ? folder.replace(/^\/+|\/+$/g, "") : "";
792
- return subpath ? join(this.config.assetsPath, subpath, filename) : join(this.config.assetsPath, filename);
932
+ const combined = subpath ? `${subpath}/${filename}` : filename;
933
+ return this.validateSubpath(combined);
793
934
  }
794
935
  /**
795
936
  * Read asset file contents for serving (filesystem-first)
@@ -876,7 +1017,7 @@ var AssetOperations = class {
876
1017
  error: "Target folder does not exist"
877
1018
  };
878
1019
  }
879
- let movedCount = 0;
1020
+ const moves = [];
880
1021
  for (const filename of filenames) {
881
1022
  const sourceFile = join(sourcePath, filename);
882
1023
  const targetFile = join(targetPath, filename);
@@ -884,19 +1025,27 @@ var AssetOperations = class {
884
1025
  const newRelativePath = normalizedTarget === "/" ? filename : `${normalizedTarget.slice(1)}/${filename}`;
885
1026
  try {
886
1027
  await rename(sourceFile, targetFile);
887
- const oldEntry = (await this.manifest.read())[oldRelativePath];
888
- if (oldEntry) {
889
- await this.manifest.remove(oldRelativePath);
890
- await this.manifest.add(newRelativePath, oldEntry);
891
- }
892
- movedCount++;
1028
+ moves.push({
1029
+ oldPath: oldRelativePath,
1030
+ newPath: newRelativePath
1031
+ });
893
1032
  } catch (err) {
894
1033
  console.error(`[AssetOperations] Failed to move ${filename}:`, err);
895
1034
  }
896
1035
  }
1036
+ if (moves.length > 0) await this.manifest.withManifest((data) => {
1037
+ for (const { oldPath, newPath } of moves) {
1038
+ const entry = data[oldPath];
1039
+ if (entry) {
1040
+ delete data[oldPath];
1041
+ data[newPath] = entry;
1042
+ }
1043
+ }
1044
+ return data;
1045
+ });
897
1046
  return {
898
1047
  success: true,
899
- moved: movedCount
1048
+ moved: moves.length
900
1049
  };
901
1050
  }
902
1051
  /**
@@ -995,8 +1144,8 @@ async function validateCFAccessRequest(request) {
995
1144
  valid: true,
996
1145
  required: true,
997
1146
  user: {
998
- email: payload.email || "",
999
- sub: payload.sub || ""
1147
+ email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1148
+ sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
1000
1149
  }
1001
1150
  };
1002
1151
  } catch (error) {
@@ -1021,7 +1170,7 @@ var ComponentRegistry = class {
1021
1170
  registry = {};
1022
1171
  initialized = false;
1023
1172
  constructor(canvasDir) {
1024
- this.registryPath = join$1(canvasDir, "components", "registry.json");
1173
+ this.registryPath = join(canvasDir, "components", "registry.json");
1025
1174
  }
1026
1175
  /**
1027
1176
  * Initialize the registry by loading from disk or creating new
@@ -1029,7 +1178,7 @@ var ComponentRegistry = class {
1029
1178
  async initialize() {
1030
1179
  if (this.initialized) return;
1031
1180
  try {
1032
- const content = await readFile$1(this.registryPath, "utf-8");
1181
+ const content = await readFile(this.registryPath, "utf-8");
1033
1182
  this.registry = JSON.parse(content);
1034
1183
  } catch (error) {
1035
1184
  if (error.code === "ENOENT") await this.save();
@@ -1047,18 +1196,10 @@ var ComponentRegistry = class {
1047
1196
  * Save registry to disk atomically
1048
1197
  */
1049
1198
  async save() {
1050
- const tempPath = `${this.registryPath}.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 9)}`;
1051
- try {
1052
- await mkdir$1(dirname$1(this.registryPath), { recursive: true });
1053
- const sorted = sortKeys(this.registry, { deep: true });
1054
- await writeFile$1(tempPath, JSON.stringify(sorted, null, 2));
1055
- await rename$1(tempPath, this.registryPath);
1056
- } catch (error) {
1057
- try {
1058
- await unlink$1(tempPath);
1059
- } catch {}
1060
- throw error;
1061
- }
1199
+ await mkdir(dirname(this.registryPath), { recursive: true });
1200
+ const sorted = sortKeys(this.registry, { deep: true });
1201
+ const content = JSON.stringify(sorted, null, 2);
1202
+ await atomicWriteFile(this.registryPath, content);
1062
1203
  }
1063
1204
  /**
1064
1205
  * Register a new component or update existing
@@ -3336,17 +3477,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3336
3477
  mdxContentPart = contentOnly;
3337
3478
  }
3338
3479
  const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
3339
- const hrtime = process.hrtime.bigint();
3340
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3341
- try {
3342
- await writeFile(tempFile, mdxContent);
3343
- await rename(tempFile, targetFilePath);
3344
- } catch (error) {
3345
- try {
3346
- await unlink(tempFile);
3347
- } catch {}
3348
- throw error;
3349
- }
3480
+ await atomicWriteFile(targetFilePath, mdxContent);
3350
3481
  } else if (targetFilePath.endsWith(".json")) {
3351
3482
  const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3352
3483
  const updatedFile = {
@@ -3364,17 +3495,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3364
3495
  if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3365
3496
  else delete updatedFile.unpublishAt;
3366
3497
  const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
3367
- const hrtime = process.hrtime.bigint();
3368
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3369
- try {
3370
- await writeFile(tempFile, serializedContent);
3371
- await rename(tempFile, targetFilePath);
3372
- } catch (error) {
3373
- try {
3374
- await unlink(tempFile);
3375
- } catch {}
3376
- throw error;
3377
- }
3498
+ await atomicWriteFile(targetFilePath, serializedContent);
3378
3499
  } else {
3379
3500
  const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3380
3501
  const updatedFile = {
@@ -3399,17 +3520,7 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3399
3520
  if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3400
3521
  else delete updatedFile.unpublishAt;
3401
3522
  const serializedContent = VXJSON.serialize(updatedFile);
3402
- const hrtime = process.hrtime.bigint();
3403
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3404
- try {
3405
- await writeFile(tempFile, serializedContent);
3406
- await rename(tempFile, targetFilePath);
3407
- } catch (error) {
3408
- try {
3409
- await unlink(tempFile);
3410
- } catch {}
3411
- throw error;
3412
- }
3523
+ await atomicWriteFile(targetFilePath, serializedContent);
3413
3524
  }
3414
3525
  const writtenBuffer = await readFile(targetFilePath);
3415
3526
  let newEtag;
@@ -4639,6 +4750,17 @@ function createContentAPIRouter(api, options) {
4639
4750
  contentRoot: options.contentRoot,
4640
4751
  ...options.assetConfig
4641
4752
  });
4753
+ function splitAssetPath(relativePath) {
4754
+ const lastSlash = relativePath.lastIndexOf("/");
4755
+ if (lastSlash > 0) return {
4756
+ folder: `/${relativePath.slice(0, lastSlash)}`,
4757
+ filename: relativePath.slice(lastSlash + 1)
4758
+ };
4759
+ return {
4760
+ folder: "/",
4761
+ filename: relativePath
4762
+ };
4763
+ }
4642
4764
  app.post("/assets/move", async (c) => {
4643
4765
  try {
4644
4766
  const { filenames, sourceFolder, targetFolder } = await c.req.json();
@@ -4728,9 +4850,9 @@ function createContentAPIRouter(api, options) {
4728
4850
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get folder tree"), 500);
4729
4851
  }
4730
4852
  });
4731
- app.get("/assets/:filename/usage", async (c) => {
4853
+ app.get("/assets/usage/:path{.+}", async (c) => {
4732
4854
  try {
4733
- const filename = c.req.param("filename");
4855
+ const { filename } = splitAssetPath(c.req.param("path"));
4734
4856
  const usage = await assetOps.getUsage(filename);
4735
4857
  return c.json({ usage });
4736
4858
  } catch (error) {
@@ -4739,47 +4861,45 @@ function createContentAPIRouter(api, options) {
4739
4861
  });
4740
4862
  app.get("/assets/serve/:path{.+}", async (c) => {
4741
4863
  try {
4742
- const relativePath = c.req.param("path");
4743
- const lastSlash = relativePath.lastIndexOf("/");
4744
- const folder = lastSlash > 0 ? `/${relativePath.slice(0, lastSlash)}` : "/";
4745
- const filename = lastSlash > 0 ? relativePath.slice(lastSlash + 1) : relativePath;
4864
+ const { folder, filename } = splitAssetPath(c.req.param("path"));
4746
4865
  const result = await assetOps.readAssetFile(filename, folder);
4747
4866
  if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
4748
- c.header("Content-Type", result.mimeType);
4749
- c.header("Cache-Control", "public, max-age=31536000, immutable");
4750
- return c.body(result.buffer);
4867
+ return new Response(new Uint8Array(result.buffer), { headers: {
4868
+ "Content-Type": result.mimeType,
4869
+ "Cache-Control": "public, max-age=31536000, immutable"
4870
+ } });
4751
4871
  } catch (error) {
4752
4872
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to serve asset"), 500);
4753
4873
  }
4754
4874
  });
4755
- app.get("/assets/:filename", async (c) => {
4875
+ app.get("/assets/meta/:path{.+}", async (c) => {
4756
4876
  try {
4757
- const filename = c.req.param("filename");
4758
- const asset = await assetOps.getAsset(filename);
4877
+ const { folder, filename } = splitAssetPath(c.req.param("path"));
4878
+ const asset = await assetOps.getAsset(filename, folder);
4759
4879
  if (!asset) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, "Asset not found"), 404);
4760
4880
  return c.json(asset);
4761
4881
  } catch (error) {
4762
4882
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get asset"), 500);
4763
4883
  }
4764
4884
  });
4765
- app.patch("/assets/:filename", async (c) => {
4885
+ app.patch("/assets/meta/:path{.+}", async (c) => {
4766
4886
  try {
4767
- const filename = c.req.param("filename");
4887
+ const { folder, filename } = splitAssetPath(c.req.param("path"));
4768
4888
  const { alt, tags } = await c.req.json();
4769
4889
  const result = await assetOps.updateMetadata(filename, {
4770
4890
  alt,
4771
4891
  tags
4772
- });
4892
+ }, folder);
4773
4893
  if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
4774
4894
  return c.json(result.asset);
4775
4895
  } catch (error) {
4776
4896
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to update asset"), 500);
4777
4897
  }
4778
4898
  });
4779
- app.delete("/assets/:filename", async (c) => {
4899
+ app.delete("/assets/meta/:path{.+}", async (c) => {
4780
4900
  try {
4781
- const filename = c.req.param("filename");
4782
- const result = await assetOps.delete(filename);
4901
+ const { folder, filename } = splitAssetPath(c.req.param("path"));
4902
+ const result = await assetOps.delete(filename, folder);
4783
4903
  if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
4784
4904
  return c.json({ success: true });
4785
4905
  } catch (error) {