@conloca/content-api 0.2.3 → 0.2.5

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 (103) hide show
  1. package/dist/.build-inputs.json +22 -11
  2. package/dist/asset-constraints.d.ts +9 -1
  3. package/dist/asset-constraints.d.ts.map +1 -1
  4. package/dist/asset-constraints.js +10 -2
  5. package/dist/asset-constraints.js.map +1 -1
  6. package/dist/asset-metadata-record.d.ts +18 -0
  7. package/dist/asset-metadata-record.d.ts.map +1 -0
  8. package/dist/asset-metadata-record.js +59 -0
  9. package/dist/asset-metadata-record.js.map +1 -0
  10. package/dist/asset-metadata-store.d.ts.map +1 -1
  11. package/dist/asset-metadata-store.js +7 -26
  12. package/dist/asset-metadata-store.js.map +1 -1
  13. package/dist/asset-naming.d.ts +39 -0
  14. package/dist/asset-naming.d.ts.map +1 -0
  15. package/dist/asset-naming.js +123 -0
  16. package/dist/asset-naming.js.map +1 -0
  17. package/dist/asset-operations.d.ts +3 -5
  18. package/dist/asset-operations.d.ts.map +1 -1
  19. package/dist/asset-operations.js +99 -90
  20. package/dist/asset-operations.js.map +1 -1
  21. package/dist/asset-types.d.ts +2 -0
  22. package/dist/asset-types.d.ts.map +1 -1
  23. package/dist/asset-usage.d.ts +8 -1
  24. package/dist/asset-usage.d.ts.map +1 -1
  25. package/dist/asset-usage.js +4 -1
  26. package/dist/asset-usage.js.map +1 -1
  27. package/dist/draft-media-ref.d.ts +9 -0
  28. package/dist/draft-media-ref.d.ts.map +1 -0
  29. package/dist/draft-media-ref.js +47 -0
  30. package/dist/draft-media-ref.js.map +1 -0
  31. package/dist/editor-host.d.ts +53 -0
  32. package/dist/editor-host.d.ts.map +1 -1
  33. package/dist/editor-host.js +92 -0
  34. package/dist/editor-host.js.map +1 -1
  35. package/dist/git-operations.d.ts +0 -5
  36. package/dist/git-operations.d.ts.map +1 -1
  37. package/dist/git-operations.js +1 -33
  38. package/dist/git-operations.js.map +1 -1
  39. package/dist/image-format.d.ts +9 -0
  40. package/dist/image-format.d.ts.map +1 -0
  41. package/dist/image-format.js +100 -0
  42. package/dist/image-format.js.map +1 -0
  43. package/dist/image-metadata.d.ts +11 -0
  44. package/dist/image-metadata.d.ts.map +1 -0
  45. package/dist/image-metadata.js +283 -0
  46. package/dist/image-metadata.js.map +1 -0
  47. package/dist/image-shrink.d.ts +15 -0
  48. package/dist/image-shrink.d.ts.map +1 -0
  49. package/dist/image-shrink.js +52 -0
  50. package/dist/image-shrink.js.map +1 -0
  51. package/dist/index.d.ts +7 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +14 -3
  54. package/dist/index.js.map +1 -1
  55. package/dist/lfs-attributes.d.ts +26 -0
  56. package/dist/lfs-attributes.d.ts.map +1 -0
  57. package/dist/lfs-attributes.js +285 -0
  58. package/dist/lfs-attributes.js.map +1 -0
  59. package/dist/skill-stamp.d.ts +10 -0
  60. package/dist/skill-stamp.d.ts.map +1 -0
  61. package/dist/skill-stamp.js +42 -0
  62. package/dist/skill-stamp.js.map +1 -0
  63. package/dist/svg-sanitize.d.ts +8 -0
  64. package/dist/svg-sanitize.d.ts.map +1 -0
  65. package/dist/svg-sanitize.js +260 -0
  66. package/dist/svg-sanitize.js.map +1 -0
  67. package/dist/types.d.ts +7 -0
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/upload-bytes.d.ts +17 -0
  70. package/dist/upload-bytes.d.ts.map +1 -0
  71. package/dist/upload-bytes.js +43 -0
  72. package/dist/upload-bytes.js.map +1 -0
  73. package/dist/upload-refusals.d.ts +24 -0
  74. package/dist/upload-refusals.d.ts.map +1 -0
  75. package/dist/upload-refusals.js +49 -0
  76. package/dist/upload-refusals.js.map +1 -0
  77. package/dist/vxjson-serialize.js +2 -2
  78. package/dist/vxjson-serialize.js.map +1 -1
  79. package/dist/vxjson.js +1 -1
  80. package/dist/vxjson.js.map +1 -1
  81. package/package.json +45 -7
  82. package/src/asset-constraints.ts +14 -2
  83. package/src/asset-metadata-record.ts +57 -0
  84. package/src/asset-metadata-store.ts +12 -21
  85. package/src/asset-naming.ts +120 -0
  86. package/src/asset-operations.ts +108 -91
  87. package/src/asset-types.ts +2 -0
  88. package/src/asset-usage.ts +16 -2
  89. package/src/draft-media-ref.ts +46 -0
  90. package/src/editor-host.ts +117 -1
  91. package/src/git-operations.ts +1 -38
  92. package/src/image-format.ts +87 -0
  93. package/src/image-metadata.ts +266 -0
  94. package/src/image-shrink.ts +57 -0
  95. package/src/index.ts +45 -3
  96. package/src/lfs-attributes.ts +291 -0
  97. package/src/skill-stamp.ts +45 -0
  98. package/src/svg-sanitize.ts +260 -0
  99. package/src/types.ts +7 -0
  100. package/src/upload-bytes.ts +46 -0
  101. package/src/upload-refusals.ts +59 -0
  102. package/src/vxjson-serialize.ts +2 -2
  103. package/src/vxjson.ts +1 -1
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The one naming rule for uploads, in every editor and on every server: the file name a picture is stored under, the
3
+ * suffix a taken name gets, and the folder names git and a stored link can hold. Pure strings: the browser entry
4
+ * re-exports them.
5
+ */
6
+
7
+ /** Names Windows reserves for devices: a file or folder named like this, with any extension, cannot be checked out. */
8
+ const WINDOWS_DEVICE_NAME = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;
9
+
10
+ /** True when the part of `name` before its first dot is a Windows device name. */
11
+ function isWindowsDeviceName(name: string): boolean {
12
+ return WINDOWS_DEVICE_NAME.test(name.split('.', 1)[0] ?? '');
13
+ }
14
+
15
+ /**
16
+ * Sanitize an uploaded filename: split accented and fullwidth letters into their plain Latin base (`é` keeps its `e`
17
+ * in either Unicode form), lowercase, spaces→`-`, drop chars outside `[a-z0-9._-]`, then leading dots, so a name
18
+ * never becomes a hidden dot-file (`.config.png` → `config.png`), and keep the first 200 characters, so a long name
19
+ * alone cannot push a storage key past its limit. A name left with no Latin letter or digit (only non-Latin words and
20
+ * dashes, say) becomes `file`.
21
+ */
22
+ export function safeAssetFilename(name: string): string {
23
+ // Split after the Unicode split, so a fullwidth dot parts the extension off as a plain one does
24
+ const normalized = name.normalize('NFKD');
25
+ const dot = normalized.lastIndexOf('.');
26
+ const hasExt = dot > 0 && dot < normalized.length - 1;
27
+ const base = hasExt ? normalized.slice(0, dot) : normalized;
28
+ const ext = hasExt ? normalized.slice(dot + 1) : '';
29
+ const cleanBase = base
30
+ .toLowerCase()
31
+ .replace(/\s+/g, '-')
32
+ .replace(/[^a-z0-9._-]/g, '')
33
+ .replace(/^\.+/, '')
34
+ .slice(0, 200);
35
+ const cleanExt = ext.toLowerCase().replace(/[^a-z0-9]/g, '');
36
+ const safeBase = /[a-z0-9]/.test(cleanBase) ? cleanBase : 'file';
37
+ return cleanExt === '' ? safeBase : `${safeBase}.${cleanExt}`;
38
+ }
39
+
40
+ /** Insert a `-n` collision suffix before the extension: `photo.png` → `photo-1.png`. */
41
+ export function withNumberSuffix(filename: string, n: number): string {
42
+ const dot = filename.lastIndexOf('.');
43
+ if (dot <= 0) return `${filename}-${n}`;
44
+ return `${filename.slice(0, dot)}-${n}${filename.slice(dot)}`;
45
+ }
46
+
47
+ /**
48
+ * `name`, or the first `-n` variant of it, that is free: its lowercase is not in `taken` (lowercased names), so
49
+ * `Hero.webp` takes `hero.webp` on a case-insensitive checkout, and it is not a Windows device name. A device name
50
+ * gets its suffix before its first dot, the part Windows reads (`aux.tar.png` → `aux-1.tar.png`).
51
+ */
52
+ export function uniqueAssetName(name: string, taken: ReadonlySet<string>): string {
53
+ const device = isWindowsDeviceName(name);
54
+ if (!device && !taken.has(name.toLowerCase())) return name;
55
+ const dot = name.indexOf('.');
56
+ const [base, rest] = dot === -1 ? [name, ''] : [name.slice(0, dot), name.slice(dot)];
57
+ for (let n = 1; ; n += 1) {
58
+ const candidate = device ? `${base}-${n}${rest}` : withNumberSuffix(name, n);
59
+ if (!taken.has(candidate.toLowerCase())) return candidate;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Characters a folder name may not hold: whitespace and control characters, and the characters that end a stored
65
+ * `/assets/...` link or that Windows cannot hold in a name.
66
+ */
67
+ const FOLDER_NAME_FORBIDDEN = /[\s\p{Cc}"'()<>`\\?#&%*:|]/u;
68
+
69
+ /**
70
+ * Why `path` (folders below the media folder, `/`-separated, `''` for the media folder itself) cannot hold new
71
+ * media, as a sentence naming the folder and the rule; `null` when it can. Each folder name must be one git can
72
+ * check out on every system and one a stored image link keeps whole.
73
+ */
74
+ export function folderPathError(path: string): string | null {
75
+ if (path === '') return null;
76
+ for (const segment of path.split('/')) {
77
+ if (segment === '') return `The folder path "${path}" has an empty folder name between two slashes.`;
78
+ if (segment === '.' || segment === '..') return `"${segment}" cannot be a folder name.`;
79
+ if (/^(\.git|git~1)$/i.test(segment)) return `"${segment}" is reserved by Git and cannot be a folder name.`;
80
+ if (segment.startsWith('.')) return `The folder name "${segment}" cannot start with a dot.`;
81
+ if (/[. ]$/.test(segment)) return `The folder name "${segment}" cannot end with a dot or a space.`;
82
+ if (isWindowsDeviceName(segment)) {
83
+ return `"${segment}" is a name Windows reserves for a device and cannot be a folder name.`;
84
+ }
85
+ if (FOLDER_NAME_FORBIDDEN.test(segment)) {
86
+ return `The folder name "${segment}" cannot hold spaces, line breaks or any of " ' ( ) < > \` \\ ? # & % * : |.`;
87
+ }
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * Why a new folder `name` cannot sit beside `siblings` (the folders already in its parent): one of them differs from it
94
+ * only in case, and Mac and Windows would check both out as one folder. `null` when none does.
95
+ */
96
+ export function folderCaseClashError(name: string, siblings: Iterable<string>): string | null {
97
+ for (const sibling of siblings) {
98
+ if (sibling !== name && sibling.toLowerCase() === name.toLowerCase()) {
99
+ return `The folder "${sibling}" already exists, and "${name}" differs from it only in capital letters, which Mac and Windows treat as the same folder.`;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * The name of the file an import URL points at: its decoded last path part, and of that only what follows the last
107
+ * decoded slash or backslash, so no folder of the remote site shows in the media library. A part whose decoding would
108
+ * hold a control character, invisible in the library, or that does not decode, stays as written in the address.
109
+ */
110
+ export function fileNameFromUrl(url: URL): string {
111
+ const lastPart = url.pathname.split('/').pop() || 'import';
112
+ let decoded: string;
113
+ try {
114
+ decoded = decodeURIComponent(lastPart);
115
+ } catch {
116
+ return lastPart;
117
+ }
118
+ if (/\p{Cc}/u.test(decoded)) return lastPart;
119
+ return decoded.split(/[/\\]/).pop() || lastPart;
120
+ }
@@ -11,13 +11,33 @@ import {
11
11
  unlink,
12
12
  writeFile,
13
13
  } from 'node:fs/promises';
14
- import { basename, dirname, extname, join, parse, resolve, sep } from 'node:path';
14
+ import { basename, dirname, extname, join, resolve, sep } from 'node:path';
15
15
  import { pipeline } from 'node:stream/promises';
16
16
  import { imageSizeFromFile } from 'image-size/fromFile';
17
- import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
17
+ import {
18
+ DEFAULT_ACCEPTED_FORMATS,
19
+ DEFAULT_MAX_FILE_SIZE,
20
+ IMAGE_EXTENSION_MIME,
21
+ VIDEO_EXTENSIONS,
22
+ } from './asset-constraints.js';
18
23
  import * as assetMetadata from './asset-metadata-store.js';
24
+ import {
25
+ fileNameFromUrl,
26
+ folderCaseClashError,
27
+ folderPathError,
28
+ safeAssetFilename,
29
+ uniqueAssetName,
30
+ } from './asset-naming.js';
19
31
  import type { AssetEntry, AssetMetadata, AssetMetadataPatch, FolderListing, FolderTreeNode } from './asset-types.js';
20
- import { setupGitLfsAttributes } from './git-operations.js';
32
+ import { shrinkImage } from './image-shrink.js';
33
+ import { conformUploadBytes } from './upload-bytes.js';
34
+ import {
35
+ importRefusal,
36
+ importTooLargeRefusal,
37
+ tooLargeRefusal,
38
+ unsupportedTypeRefusal,
39
+ videoRefusal,
40
+ } from './upload-refusals.js';
21
41
  import { validateFetchUrl } from './url-validation.js';
22
42
 
23
43
  export interface AssetConfig {
@@ -41,6 +61,18 @@ const MAX_IMPORT_REDIRECTS = 5;
41
61
 
42
62
  const DEFAULT_IMPORT_TIMEOUT_MS = 30_000;
43
63
 
64
+ /** Why an import may not request `url`, in words for the person importing, or `null` when it may. */
65
+ function fetchUrlProblem(url: string): string | null {
66
+ try {
67
+ validateFetchUrl(url);
68
+ return null;
69
+ } catch {
70
+ // It throws for a malformed or non-web address, and otherwise for a private host.
71
+ const web = URL.canParse(url) && /^https?:$/.test(new URL(url).protocol);
72
+ return web ? 'it points to a private network' : 'the address is not a web address';
73
+ }
74
+ }
75
+
44
76
  /** Check if filename has a recognized web image extension */
45
77
  function isRecognizedImageExtension(filename: string): boolean {
46
78
  const ext = extname(filename).slice(1).toLowerCase();
@@ -65,7 +97,6 @@ function isBareFilename(filename: unknown): boolean {
65
97
  export class AssetOperations {
66
98
  private config: Required<AssetConfig>;
67
99
  private dirEnsured = false;
68
- private lfsSetup = false;
69
100
 
70
101
  constructor(config: AssetConfig) {
71
102
  this.config = {
@@ -107,44 +138,16 @@ export class AssetOperations {
107
138
  }
108
139
 
109
140
  /**
110
- * Resolve a unique filename by appending -1, -2, etc. if collision exists
111
- * @param originalName Original filename
112
- * @param folder Optional folder path (relative to assets root)
141
+ * The lowercased names already in an assets folder (`/` for the assets root), so a new name clashes with any case of
142
+ * them; none when the folder does not exist yet. Broken symlinks count too.
113
143
  */
114
- private async resolveFilename(originalName: string, folder?: string): Promise<string> {
115
- const { name, ext } = parse(originalName);
116
- // Normalize compatibility forms and accents before restricting the stored filename.
117
- const cleaned = name
118
- .normalize('NFKD')
119
- .toLowerCase()
120
- .replace(/\s+/g, '-')
121
- .replace(/[^a-z0-9-]/g, '')
122
- .slice(0, 200);
123
- const sanitized = /[a-z0-9]/.test(cleaned) ? cleaned : 'file';
124
- const safeExt = ext.toLowerCase();
125
-
126
- // Determine base directory (assetsPath or assetsPath/folder)
127
- const baseDir =
128
- folder && folder !== '/'
129
- ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, ''))
130
- : this.config.assetsPath;
131
-
132
- let candidate = `${sanitized}${safeExt}`;
133
- let counter = 0;
134
-
135
- // eslint-disable-next-line no-constant-condition
136
- while (true) {
137
- try {
138
- // lstat also reserves the name of a broken symlink.
139
- await lstat(join(baseDir, candidate));
140
- counter++;
141
- candidate = `${sanitized}-${counter}${safeExt}`;
142
- } catch {
143
- break;
144
- }
144
+ private async takenNames(folder: string): Promise<Set<string>> {
145
+ const dir = folder === '/' ? this.config.assetsPath : join(this.config.assetsPath, folder.slice(1));
146
+ try {
147
+ return new Set((await readdir(dir)).map((name) => name.toLowerCase()));
148
+ } catch {
149
+ return new Set();
145
150
  }
146
-
147
- return candidate;
148
151
  }
149
152
 
150
153
  private validateFormat(filename: string): boolean {
@@ -213,14 +216,25 @@ export class AssetOperations {
213
216
  file: File,
214
217
  metadata?: { alt?: string; uploadedBy?: string; folder?: string },
215
218
  ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {
219
+ if (VIDEO_EXTENSIONS.has(extname(file.name).slice(1).toLowerCase()) || file.type.startsWith('video/')) {
220
+ return { success: false, error: videoRefusal(file.name) };
221
+ }
216
222
  if (!this.validateFormat(file.name)) {
217
- const allowed = this.config.acceptedFormats.join(', ');
218
- return { success: false, error: `Invalid format. Accepted: ${allowed}` };
223
+ return { success: false, error: unsupportedTypeRefusal(file.name, this.config.acceptedFormats) };
219
224
  }
220
225
 
221
- if (!this.validateSize(file.size)) {
222
- const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
223
- return { success: false, error: `File too large. Maximum: ${maxMB}MB` };
226
+ const shrunk = await shrinkImage(new Uint8Array(await file.arrayBuffer()), file.name, this.config.acceptedFormats);
227
+ if ('refusal' in shrunk) return { success: false, error: shrunk.refusal };
228
+ if (shrunk.warning !== undefined) console.warn(shrunk.warning);
229
+ const conformed = conformUploadBytes(shrunk.bytes, shrunk.filename);
230
+ if (!conformed.ok) return { success: false, error: conformed.refusal };
231
+ // The bytes may hold another format than the name said; a site's own acceptedFormats still decides.
232
+ if (!this.validateFormat(conformed.filename)) {
233
+ return { success: false, error: unsupportedTypeRefusal(conformed.filename, this.config.acceptedFormats) };
234
+ }
235
+ const data = conformed.bytes;
236
+ if (!this.validateSize(data.byteLength)) {
237
+ return { success: false, error: tooLargeRefusal(file.name, data.byteLength, this.config.maxFileSize) };
224
238
  }
225
239
 
226
240
  // Normalize folder path
@@ -228,11 +242,19 @@ export class AssetOperations {
228
242
 
229
243
  // Validate folder path (prevent path traversal)
230
244
  if (folder !== '/') {
245
+ let folderPath: string;
231
246
  try {
232
- this.validateSubpath(folder);
247
+ folderPath = this.validateSubpath(folder);
233
248
  } catch {
234
249
  return { success: false, error: 'Invalid folder path' };
235
250
  }
251
+ // Only a new folder has to follow the folder rule: uploads into a folder a site already has keep working.
252
+ const exists = await stat(folderPath).then(
253
+ (stats) => stats.isDirectory(),
254
+ () => false,
255
+ );
256
+ const folderError = exists ? null : folderPathError(folder.slice(1));
257
+ if (folderError !== null) return { success: false, error: folderError };
236
258
  }
237
259
 
238
260
  try {
@@ -248,16 +270,12 @@ export class AssetOperations {
248
270
  await this.ensureDir(folder.replace(/^\//, ''));
249
271
  }
250
272
 
251
- if (!this.lfsSetup) {
252
- await setupGitLfsAttributes(this.config.assetsPath);
253
- this.lfsSetup = true;
254
- }
255
-
256
- const data = new Uint8Array(await file.arrayBuffer());
273
+ const sanitized = safeAssetFilename(conformed.filename);
274
+ const taken = await this.takenNames(folder);
257
275
  let filename: string;
258
276
  let filePath: string;
259
277
  for (;;) {
260
- filename = await this.resolveFilename(file.name, folder);
278
+ filename = uniqueAssetName(sanitized, taken);
261
279
  filePath = this.getAssetPath(filename, folder);
262
280
  try {
263
281
  // oxlint-disable-next-line no-await-in-loop -- each exclusive create depends on the filename collision found by the preceding attempt.
@@ -265,6 +283,7 @@ export class AssetOperations {
265
283
  break;
266
284
  } catch (error) {
267
285
  if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
286
+ taken.add(filename.toLowerCase());
268
287
  }
269
288
  }
270
289
 
@@ -291,7 +310,7 @@ export class AssetOperations {
291
310
  filename,
292
311
  originalName: file.name,
293
312
  mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
294
- size: file.size,
313
+ size: data.byteLength,
295
314
  width,
296
315
  height,
297
316
  alt: metadata?.alt,
@@ -404,12 +423,14 @@ export class AssetOperations {
404
423
  url: string,
405
424
  metadata?: { alt?: string; uploadedBy?: string; folder?: string },
406
425
  ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {
407
- // Validate URL: block private IPs and non-http(s) schemes
408
- try {
409
- validateFetchUrl(url);
410
- } catch (err) {
411
- return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
412
- }
426
+ const blocked = fetchUrlProblem(url);
427
+ if (blocked !== null) return { success: false, error: importRefusal(blocked) };
428
+ const timedOut = {
429
+ success: false as const,
430
+ error: importRefusal(`it took longer than ${Math.ceil(this.config.importTimeoutMs / 1000)} seconds`),
431
+ };
432
+ const unreachable = { success: false as const, error: importRefusal('the site could not be reached') };
433
+ const tooLarge = { success: false as const, error: importTooLargeRefusal(this.config.maxFileSize) };
413
434
 
414
435
  // One wall-clock budget covers every hop AND the body read: a server that
415
436
  // sends headers promptly and then trickles bytes must not hold the import
@@ -433,32 +454,28 @@ export class AssetOperations {
433
454
  await hopResponse.body?.cancel().catch(() => {});
434
455
  const location = hopResponse.headers.get('location');
435
456
  if (location === null) {
436
- return { success: false, error: 'Redirect missing Location header' };
437
- }
438
- try {
439
- // A relative Location is legal and common; resolve it against the URL
440
- // that produced it, then validate the absolute result.
441
- current = validateFetchUrl(new URL(location, current).toString()).toString();
442
- } catch (err) {
443
- return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
457
+ return { success: false, error: importRefusal('the site redirected without saying where to') };
444
458
  }
459
+ // A relative Location is legal and common; resolve it against the URL
460
+ // that produced it, then validate the absolute result.
461
+ const next = new URL(location, current).toString();
462
+ const hopBlocked = fetchUrlProblem(next);
463
+ if (hopBlocked !== null) return { success: false, error: importRefusal(hopBlocked) };
464
+ current = next;
445
465
  }
446
466
  } catch {
447
- return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
467
+ return controller.signal.aborted ? timedOut : unreachable;
448
468
  }
449
469
 
450
470
  // Budget exhausted without a final response — fail closed rather than
451
471
  // treating the last redirect as content
452
472
  if (!response) {
453
- return { success: false, error: 'Too many redirects' };
473
+ return { success: false, error: importRefusal('it redirected too many times') };
454
474
  }
455
475
 
456
- const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
457
- const tooLarge = { success: false as const, error: `Remote file too large. Maximum: ${maxMB}MB` };
458
-
459
476
  if (!response.ok) {
460
477
  await response.body?.cancel().catch(() => {});
461
- return { success: false, error: `Fetch failed with status ${response.status}` };
478
+ return { success: false, error: importRefusal(`the site answered ${response.status}`) };
462
479
  }
463
480
 
464
481
  // Early size check from Content-Length header
@@ -469,14 +486,7 @@ export class AssetOperations {
469
486
  }
470
487
 
471
488
  const contentType = response.headers.get('content-type') || '';
472
- const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
473
- let urlFilename = lastSegment;
474
- try {
475
- const decoded = decodeURIComponent(lastSegment);
476
- if (!/\p{Cc}/u.test(decoded)) urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
477
- } catch {
478
- // A malformed escape keeps the filename as written in the address.
479
- }
489
+ const urlFilename = fileNameFromUrl(new URL(url));
480
490
 
481
491
  // Stream the body, stopping the moment it passes the limit: Content-Length
482
492
  // is optional and may lie, so it cannot be trusted to bound memory.
@@ -490,7 +500,7 @@ export class AssetOperations {
490
500
  try {
491
501
  while (true) {
492
502
  const { done, value } = await reader.read();
493
- if (controller.signal.aborted) return { success: false, error: 'URL import timed out' };
503
+ if (controller.signal.aborted) return timedOut;
494
504
  if (done) break;
495
505
  received += value.byteLength;
496
506
  if (received > this.config.maxFileSize) {
@@ -501,7 +511,7 @@ export class AssetOperations {
501
511
  }
502
512
  } catch {
503
513
  await reader.cancel().catch(() => {});
504
- return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
514
+ return controller.signal.aborted ? timedOut : unreachable;
505
515
  } finally {
506
516
  controller.signal.removeEventListener('abort', onAbort);
507
517
  }
@@ -586,15 +596,22 @@ export class AssetOperations {
586
596
  return { success: false, error: 'Invalid folder path' };
587
597
  }
588
598
 
589
- const folderSegments = subpath.split('/').filter(Boolean);
590
- if (folderSegments.some(isSystemFile)) {
599
+ const folderError = folderPathError(subpath.replace(/^\/+|\/+$/g, ''));
600
+ if (folderError !== null) return { success: false, error: folderError };
601
+ // The media library hides these names, so a folder named like one would vanish from it.
602
+ if (subpath.split('/').some(isSystemFile)) {
591
603
  return { success: false, error: "Folder names can't start with a dot or be a system file name like Thumbs.db" };
592
604
  }
593
- if (/[#?%\\]/.test(subpath)) {
594
- return { success: false, error: "Folder names can't contain #, ?, % or \\" };
595
- }
596
- if (/[\t\n\r]/.test(subpath)) {
597
- return { success: false, error: "Folder names can't contain tabs or line breaks" };
605
+ // Walk down the folders that exist: a name another one holds in another case would merge with it on Mac and Windows.
606
+ let parent = this.config.assetsPath;
607
+ for (const name of subpath.replace(/^\/+|\/+$/g, '').split('/')) {
608
+ // oxlint-disable-next-line no-await-in-loop -- each level is read only once the one above it exists.
609
+ const siblings = await readdir(parent, { withFileTypes: true }).catch(() => []);
610
+ const folders = siblings.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
611
+ const clash = folderCaseClashError(name, folders);
612
+ if (clash !== null) return { success: false, error: clash };
613
+ if (!folders.includes(name)) break;
614
+ parent = join(parent, name);
598
615
  }
599
616
 
600
617
  try {
@@ -27,6 +27,8 @@ export interface AssetEntry {
27
27
  folder?: string;
28
28
  /** Tags for categorization/filtering */
29
29
  tags?: string[];
30
+ /** The link a pick stores, when the backend serves this image from somewhere other than the image folder. */
31
+ ref?: string;
30
32
  }
31
33
 
32
34
  /** Asset usage reference - tracks where an asset is used */
@@ -1,5 +1,13 @@
1
1
  import type { AssetUsage } from './asset-types.js';
2
2
  import type { ContentAPI } from './content-api.interface.js';
3
+ import type { ContentManifest } from './types.js';
4
+
5
+ /** What the usage scan reads: the sites, each entry language, and a listing that may arrive asynchronously. */
6
+ export interface AssetUsageSource {
7
+ sitesConfig: ContentAPI['sitesConfig'];
8
+ getLocalized: ContentAPI['getLocalized'];
9
+ listAllContent(): Iterable<ContentManifest> | AsyncIterable<ContentManifest>;
10
+ }
3
11
 
4
12
  /**
5
13
  * Every page, fragment and data entry language whose meta or content links to an asset. The editor
@@ -8,13 +16,19 @@ import type { ContentAPI } from './content-api.interface.js';
8
16
  * `/assets/beach.png.bak`. A full URL such as `https://…/assets/beach.png` never counts, even one to this
9
17
  * site, whose address is not known here.
10
18
  */
11
- export async function findAssetUsage(api: ContentAPI, path: string, assetRefBase = '/assets'): Promise<AssetUsage[]> {
19
+ export async function findAssetUsage(
20
+ api: AssetUsageSource,
21
+ path: string,
22
+ assetRefBase = '/assets',
23
+ ): Promise<AssetUsage[]> {
12
24
  const link = `${assetRefBase}/${path.replace(/^\/+|\/+$/g, '')}`;
13
25
  const whole = new RegExp(`(?<![\\w.~%/-])${link.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w./-])`);
14
26
  const usage: AssetUsage[] = [];
15
27
  const severalSites = Object.keys(api.sitesConfig.sites).length > 1;
16
28
  // Listed first: reading an entry can re-index it, which must not disturb the listing being walked
17
- for (const manifest of [...api.listAllContent()]) {
29
+ const manifests: ContentManifest[] = [];
30
+ for await (const manifest of api.listAllContent()) manifests.push(manifest);
31
+ for (const manifest of manifests) {
18
32
  for (const locale of Object.keys(manifest.locales)) {
19
33
  const entry = await api.getLocalized(manifest.id, locale);
20
34
  if (!entry) continue;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Where the editor links an image uploaded on a branch but not yet published: a path no site serves, so it is never
3
+ * mistaken for one of the site's own images.
4
+ */
5
+ import { IMAGE_EXTENSION_MIME } from './asset-constraints.js';
6
+
7
+ /** The path every draft address starts with. */
8
+ export const DRAFT_MEDIA_REF_BASE = '/api/v1/assets/serve';
9
+
10
+ /** The draft address of a path inside the media library, written raw, never URL-encoded. */
11
+ export function draftMediaRef(path: string): string {
12
+ return `${DRAFT_MEDIA_REF_BASE}/${path}`;
13
+ }
14
+
15
+ /** The raw media path of a link that is exactly `${base}/<path>`, or `undefined` when it is not a safe image path. */
16
+ export function mediaRefPath(value: string, base: string): string | undefined {
17
+ if (!value.startsWith(`${base}/`)) return undefined;
18
+ const path = value.slice(base.length + 1);
19
+ if (/[\\?#]/.test(path)) return undefined;
20
+ const segments = path.split('/');
21
+ for (const part of segments) {
22
+ if (part === '' || part === '.' || part === '..' || hasControlChar(part)) {
23
+ return undefined;
24
+ }
25
+ }
26
+ const filename = segments[segments.length - 1] ?? '';
27
+ const dot = filename.lastIndexOf('.');
28
+ if (dot <= 0) return undefined;
29
+ const extension = filename.slice(dot + 1).toLowerCase();
30
+ if (!Object.prototype.hasOwnProperty.call(IMAGE_EXTENSION_MIME, extension)) return undefined;
31
+ return path;
32
+ }
33
+
34
+ /** Whether `text` holds an ASCII control character (U+0000–U+001F or U+007F). */
35
+ function hasControlChar(text: string): boolean {
36
+ for (let index = 0; index < text.length; index += 1) {
37
+ const code = text.charCodeAt(index);
38
+ if (code < 32 || code === 127) return true;
39
+ }
40
+ return false;
41
+ }
42
+
43
+ /** The raw media path of a draft address, or `undefined` when the value is not one. */
44
+ export function draftMediaRefPath(value: string): string | undefined {
45
+ return mediaRefPath(value, DRAFT_MEDIA_REF_BASE);
46
+ }