@conloca/content-api 0.1.16 → 0.2.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 (299) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +18 -13
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +302 -254
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +59 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +88 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +407 -281
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +6 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +170 -119
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +914 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +47 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +113 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2685 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1341 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -1,25 +1,33 @@
1
- import { access, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
- import { extname, join, parse, resolve } from 'node:path';
3
- import { imageSize } from 'image-size';
4
- import { AssetManifest, } from './asset-manifest';
5
- import { setupGitLfsAttributes } from './git-operations';
6
- import { validateFetchUrl } from './url-validation';
7
- const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
8
- const DEFAULT_ACCEPTED_FORMATS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'ico'];
9
- const MIME_MAP = {
10
- jpg: 'image/jpeg',
11
- jpeg: 'image/jpeg',
12
- png: 'image/png',
13
- gif: 'image/gif',
14
- webp: 'image/webp',
15
- avif: 'image/avif',
16
- svg: 'image/svg+xml',
17
- ico: 'image/x-icon',
18
- };
19
- /** Recognized web image extensions for filesystem scanning */
20
- const RECOGNIZED_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'avif', 'ico']);
1
+ import { lstat, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { extname, join, parse, resolve, sep } from 'node:path';
3
+ import { imageSizeFromFile } from 'image-size/fromFile';
4
+ import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
5
+ import * as assetMetadata from './asset-metadata-store.js';
6
+ import { setupGitLfsAttributes } from './git-operations.js';
7
+ import { validateFetchUrl } from './url-validation.js';
8
+ /** Recognized web image extensions for filesystem scanning — the accepted upload formats */
9
+ const RECOGNIZED_IMAGE_EXTENSIONS = new Set(DEFAULT_ACCEPTED_FORMATS);
21
10
  /** System files to skip during filesystem scanning */
22
11
  const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);
