@conloca/content-api 0.2.3 → 0.2.4
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/.build-inputs.json +20 -9
- package/dist/asset-constraints.d.ts +9 -1
- package/dist/asset-constraints.d.ts.map +1 -1
- package/dist/asset-constraints.js +10 -2
- package/dist/asset-constraints.js.map +1 -1
- package/dist/asset-metadata-record.d.ts +18 -0
- package/dist/asset-metadata-record.d.ts.map +1 -0
- package/dist/asset-metadata-record.js +59 -0
- package/dist/asset-metadata-record.js.map +1 -0
- package/dist/asset-metadata-store.d.ts.map +1 -1
- package/dist/asset-metadata-store.js +7 -26
- package/dist/asset-metadata-store.js.map +1 -1
- package/dist/asset-naming.d.ts +39 -0
- package/dist/asset-naming.d.ts.map +1 -0
- package/dist/asset-naming.js +123 -0
- package/dist/asset-naming.js.map +1 -0
- package/dist/asset-operations.d.ts +3 -5
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +99 -90
- package/dist/asset-operations.js.map +1 -1
- package/dist/asset-types.d.ts +2 -0
- package/dist/asset-types.d.ts.map +1 -1
- package/dist/asset-usage.d.ts +8 -1
- package/dist/asset-usage.d.ts.map +1 -1
- package/dist/asset-usage.js +4 -1
- package/dist/asset-usage.js.map +1 -1
- package/dist/draft-media-ref.d.ts +9 -0
- package/dist/draft-media-ref.d.ts.map +1 -0
- package/dist/draft-media-ref.js +47 -0
- package/dist/draft-media-ref.js.map +1 -0
- package/dist/editor-host.d.ts +53 -0
- package/dist/editor-host.d.ts.map +1 -1
- package/dist/editor-host.js +92 -0
- package/dist/editor-host.js.map +1 -1
- package/dist/git-operations.d.ts +0 -5
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +1 -33
- package/dist/git-operations.js.map +1 -1
- package/dist/image-format.d.ts +9 -0
- package/dist/image-format.d.ts.map +1 -0
- package/dist/image-format.js +100 -0
- package/dist/image-format.js.map +1 -0
- package/dist/image-metadata.d.ts +11 -0
- package/dist/image-metadata.d.ts.map +1 -0
- package/dist/image-metadata.js +283 -0
- package/dist/image-metadata.js.map +1 -0
- package/dist/image-shrink.d.ts +15 -0
- package/dist/image-shrink.d.ts.map +1 -0
- package/dist/image-shrink.js +52 -0
- package/dist/image-shrink.js.map +1 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -3
- package/dist/index.js.map +1 -1
- package/dist/lfs-attributes.d.ts +26 -0
- package/dist/lfs-attributes.d.ts.map +1 -0
- package/dist/lfs-attributes.js +285 -0
- package/dist/lfs-attributes.js.map +1 -0
- package/dist/skill-stamp.d.ts +10 -0
- package/dist/skill-stamp.d.ts.map +1 -0
- package/dist/skill-stamp.js +42 -0
- package/dist/skill-stamp.js.map +1 -0
- package/dist/svg-sanitize.d.ts +8 -0
- package/dist/svg-sanitize.d.ts.map +1 -0
- package/dist/svg-sanitize.js +260 -0
- package/dist/svg-sanitize.js.map +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/upload-bytes.d.ts +17 -0
- package/dist/upload-bytes.d.ts.map +1 -0
- package/dist/upload-bytes.js +43 -0
- package/dist/upload-bytes.js.map +1 -0
- package/dist/upload-refusals.d.ts +24 -0
- package/dist/upload-refusals.d.ts.map +1 -0
- package/dist/upload-refusals.js +49 -0
- package/dist/upload-refusals.js.map +1 -0
- package/package.json +43 -5
- package/src/asset-constraints.ts +14 -2
- package/src/asset-metadata-record.ts +57 -0
- package/src/asset-metadata-store.ts +12 -21
- package/src/asset-naming.ts +120 -0
- package/src/asset-operations.ts +108 -91
- package/src/asset-types.ts +2 -0
- package/src/asset-usage.ts +16 -2
- package/src/draft-media-ref.ts +46 -0
- package/src/editor-host.ts +117 -1
- package/src/git-operations.ts +1 -38
- package/src/image-format.ts +87 -0
- package/src/image-metadata.ts +266 -0
- package/src/image-shrink.ts +57 -0
- package/src/index.ts +45 -3
- package/src/lfs-attributes.ts +291 -0
- package/src/skill-stamp.ts +45 -0
- package/src/svg-sanitize.ts +260 -0
- package/src/types.ts +7 -0
- package/src/upload-bytes.ts +46 -0
- package/src/upload-refusals.ts +59 -0
package/src/asset-operations.ts
CHANGED
|
@@ -11,13 +11,33 @@ import {
|
|
|
11
11
|
unlink,
|
|
12
12
|
writeFile,
|
|
13
13
|
} from 'node:fs/promises';
|
|
14
|
-
import { basename, dirname, extname, join,
|
|
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 {
|
|
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 {
|
|
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
|
-
*
|
|
111
|
-
*
|
|
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
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
-
|
|
252
|
-
|
|
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 =
|
|
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:
|
|
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
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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: '
|
|
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
|
|
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: '
|
|
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: `
|
|
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
|
|
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
|
|
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
|
|
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
|
|
590
|
-
if (
|
|
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
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
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 {
|
package/src/asset-types.ts
CHANGED
|
@@ -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 */
|
package/src/asset-usage.ts
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
+
}
|
package/src/editor-host.ts
CHANGED
|
@@ -1,9 +1,74 @@
|
|
|
1
|
+
import { folderPathError } from './asset-naming.js';
|
|
1
2
|
import { isRecord } from './component-vocabulary.js';
|
|
2
3
|
|
|
3
4
|
/** The wire protocol an editor page built by this release speaks; the editor UI path is /host/v<this>/. */
|
|
4
5
|
export const EDITOR_HOST_PROTOCOL = 1;
|
|
5
6
|
/** Protocols the current editor UI accepts. */
|
|
6
7
|
export const EDITOR_HOST_PROTOCOLS = { min: 1, max: 1 } as const;
|
|
8
|
+
/**
|
|
9
|
+
* The draft-preview protocol a preview server built by this release speaks. Protocol 1 keeps the pass out of the
|
|
10
|
+
* page; protocol 2 opens a preview with a single-use code the server trades for the pass, so no pass travels in a
|
|
11
|
+
* link. conloca.json `preview.protocol` and the exit route's `conloca-preview-protocol` header carry it.
|
|
12
|
+
*/
|
|
13
|
+
export const PREVIEW_PROTOCOL = 2;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* How a build serves draft previews: `d2` from the site's own server deploy, `d3` from a dispatcher in front of a
|
|
17
|
+
* static site under `<base>_conloca/preview/<branch slug>/`, `d4` from a separate preview deploy, `off` not at all.
|
|
18
|
+
*/
|
|
19
|
+
export type PreviewMode = 'd2' | 'd3' | 'd4' | 'off';
|
|
20
|
+
|
|
21
|
+
const PREVIEW_MODES: readonly PreviewMode[] = ['d2', 'd3', 'd4', 'off'];
|
|
22
|
+
|
|
23
|
+
function isPreviewMode(value: unknown): value is PreviewMode {
|
|
24
|
+
return PREVIEW_MODES.some((mode) => mode === value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** conloca.json `preview`: the build's preview mode and the preview protocol it speaks. */
|
|
28
|
+
export interface PreviewSignal {
|
|
29
|
+
mode: PreviewMode;
|
|
30
|
+
protocol: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A branch name as one path segment and cookie-name suffix: its UTF-8 bytes as unpadded base64url, one slug per name. */
|
|
34
|
+
export function previewBranchSlug(branch: string): string {
|
|
35
|
+
let binary = '';
|
|
36
|
+
for (const byte of new TextEncoder().encode(branch)) binary += String.fromCharCode(byte);
|
|
37
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The branch a slug names, or null unless it is the slug of a valid branch name (at most 765 UTF-8 bytes, 1020 characters; 1360 bounds it with room). */
|
|
41
|
+
export function branchOfPreviewSlug(slug: string): string | null {
|
|
42
|
+
if (!/^[A-Za-z0-9_-]{1,1360}$/u.test(slug)) return null;
|
|
43
|
+
let bytes: Uint8Array;
|
|
44
|
+
try {
|
|
45
|
+
bytes = Uint8Array.from(atob(slug.replaceAll('-', '+').replaceAll('_', '/')), (char) => char.charCodeAt(0));
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
let branch: string;
|
|
50
|
+
try {
|
|
51
|
+
branch = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
return isValidBranchName(branch) && previewBranchSlug(branch) === slug ? branch : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Whether a branch's slug leaves room in a 1024-byte cookie `Path` (`<base>_conloca/preview/<slug>`). */
|
|
59
|
+
export function previewSlugFits(branch: string): boolean {
|
|
60
|
+
return previewBranchSlug(branch).length <= 900;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** conloca.json `preview`; `undefined` when absent or malformed, so a bad optional field never makes the page invalid. */
|
|
64
|
+
export function previewSignalOf(info: ConlocaJson): PreviewSignal | undefined {
|
|
65
|
+
const value: unknown = Reflect.get(info, 'preview');
|
|
66
|
+
if (!isRecord(value)) return undefined;
|
|
67
|
+
const { mode, protocol } = value;
|
|
68
|
+
return isPreviewMode(mode) && typeof protocol === 'number' && Number.isSafeInteger(protocol)
|
|
69
|
+
? { mode, protocol }
|
|
70
|
+
: undefined;
|
|
71
|
+
}
|
|
7
72
|
export const DEFAULT_EDITOR_ENDPOINT = 'https://app.conloca.com';
|
|
8
73
|
/** Where the editor page is served, below the site's base. */
|
|
9
74
|
export const EDITOR_PAGE_PATH = '/_conloca/editor/';
|
|
@@ -82,6 +147,9 @@ export interface EditorPageInfo {
|
|
|
82
147
|
componentManifest: { path: string; sha256: string } | null;
|
|
83
148
|
}
|
|
84
149
|
|
|
150
|
+
/** The file beside conloca.json holding each `dataSchemas` collection's JSON schema, as `{ collections }`. */
|
|
151
|
+
export const DATA_SCHEMAS_FILE = 'data-schemas.json';
|
|
152
|
+
|
|
85
153
|
export const EDITOR_PAGE_INFO_FORMATS = {
|
|
86
154
|
commit: /^[0-9a-f]{40}$/,
|
|
87
155
|
builtWith: /^@conloca\/cloud-astro@\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,
|
|
@@ -98,7 +166,9 @@ export type BranchDeploys = { host: 'cloudflare-pages'; project: string };
|
|
|
98
166
|
const PAGES_PROJECT_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
99
167
|
|
|
100
168
|
/** A parsed conloca.json object, whether or not it passed `isEditorPageInfo`, as the optional-field readers take it. */
|
|
101
|
-
export type ConlocaJson =
|
|
169
|
+
export type ConlocaJson =
|
|
170
|
+
| EditorPageInfo
|
|
171
|
+
| { branchDeploys?: unknown; contentPaths?: unknown; preview?: unknown; routes?: unknown; media?: unknown };
|
|
102
172
|
|
|
103
173
|
/** conloca.json `branchDeploys`; `undefined` when absent or malformed, so a bad optional field never makes the page invalid. */
|
|
104
174
|
export function branchDeploysOf(info: ConlocaJson): BranchDeploys | undefined {
|
|
@@ -130,6 +200,52 @@ export function contentPathsOf(info: ConlocaJson): string[] | undefined {
|
|
|
130
200
|
return [...new Set<string>(value)];
|
|
131
201
|
}
|
|
132
202
|
|
|
203
|
+
/** The most bytes of conloca.json the workspace editor reads; a build never writes more. */
|
|
204
|
+
export const CONLOCA_JSON_MAX_BYTES = 16 * 1024;
|
|
205
|
+
|
|
206
|
+
/** A page route: `/` then at most 200 unreserved URL characters or `/`, so no route carries prompt or shell syntax. */
|
|
207
|
+
export const EDITOR_ROUTE_RE = /^\/[A-Za-z0-9._~\-/]{0,200}$/;
|
|
208
|
+
/** The most routes a conloca.json lists. */
|
|
209
|
+
export const ROUTES_MAX = 500;
|
|
210
|
+
|
|
211
|
+
/** Whether `route` is a string matching `EDITOR_ROUTE_RE`. */
|
|
212
|
+
export function isEditorRoute(route: unknown): route is string {
|
|
213
|
+
return typeof route === 'string' && EDITOR_ROUTE_RE.test(route);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* conloca.json `routes`: the page routes a build lists, those outside `EDITOR_ROUTE_RE` and duplicates dropped,
|
|
218
|
+
* at most `ROUTES_MAX`; `undefined` when absent or not a list, so a bad optional field never makes the page invalid.
|
|
219
|
+
*/
|
|
220
|
+
export function routesOf(info: ConlocaJson): string[] | undefined {
|
|
221
|
+
const value: unknown = Reflect.get(info, 'routes');
|
|
222
|
+
if (!Array.isArray(value)) return undefined;
|
|
223
|
+
return [...new Set(value.filter(isEditorRoute))].slice(0, ROUTES_MAX);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** conloca.json `media`: the repository folder uploaded images go to and the URL the site serves it at. */
|
|
227
|
+
export interface EditorMedia {
|
|
228
|
+
path: string;
|
|
229
|
+
refBase: string;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A link base: `''`, or `/`-led segments of URL-safe characters with no `.` or `..` segment and no trailing `/`. */
|
|
233
|
+
const REF_BASE_RE = /^(\/(?!\.\.?(?:\/|$))[A-Za-z0-9._~-]+)*$/;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* conloca.json `media`; `undefined` when absent or malformed (the repository root, a folder `folderPathError`
|
|
237
|
+
* refuses, or a link base {@link REF_BASE_RE} refuses), so a bad optional field never makes the page invalid. The
|
|
238
|
+
* link base is written into saved pages, so it may hold nothing a page's JSON, front matter or MDX would read.
|
|
239
|
+
*/
|
|
240
|
+
export function mediaOf(info: ConlocaJson): EditorMedia | undefined {
|
|
241
|
+
const value: unknown = Reflect.get(info, 'media');
|
|
242
|
+
if (!isRecord(value)) return undefined;
|
|
243
|
+
const { path, refBase } = value;
|
|
244
|
+
if (typeof path !== 'string' || path === '' || path.length > 255 || folderPathError(path) !== null) return undefined;
|
|
245
|
+
if (typeof refBase !== 'string' || refBase.length > 255 || !REF_BASE_RE.test(refBase)) return undefined;
|
|
246
|
+
return { path, refBase };
|
|
247
|
+
}
|
|
248
|
+
|
|
133
249
|
// `~^:?*[\`, `..`, `@{` and `//` anywhere (`git check-ref-format`); space and control characters are checked apart.
|
|
134
250
|
const BRANCH_FORBIDDEN_RE = /[~^:?*[\\]|\.\.|@\{|\/\//;
|
|
135
251
|
|
package/src/git-operations.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { dirname, join, resolve } from 'node:path';
|
|
5
5
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
@@ -448,40 +448,3 @@ export function createGitOperations(config: GitConfig): GitOperations {
|
|
|
448
448
|
},
|
|
449
449
|
};
|
|
450
450
|
}
|
|
451
|
-
|
|
452
|
-
const LFS_PATTERNS = [
|
|
453
|
-
'*.jpg filter=lfs diff=lfs merge=lfs -text',
|
|
454
|
-
'*.jpeg filter=lfs diff=lfs merge=lfs -text',
|
|
455
|
-
'*.png filter=lfs diff=lfs merge=lfs -text',
|
|
456
|
-
'*.gif filter=lfs diff=lfs merge=lfs -text',
|
|
457
|
-
'*.svg filter=lfs diff=lfs merge=lfs -text',
|
|
458
|
-
'*.webp filter=lfs diff=lfs merge=lfs -text',
|
|
459
|
-
'*.avif filter=lfs diff=lfs merge=lfs -text',
|
|
460
|
-
'*.ico filter=lfs diff=lfs merge=lfs -text',
|
|
461
|
-
];
|
|
462
|
-
|
|
463
|
-
/**
|
|
464
|
-
* Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.
|
|
465
|
-
* Creates the file if missing, or appends missing patterns if file exists.
|
|
466
|
-
*/
|
|
467
|
-
export async function setupGitLfsAttributes(contentRoot: string): Promise<void> {
|
|
468
|
-
const gitattributesPath = join(contentRoot, '.gitattributes');
|
|
469
|
-
let existing = '';
|
|
470
|
-
|
|
471
|
-
try {
|
|
472
|
-
await access(gitattributesPath);
|
|
473
|
-
existing = await readFile(gitattributesPath, 'utf-8');
|
|
474
|
-
} catch {
|
|
475
|
-
// File doesn't exist — will create fresh
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));
|
|
479
|
-
|
|
480
|
-
if (missingPatterns.length === 0) return;
|
|
481
|
-
|
|
482
|
-
const newContent = existing
|
|
483
|
-
? `${existing.trimEnd()}\n${missingPatterns.join('\n')}\n`
|
|
484
|
-
: `${missingPatterns.join('\n')}\n`;
|
|
485
|
-
|
|
486
|
-
await writeFile(gitattributesPath, newContent, 'utf-8');
|
|
487
|
-
}
|