12
+ /** Max redirect hops a URL import may follow (each re-validated before it is requested) */
13
+ const MAX_IMPORT_REDIRECTS = 5;
14
+ /** Recursively enumerate vxjson files without serial directory waits. */
15
+ async function vxjsonFiles(dir) {
16
+ let entries;
17
+ try {
18
+ entries = await readdir(dir, { withFileTypes: true });
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ const nested = await Promise.all(entries.map(async (entry) => {
24
+ const fullPath = join(dir, entry.name);
25
+ if (entry.isDirectory() && !entry.name.startsWith('.'))
26
+ return vxjsonFiles(fullPath);
27
+ return entry.isFile() && entry.name.endsWith('.vxjson') ? [fullPath] : [];
28
+ }));
29
+ return nested.flat();
30
+ }
23
31
  /** Check if filename has a recognized web image extension */
24
32
  function isRecognizedImageExtension(filename) {
25
33
  const ext = extname(filename).slice(1).toLowerCase();
@@ -29,28 +37,27 @@ function isRecognizedImageExtension(filename) {
29
37
  function isSystemFile(filename) {
30
38
  return filename.startsWith('.') || SYSTEM_FILES.has(filename.toLowerCase());
31
39
  }
40
+ /**
41
+ * Check that a name is one file in its folder, not a path that could step out of it. The names come
42
+ * straight from a request body, so anything that is not a string is refused too.
43
+ */
44
+ function isBareFilename(filename) {
45
+ return (typeof filename === 'string' && filename !== '' && filename !== '.' && filename !== '..' && !/[/\\]/.test(filename));
46
+ }
32
47
  export class AssetOperations {
33
48
  config;
34
- manifest;
35
49
  dirEnsured = false;
36
50
  lfsSetup = false;
37
51
  constructor(config) {
38
52
  this.config = {
39
53
  assetsPath: config.assetsPath,
40
54
  maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
41
- acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,
55
+ // Copy: the shared default is frozen, but AssetConfig stays a plain string[]
56
+ acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
42
57
  contentRoot: config.contentRoot,
43
58
  };
44
- this.manifest = new AssetManifest(config.assetsPath);
45
- }
46
- /** Resolve folder from manifest when only filename is known */
47
- async resolveFolder(filename) {
48
- const entry = await this.manifest.getByFilename(filename);
49
- if (!entry)
50
- return '/';
51
- const lastSlash = entry.relativePath.lastIndexOf('/');
52
- return lastSlash > 0 ? `/${entry.relativePath.slice(0, lastSlash)}` : '/';
53
59
  }
60
+ /** A bare filename always means the assets root; subfolder assets are addressed with their folder. */
54
61
  async ensureDir(subpath) {
55
62
  const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
56
63
  if (!subpath && this.dirEnsured)
@@ -69,8 +76,9 @@ export class AssetOperations {
69
76
  // Resolve both paths to absolute to ensure consistent comparison
70
77
  const assetsAbsolute = resolve(this.config.assetsPath);
71
78
  const fullPath = resolve(assetsAbsolute, normalizedSubpath);
72
- // Security check: ensure resolved path is within assetsPath
73
- if (!fullPath.startsWith(assetsAbsolute)) {
79
+ // Security check: ensure resolved path is assetsPath or inside it. The separator matters:
80
+ // a bare prefix check lets `../assets-evil` through as if it were inside `assets`.
81
+ if (fullPath !== assetsAbsolute && !fullPath.startsWith(`${assetsAbsolute}${sep}`)) {
74
82
  throw new Error('Path traversal detected');
75
83
  }
76
84
  return fullPath;
@@ -82,11 +90,14 @@ export class AssetOperations {
82
90
  */
83
91
  async resolveFilename(originalName, folder) {
84
92
  const { name, ext } = parse(originalName);
85
- // Sanitize: lowercase, replace spaces with dashes, remove non-alphanumeric except dash/dot
86
- const sanitized = name
93
+ // Normalize compatibility forms and accents before restricting the stored filename.
94
+ const cleaned = name
95
+ .normalize('NFKD')
87
96
  .toLowerCase()
88
97
  .replace(/\s+/g, '-')
89
- .replace(/[^a-z0-9-]/g, '');
98
+ .replace(/[^a-z0-9-]/g, '')
99
+ .slice(0, 200);
100
+ const sanitized = /[a-z0-9]/.test(cleaned) ? cleaned : 'file';
90
101
  const safeExt = ext.toLowerCase();
91
102
  // Determine base directory (assetsPath or assetsPath/folder)
92
103
  const baseDir = folder && folder !== '/'
@@ -97,7 +108,8 @@ export class AssetOperations {
97
108
  // eslint-disable-next-line no-constant-condition
98
109
  while (true) {
99
110
  try {
100
- await access(join(baseDir, candidate));
111
+ // lstat also reserves the name of a broken symlink.
112
+ await lstat(join(baseDir, candidate));
101
113
  counter++;
102
114
  candidate = `${sanitized}-${counter}${safeExt}`;
103
115
  }
@@ -115,58 +127,46 @@ export class AssetOperations {
115
127
  return size <= this.config.maxFileSize;
116
128
  }
117
129
  /**
118
- * Get image dimensions from manifest cache or by reading file headers
130
+ * Measure an image by reading its header. Never cached: the image is the only
131
+ * honest source, and writing the numbers back turned every listing into a write.
119
132
  */
120
- async getDimensions(filePath, manifestEntry) {
121
- // Check manifest cache first
122
- if (manifestEntry?.width && manifestEntry?.height) {
123
- return { width: manifestEntry.width, height: manifestEntry.height, fromCache: true };
124
- }
125
- // Read from file headers
133
+ async getDimensions(filePath) {
126
134
  try {
127
- const buffer = await readFile(filePath);
128
- const result = imageSize(new Uint8Array(buffer));
129
- return { width: result.width, height: result.height, fromCache: false };
135
+ const result = await imageSizeFromFile(filePath);
136
+ return { width: result.width, height: result.height };
130
137
  }
131
138
  catch {
132
- // SVGs and some formats may fail - return undefined dimensions
133
- return { width: undefined, height: undefined, fromCache: false };
139
+ // SVGs without intrinsic size and unsupported formats have no dimensions
140
+ return { width: undefined, height: undefined };
134
141
  }
135
142
  }
136
143
  /**
137
- * Build an AssetEntry from a directory entry, enriching with manifest metadata
144
+ * One AssetEntry: the file as it is on disk, plus whatever a person has
145
+ * written about it. Shared by every read, so they cannot drift.
138
146
  */
139
- async buildAssetEntry(dirent, folder, manifestData) {
140
- // Compute relative path for manifest lookup
141
- const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
142
- const manifestEntry = manifestData[relativePath];
143
- // Build full file path
144
- const fullPath = this.getAssetPath(dirent.name, folder);
145
- // Get file stats
146
- const stats = await stat(fullPath);
147
- // Get dimensions (from cache or file)
148
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
149
- // Progressive caching: if dimensions were computed from file, cache them
150
- if (!fromCache && width && height) {
151
- this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => { });
152
- }
153
- // Derive mimeType from extension
154
- const ext = extname(dirent.name).slice(1).toLowerCase();
155
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
147
+ async assetEntry(filename, folder, stats, metadata) {
148
+ const { width, height } = await this.getDimensions(this.getAssetPath(filename, folder));
149
+ const ext = extname(filename).slice(1).toLowerCase();
156
150
  return {
157
- filename: dirent.name,
158
- originalName: manifestEntry?.originalName || dirent.name,
159
- mimeType,
151
+ filename,
152
+ originalName: metadata?.originalName || filename,
153
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
160
154
  size: stats.size,
161
155
  width,
162
156
  height,
163
- alt: manifestEntry?.alt,
164
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
165
- uploadedBy: manifestEntry?.uploadedBy,
157
+ alt: metadata?.alt,
158
+ uploadedAt: metadata?.uploadedAt || stats.birthtime.toISOString(),
159
+ uploadedBy: metadata?.uploadedBy,
166
160
  folder,
167
- tags: manifestEntry?.tags,
161
+ tags: metadata?.tags,
168
162
  };
169
163
  }
164
+ /** Build an AssetEntry from a directory entry and the records already read for its folder */
165
+ async buildAssetEntry(dirent, folder, records) {
166
+ const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
167
+ const stats = await stat(this.getAssetPath(dirent.name, folder));
168
+ return this.assetEntry(dirent.name, folder, stats, records.get(relativePath));
169
+ }
170
170
  async upload(file, metadata) {
171
171
  if (!this.validateFormat(file.name)) {
172
172
  const allowed = this.config.acceptedFormats.join(', ');
@@ -177,7 +177,7 @@ export class AssetOperations {
177
177
  return { success: false, error: `File too large. Maximum: ${maxMB}MB` };
178
178
  }
179
179
  // Normalize folder path
180
- const folder = metadata?.folder && metadata.folder !== '/' ? '/' + metadata.folder.replace(/^\/+|\/+$/g, '') : '/';
180
+ const folder = metadata?.folder && metadata.folder !== '/' ? `/${metadata.folder.replace(/^\/+|\/+$/g, '')}` : '/';
181
181
  // Validate folder path (prevent path traversal)
182
182
  if (folder !== '/') {
183
183
  try {
@@ -187,6 +187,12 @@ export class AssetOperations {
187
187
  return { success: false, error: 'Invalid folder path' };
188
188
  }
189
189
  }
190
+ try {
191
+ await assetMetadata.migrateLegacyManifest(this.config);
192
+ }
193
+ catch (err) {
194
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
195
+ }
190
196
  await this.ensureDir();
191
197
  // Ensure target folder exists
192
198
  if (folder !== '/') {
@@ -196,36 +202,46 @@ export class AssetOperations {
196
202
  await setupGitLfsAttributes(this.config.assetsPath);
197
203
  this.lfsSetup = true;
198
204
  }
199
- const filename = await this.resolveFilename(file.name, folder);
200
- // Determine file path (in folder if specified)
201
- const filePath = folder !== '/'
202
- ? join(this.config.assetsPath, folder.replace(/^\//, ''), filename)
203
- : join(this.config.assetsPath, filename);
204
- const arrayBuffer = await file.arrayBuffer();
205
- await writeFile(filePath, new Uint8Array(arrayBuffer));
206
- // Compute relative path for manifest
205
+ const data = new Uint8Array(await file.arrayBuffer());
206
+ let filename;
207
+ let filePath;
208
+ for (;;) {
209
+ filename = await this.resolveFilename(file.name, folder);
210
+ filePath = this.getAssetPath(filename, folder);
211
+ try {
212
+ // oxlint-disable-next-line no-await-in-loop -- each exclusive create depends on the filename collision found by the preceding attempt.
213
+ await writeFile(filePath, data, { flag: 'wx' });
214
+ break;
215
+ }
216
+ catch (error) {
217
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST')
218
+ throw error;
219
+ }
220
+ }
207
221
  const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
208
- // Create manifest entry
209
- const manifestEntry = {
222
+ const uploadedAt = new Date().toISOString();
223
+ const uploaded = {
210
224
  alt: metadata?.alt,
211
- width: metadata?.width,
212
- height: metadata?.height,
213
- uploadedAt: new Date().toISOString(),
225
+ uploadedAt,
214
226
  uploadedBy: metadata?.uploadedBy,
215
227
  originalName: file.name,
216
228
  };
217
- await this.manifest.add(relativePath, manifestEntry);
218
- // Build full AssetEntry for return
229
+ // Replace, never merge: a new file landing on a freed filename must not
230
+ // inherit the alt text of the picture that used to be there.
231
+ await assetMetadata.write(this.config, relativePath, uploaded);
232
+ // Measure the file that was just written, so URL imports and API clients
233
+ // that send no dimensions still get the real ones back
234
+ const { width, height } = await this.getDimensions(filePath);
219
235
  const ext = extname(filename).slice(1).toLowerCase();
220
236
  const entry = {
221
237
  filename,
222
238
  originalName: file.name,
223
- mimeType: MIME_MAP[ext] || `image/${ext}`,
239
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
224
240
  size: file.size,
225
- width: metadata?.width,
226
- height: metadata?.height,
241
+ width,
242
+ height,
227
243
  alt: metadata?.alt,
228
- uploadedAt: manifestEntry.uploadedAt,
244
+ uploadedAt,
229
245
  uploadedBy: metadata?.uploadedBy,
230
246
  folder,
231
247
  };
@@ -235,8 +251,6 @@ export class AssetOperations {
235
251
  * List all assets recursively from filesystem
236
252
  */
237
253
  async list() {
238
- // Load manifest once for enrichment
239
- const manifestData = await this.manifest.read();
240
254
  const assets = [];
241
255
  // Recursive scanning helper
242
256
  const scanFolder = async (folderPath, folder) => {
@@ -247,21 +261,23 @@ export class AssetOperations {
247
261
  catch {
248
262
  return;
249
263
  }
250
- for (const entry of entries) {
251
- // Skip hidden files, system files, and symlinks
252
- if (isSystemFile(entry.name) || entry.isSymbolicLink()) {
253
- continue;
254
- }
255
- const entryPath = join(folderPath, entry.name);
264
+ // Skip hidden files, system files, and symlinks
265
+ const visible = entries.filter((entry) => !isSystemFile(entry.name) && !entry.isSymbolicLink());
266
+ const imageFiles = visible.filter((entry) => entry.isFile() && isRecognizedImageExtension(entry.name));
267
+ if (imageFiles.length > 0) {
268
+ // Records are gathered per folder: one folder's records say nothing
269
+ // about another's, so a single read of the root would blank every
270
+ // subfolder image's alt text.
271
+ const records = await assetMetadata.readFolder(this.config, folder);
272
+ const folderAssets = await Promise.all(imageFiles.map((entry) => this.buildAssetEntry(entry, folder, records)));
273
+ for (const asset of folderAssets)
274
+ assets.push(asset);
275
+ }
276
+ for (const entry of visible) {
256
277
  if (entry.isDirectory()) {
257
- // Recurse into subdirectories
258
278
  const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;
259
- await scanFolder(entryPath, subFolder);
260
- }
261
- else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
262
- // Build asset entry from filesystem + manifest
263
- const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);
264
- assets.push(assetEntry);
279
+ // oxlint-disable-next-line no-await-in-loop -- preserve deterministic depth-first asset ordering across folders.
280
+ await scanFolder(join(folderPath, entry.name), subFolder);
265
281
  }
266
282
  }
267
283
  };
@@ -272,73 +288,53 @@ export class AssetOperations {
272
288
  * Get asset by filename and optional folder
273
289
  */
274
290
  async getAsset(filename, folder = '/') {
275
- // Resolve actual folder from manifest when caller only provides filename
276
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
277
- // Compute relative path and full file path
278
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
279
- const fullPath = this.getAssetPath(filename, resolvedFolder);
280
- // Check if file exists on disk
291
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
281
292
  let stats;
282
293
  try {
283
- stats = await stat(fullPath);
294
+ stats = await stat(this.getAssetPath(filename, folder));
284
295
  }
285
296
  catch {
286
- // File doesn't exist
287
297
  return undefined;
288
298
  }
289
- if (!stats.isFile()) {
299
+ if (!stats.isFile())
290
300
  return undefined;
291
- }
292
- // Load manifest for enrichment
293
- const manifestData = await this.manifest.read();
294
- const manifestEntry = manifestData[relativePath];
295
- // Get dimensions
296
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
297
- // Progressive caching
298
- if (!fromCache && width && height) {
299
- this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => { });
300
- }
301
- // Derive mimeType from extension
302
- const ext = extname(filename).slice(1).toLowerCase();
303
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
304
- return {
305
- filename,
306
- originalName: manifestEntry?.originalName || filename,
307
- mimeType,
308
- size: stats.size,
309
- width,
310
- height,
311
- alt: manifestEntry?.alt,
312
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
313
- uploadedBy: manifestEntry?.uploadedBy,
314
- folder: resolvedFolder,
315
- tags: manifestEntry?.tags,
316
- };
301
+ const metadata = await assetMetadata.read(this.config, relativePath);
302
+ return this.assetEntry(filename, folder, stats, metadata);
317
303
  }
318
304
  /**
319
305
  * Delete asset file and manifest entry
320
306
  */
321
307
  async delete(filename, folder = '/') {
322
- // Resolve actual folder from manifest when caller only provides filename
323
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
324
- // Compute relative path for manifest
325
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
326
- // Build full file path
327
- const filePath = this.getAssetPath(filename, resolvedFolder);
308
+ // Resolve the path BEFORE the catch that forgives a missing file: a path
309
+ // that climbs out of the media library names nothing we may delete.
310
+ let assetPath;
311
+ try {
312
+ assetPath = this.getAssetPath(filename, folder);
313
+ }
314
+ catch {
315
+ return { success: false, error: 'Asset not found' };
316
+ }
317
+ try {
318
+ await assetMetadata.migrateLegacyManifest(this.config);
319
+ }
320
+ catch (err) {
321
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
322
+ }
323
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
328
324
  // Delete file from disk (ignore if already gone)
329
325
  try {
330
- await unlink(filePath);
326
+ await unlink(assetPath);
331
327
  }
332
328
  catch {
333
- // File may already be gone, continue with manifest cleanup
329
+ // File may already be gone, continue with metadata cleanup
334
330
  }
335
- // Remove manifest entry
336
- await this.manifest.remove(relativePath);
331
+ await assetMetadata.remove(this.config, relativePath);
337
332
  return { success: true };
338
333
  }
339
334
  /**
340
335
  * Import an image from a URL (server-side fetch, no CORS issues)
341
- * Validates URL against SSRF, enforces 30s timeout, and checks response size.
336
+ * Validates the URL and every redirect hop against SSRF, enforces 30s timeout,
337
+ * and checks response size.
342
338
  */
343
339
  async importFromUrl(url, metadata) {
344
340
  // Validate URL: block private IPs and non-http(s) schemes
@@ -348,12 +344,34 @@ export class AssetOperations {
348
344
  catch (err) {
349
345
  return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
350
346
  }
351
- // Fetch with 30-second timeout
347
+ // Fetch with 30-second timeout, following redirects MANUALLY so every hop's
348
+ // target runs through the SSRF guard BEFORE it is requested — otherwise a
349
+ // public URL can redirect into a loopback or link-local (cloud metadata)
350
+ // address that the initial check would have rejected.
352
351
  const controller = new AbortController();
353
352
  const timeout = setTimeout(() => controller.abort(), 30_000);
354
353
  let response;
354
+ let current = url;
355
355
  try {
356
- response = await fetch(url, { signal: controller.signal });
356
+ for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
357
+ const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
358
+ if (hopResponse.status < 300 || hopResponse.status >= 400) {
359
+ response = hopResponse;
360
+ break;
361
+ }
362
+ const location = hopResponse.headers.get('location');
363
+ if (location === null) {
364
+ return { success: false, error: 'Redirect missing Location header' };
365
+ }
366
+ try {
367
+ // A relative Location is legal and common; resolve it against the URL
368
+ // that produced it, then validate the absolute result.
369
+ current = validateFetchUrl(new URL(location, current).toString()).toString();
370
+ }
371
+ catch (err) {
372
+ return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
373
+ }
374
+ }
357
375
  }
358
376
  catch {
359
377
  return { success: false, error: 'Failed to fetch URL' };
@@ -361,6 +379,11 @@ export class AssetOperations {
361
379
  finally {
362
380
  clearTimeout(timeout);
363
381
  }
382
+ // Budget exhausted without a final response — fail closed rather than
383
+ // treating the last redirect as content
384
+ if (!response) {
385
+ return { success: false, error: 'Too many redirects' };
386
+ }
364
387
  if (!response.ok) {
365
388
  return { success: false, error: `Fetch failed with status ${response.status}` };
366
389
  }
@@ -371,8 +394,16 @@ export class AssetOperations {
371
394
  return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
372
395
  }
373
396
  const contentType = response.headers.get('content-type') || '';
374
- const urlPath = new URL(url).pathname;
375
- const urlFilename = urlPath.split('/').pop() || 'imported-image.jpg';
397
+ const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
398
+ let urlFilename = lastSegment;
399
+ try {
400
+ const decoded = decodeURIComponent(lastSegment);
401
+ if (!/\p{Cc}/u.test(decoded))
402
+ urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
403
+ }
404
+ catch {
405
+ // A malformed escape keeps the filename as written in the address.
406
+ }
376
407
  // Read response body and verify actual size
377
408
  const arrayBuffer = await response.arrayBuffer();
378
409
  if (arrayBuffer.byteLength > this.config.maxFileSize) {
@@ -388,7 +419,7 @@ export class AssetOperations {
388
419
  */
389
420
  async listFolder(subpath = '/') {
390
421
  // Normalize subpath
391
- const normalizedSubpath = subpath === '/' ? '/' : '/' + subpath.replace(/^\/+|\/+$/g, '');
422
+ const normalizedSubpath = subpath === '/' ? '/' : `/${subpath.replace(/^\/+|\/+$/g, '')}`;
392
423
  // Validate path (prevent path traversal)
393
424
  let fullPath;
394
425
  if (normalizedSubpath === '/') {
@@ -408,17 +439,16 @@ export class AssetOperations {
408
439
  }
409
440
  // Get subfolders (exclude hidden, symlinks)
410
441
  const folders = entries
411
- .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !e.isSymbolicLink())
442
+ .filter((e) => e.isDirectory() && !isSystemFile(e.name) && !e.isSymbolicLink())
412
443
  .map((e) => ({
413
444
  name: e.name,
414
445
  path: normalizedSubpath === '/' ? `/${e.name}` : `${normalizedSubpath}/${e.name}`,
415
446
  }));
416
447
  // Get image files (exclude hidden, system files, symlinks, non-images)
417
448
  const imageFiles = entries.filter((e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name));
418
- // Load manifest for enrichment
419
- const manifestData = await this.manifest.read();
449
+ const records = await assetMetadata.readFolder(this.config, normalizedSubpath);
420
450
  // Build asset entries from filesystem
421
- const assets = await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData)));
451
+ const assets = await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, records)));
422
452
  return { assets, folders };
423
453
  }
424
454
  /**
@@ -426,7 +456,7 @@ export class AssetOperations {
426
456
  * @param subpath Folder path relative to assets root
427
457
  */
428
458
  async createFolder(subpath) {
429
- if (!subpath || subpath === '/') {
459
+ if (!subpath || /^\/+$/.test(subpath)) {
430
460
  return { success: false, error: 'Cannot create root folder' };
431
461
  }
432
462
  // Validate path (prevent path traversal)
@@ -437,6 +467,16 @@ export class AssetOperations {
437
467
  catch {
438
468
  return { success: false, error: 'Invalid folder path' };
439
469
  }
470
+ const folderSegments = subpath.split('/').filter(Boolean);
471
+ if (folderSegments.some(isSystemFile)) {
472
+ return { success: false, error: "Folder names can't start with a dot or be a system file name like Thumbs.db" };
473
+ }
474
+ if (/[#?%\\]/.test(subpath)) {
475
+ return { success: false, error: "Folder names can't contain #, ?, % or \\" };
476
+ }
477
+ if (/[\t\n\r]/.test(subpath)) {
478
+ return { success: false, error: "Folder names can't contain tabs or line breaks" };
479
+ }
440
480
  try {
441
481
  await mkdir(fullPath, { recursive: true });
442
482
  return { success: true };
@@ -449,97 +489,72 @@ export class AssetOperations {
449
489
  }
450
490
  }
451
491
  /**
452
- * Update asset metadata (alt text, tags)
492
+ * Update asset metadata (alt text, tags). The merge happens inside the
493
+ * record's lock and the saved value is what comes back — the old re-read
494
+ * afterwards is how a success could report alt text another save had
495
+ * already written over.
453
496
  * @param filename Asset filename
454
497
  * @param updates Metadata updates (alt, tags)
455
498
  * @param folder Optional folder path (default '/')
456
499
  */
457
500
  async updateMetadata(filename, updates, folder = '/') {
458
- // Resolve actual folder from manifest when caller only provides filename
459
- const resolvedFolder = folder === '/' ? await this.resolveFolder(filename) : folder;
460
- // Compute relative path
461
- const relativePath = resolvedFolder === '/' ? filename : `${resolvedFolder.slice(1)}/${filename}`;
462
- // Check if file exists on disk
463
- const fullPath = this.getAssetPath(filename, resolvedFolder);
501
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
502
+ let stats;
464
503
  try {
465
- await stat(fullPath);
504
+ stats = await stat(this.getAssetPath(filename, folder));
466
505
  }
467
506
  catch {
468
- return { success: false, error: 'Asset not found' };
507
+ return { success: false, reason: 'not-found', error: 'Asset not found' };
508
+ }
509
+ let metadata;
510
+ try {
511
+ await assetMetadata.migrateLegacyManifest(this.config);
512
+ metadata = await assetMetadata.update(this.config, relativePath, updates);
469
513
  }
470
- // Get existing manifest entry
471
- const manifestData = await this.manifest.read();
472
- const existing = manifestData[relativePath] || {};
473
- // Merge updates
474
- const merged = { ...existing, ...updates };
475
- // Write back to manifest
476
- await this.manifest.add(relativePath, merged);
477
- // Return updated asset entry
478
- const asset = await this.getAsset(filename, resolvedFolder);
479
- if (!asset) {
480
- return { success: false, error: 'Failed to retrieve updated asset' };
481
- }
482
- return { success: true, asset };
514
+ catch (err) {
515
+ return {
516
+ success: false,
517
+ reason: 'write-failed',
518
+ error: err instanceof Error ? err.message : 'Failed to save asset metadata',
519
+ };
520
+ }
521
+ return { success: true, asset: await this.assetEntry(filename, folder, stats, metadata) };
483
522
  }
484
523
  /**
485
524
  * Get usage information for an asset (which pages reference it)
486
525
  * @param filename Asset filename
487
526
  */
488
527
  async getUsage(filename) {
489
- if (!this.config.contentRoot) {
490
- return [];
491
- }
492
528
  const usages = [];
493
529
  // Search patterns for the asset
494
530
  const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];
495
- // Recursively walk the content directory to find all .vxjson files
496
- const walkDir = async (dir) => {
497
- const files = [];
498
- let entries;
531
+ const files = await vxjsonFiles(this.config.contentRoot);
532
+ // Promise.all preserves `files` order while avoiding serial disk reads.
533
+ const documents = await Promise.all(files.map(async (filePath) => {
499
534
  try {
500
- entries = await readdir(dir, { withFileTypes: true });
535
+ return { filePath, content: await readFile(filePath, 'utf-8') };
501
536
  }
502
537
  catch {
503
- return files;
538
+ return null;
504
539
  }
505
- for (const entry of entries) {
506
- const fullPath = join(dir, entry.name);
507
- if (entry.isDirectory() && !entry.name.startsWith('.')) {
508
- files.push(...(await walkDir(fullPath)));
509
- }
510
- else if (entry.isFile() && entry.name.endsWith('.vxjson')) {
511
- files.push(fullPath);
512
- }
513
- }
514
- return files;
515
- };
516
- const vxjsonFiles = await walkDir(this.config.contentRoot);
517
- for (const filePath of vxjsonFiles) {
540
+ }));
541
+ for (const document of documents) {
542
+ if (document === null)
543
+ continue;
544
+ const { filePath, content } = document;
545
+ if (!searchPatterns.some((pattern) => content.includes(pattern)))
546
+ continue;
547
+ const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\]/, '');
548
+ const pageName = relativePath.replace(/\.vxjson$/, '');
549
+ let field = 'content';
518
550
  try {
519
- const content = await readFile(filePath, 'utf-8');
520
- // Check if any search pattern is found in the file content
521
- const found = searchPatterns.some((pattern) => content.includes(pattern));
522
- if (found) {
523
- // Extract page name from file path (remove .vxjson extension)
524
- const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\]/, '');
525
- const pageName = relativePath.replace(/\.vxjson$/, '');
526
- // Try to identify which field contains the reference
527
- // Simple approach: look for the pattern in JSON structure
528
- let field = 'unknown';
529
- try {
530
- const json = JSON.parse(content);
531
- field = this.findFieldWithAsset(json, searchPatterns) || 'content';
532
- }
533
- catch {
534
- // If JSON parsing fails, just mark as content
535
- field = 'content';
536
- }
537
- usages.push({ page: pageName, field });
538
- }
551
+ const json = JSON.parse(content);
552
+ field = this.findFieldWithAsset(json, searchPatterns) || 'content';
539
553
  }
540
554
  catch {
541
- // Skip files that can't be read
555
+ // An unreadable JSON document can still be reported by its text match.
542
556
  }
557
+ usages.push({ page: pageName, field });
543
558
  }
544
559
  return usages;
545
560
  }
@@ -559,11 +574,16 @@ export class AssetOperations {
559
574
  * @param folder Optional folder path (default '/')
560
575
  */
561
576
  async readAssetFile(filename, folder = '/') {
577
+ // Serve images only: the metadata records live under the same tree and are
578
+ // nobody's business, and neither is any other file that lands in there.
579
+ if (!isRecognizedImageExtension(filename)) {
580
+ return { success: false, error: 'Asset not found' };
581
+ }
562
582
  // Build path from folder + filename
563
583
  const filePath = this.getAssetPath(filename, folder);
564
- // Derive mimeType from extension (don't require manifest entry)
584
+ // Derive mimeType from extension (don't require a metadata record)
565
585
  const ext = extname(filename).slice(1).toLowerCase();
566
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
586
+ const mimeType = IMAGE_EXTENSION_MIME[ext] || `image/${ext}`;
567
587
  try {
568
588
  const buffer = await readFile(filePath);
569
589
  return { success: true, buffer, mimeType };
@@ -607,8 +627,8 @@ export class AssetOperations {
607
627
  */
608
628
  async moveAssets(filenames, sourceFolder, targetFolder) {
609
629
  // Normalize folder paths
610
- const normalizedSource = sourceFolder === '/' ? '/' : '/' + sourceFolder.replace(/^\/+|\/+$/g, '');
611
- const normalizedTarget = targetFolder === '/' ? '/' : '/' + targetFolder.replace(/^\/+|\/+$/g, '');
630
+ const normalizedSource = sourceFolder === '/' ? '/' : `/${sourceFolder.replace(/^\/+|\/+$/g, '')}`;
631
+ const normalizedTarget = targetFolder === '/' ? '/' : `/${targetFolder.replace(/^\/+|\/+$/g, '')}`;
612
632
  // Validate both folders exist (for non-root folders)
613
633
  let sourcePath;
614
634
  let targetPath;
@@ -619,6 +639,14 @@ export class AssetOperations {
619
639
  catch {
620
640
  return { success: false, error: 'Invalid folder path' };
621
641
  }
642
+ // Each name is joined onto both folders, so one with a separator or `..` would reach outside them
643
+ if (!filenames.every(isBareFilename)) {
644
+ return { success: false, error: 'Invalid filename' };
645
+ }
646
+ // The listing hides system files, and moving the folder's own manifest would drop every asset's metadata
647
+ if (filenames.some(isSystemFile)) {
648
+ return { success: false, error: 'Invalid filename' };
649
+ }
622
650
  // Verify source folder exists
623
651
  try {
624
652
  const sourceStat = await stat(sourcePath);
@@ -639,35 +667,54 @@ export class AssetOperations {
639
667
  catch {
640
668
  return { success: false, error: 'Target folder does not exist' };
641
669
  }
642
- // Move files on disk first, collect successful moves
643
- const moves = [];
670
+ if (normalizedSource === normalizedTarget)
671
+ return { success: true, moved: 0 };
672
+ const found = await Promise.all(filenames.map((filename) => lstat(join(sourcePath, filename)).catch(() => null)));
673
+ const notFiles = filenames.filter((_, index) => found[index]?.isFile() === false);
674
+ if (notFiles.length > 0)
675
+ return { success: false, error: `Not a file: ${notFiles.join(', ')}` };
676
+ const taken = new Set((await readdir(targetPath)).map((name) => name.toLowerCase()));
677
+ const conflicts = filenames.filter((filename) => taken.has(filename.toLowerCase()));
678
+ if (conflicts.length > 0) {
679
+ return { success: false, error: `Already in the target folder: ${conflicts.join(', ')}` };
680
+ }
681
+ try {
682
+ await assetMetadata.migrateLegacyManifest(this.config);
683
+ }
684
+ catch (err) {
685
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
686
+ }
687
+ // Move each file with its own record, so one failure cannot take the rest
688
+ // of the folder's metadata with it
689
+ let moved = 0;
644
690
  for (const filename of filenames) {
645
- const sourceFile = join(sourcePath, filename);
646
- const targetFile = join(targetPath, filename);
647
691
  const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
648
692
  const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
693
+ // Both folders are checked above, but the names come straight off the
694
+ // request and a name is free to carry `../` of its own
695
+ let from;
696
+ let to;
697
+ try {
698
+ from = this.getAssetPath(filename, normalizedSource);
699
+ to = this.getAssetPath(filename, normalizedTarget);
700
+ }
701
+ catch {
702
+ console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
703
+ continue;
704
+ }
649
705
  try {
650
- await rename(sourceFile, targetFile);
651
- moves.push({ oldPath: oldRelativePath, newPath: newRelativePath });
706
+ // oxlint-disable-next-line no-await-in-loop -- each move is committed before its metadata follows; partial failure stays attributable to one filename.
707
+ await rename(from, to);
652
708
  }
653
709
  catch (err) {
654
710
  console.error(`[AssetOperations] Failed to move ${filename}:`, err);
711
+ continue;
655
712
  }
713
+ // oxlint-disable-next-line no-await-in-loop -- metadata must follow the file that just moved before the next file starts.
714
+ await assetMetadata.move(this.config, oldRelativePath, newRelativePath);
715
+ moved += 1;
656
716
  }
657
- // Single atomic manifest update for all moves (1 read + 1 write)
658
- if (moves.length > 0) {
659
- await this.manifest.withManifest((data) => {
660
- for (const { oldPath, newPath } of moves) {
661
- const entry = data[oldPath];
662
- if (entry) {
663
- delete data[oldPath];
664
- data[newPath] = entry;
665
- }
666
- }
667
- return data;
668
- });
669
- }
670
- return { success: true, moved: moves.length };
717
+ return { success: true, moved };
671
718
  }
672
719
  /**
673
720
  * Get the complete folder tree with asset counts
@@ -734,3 +781,4 @@ export class AssetOperations {
734
781
  ];
735
782
  }
736
783
  }
784
+ //# sourceMappingURL=asset-operations.js.map