@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.
- package/dist/.build-inputs.json +22 -11
- 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/dist/vxjson-serialize.js +2 -2
- package/dist/vxjson-serialize.js.map +1 -1
- package/dist/vxjson.js +1 -1
- package/dist/vxjson.js.map +1 -1
- package/package.json +45 -7
- 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/vxjson-serialize.ts +2 -2
- package/src/vxjson.ts +1 -1
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
|
-
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an upload is, read from its bytes rather than its name: a server stores a file by what it actually holds.
|
|
3
|
+
* Pure and runtime-neutral, so the browser entry can re-export it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The image formats the editors store, by content. */
|
|
7
|
+
export type ImageFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'avif' | 'ico' | 'svg';
|
|
8
|
+
|
|
9
|
+
/** How much of a text file is read to find its first element: room for a long comment and an Illustrator DOCTYPE. */
|
|
10
|
+
const SVG_PROLOG_BYTES = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* True when `text` opens with an optional BOM, then whitespace, the XML declaration, comments, processing
|
|
14
|
+
* instructions and DOCTYPEs, then `<svg`. Each skip searches forward from where the last one ended, so the scan stays
|
|
15
|
+
* linear however the prolog is built (a backtracking pattern took seconds on a few KB of empty comments).
|
|
16
|
+
*/
|
|
17
|
+
function startsWithSvg(text: string): boolean {
|
|
18
|
+
let at = text.startsWith('\uFEFF') ? 1 : 0;
|
|
19
|
+
const past = (close: string, from: number) => {
|
|
20
|
+
const found = text.indexOf(close, from);
|
|
21
|
+
return found === -1 ? -1 : found + close.length;
|
|
22
|
+
};
|
|
23
|
+
while (at < text.length) {
|
|
24
|
+
if (/\s/.test(text[at] ?? '')) at += 1;
|
|
25
|
+
else if (text.startsWith('<?', at)) at = past('?>', at + 2);
|
|
26
|
+
else if (text.startsWith('<!--', at)) at = past('-->', at + 4);
|
|
27
|
+
else if (text.startsWith('<!DOCTYPE', at)) at = doctypeEnd(text, at);
|
|
28
|
+
else return /^<svg[\s/>]/.test(text.slice(at, at + 5));
|
|
29
|
+
if (at === -1) return false; // never closed
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The index just past the `>` that closes the DOCTYPE at `start`, after its internal subset when it has one; -1 if none. */
|
|
35
|
+
function doctypeEnd(text: string, start: number): number {
|
|
36
|
+
const close = text.indexOf('>', start);
|
|
37
|
+
if (close === -1) return -1;
|
|
38
|
+
// Looked for only up to that `>`, so a run of DOCTYPEs never rescans the rest of the text.
|
|
39
|
+
const open = text.slice(start, close).indexOf('[');
|
|
40
|
+
if (open === -1) return close + 1;
|
|
41
|
+
const bracket = start + open;
|
|
42
|
+
// The subset ends at the first `]` that only whitespace separates from `>`.
|
|
43
|
+
for (let end = text.indexOf(']', bracket); end !== -1; end = text.indexOf(']', end + 1)) {
|
|
44
|
+
let next = end + 1;
|
|
45
|
+
while (/\s/.test(text[next] ?? '')) next += 1;
|
|
46
|
+
if (text[next] === '>') return next + 1;
|
|
47
|
+
}
|
|
48
|
+
return -1;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function ascii(bytes: Uint8Array, start: number, text: string): boolean {
|
|
52
|
+
if (bytes.length < start + text.length) return false;
|
|
53
|
+
for (let i = 0; i < text.length; i += 1) if (bytes[start + i] !== text.charCodeAt(i)) return false;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** True when an ISO-BMFF `ftyp` box names an AVIF brand, as its major brand or a compatible one. */
|
|
58
|
+
function isAvif(bytes: Uint8Array): boolean {
|
|
59
|
+
if (!ascii(bytes, 4, 'ftyp')) return false;
|
|
60
|
+
const boxEnd = Math.min(new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0), bytes.length);
|
|
61
|
+
for (let brand = 8; brand + 4 <= boxEnd; brand += brand === 8 ? 8 : 4) {
|
|
62
|
+
if (ascii(bytes, brand, 'avif') || ascii(bytes, brand, 'avis')) return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isSvg(bytes: Uint8Array): boolean {
|
|
68
|
+
let prolog: string;
|
|
69
|
+
try {
|
|
70
|
+
// `stream` holds back a character the cut splits instead of failing on it.
|
|
71
|
+
prolog = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, SVG_PROLOG_BYTES), { stream: true });
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return startsWithSvg(prolog);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The image format `bytes` hold, or `null` when they are no image the editors store. */
|
|
79
|
+
export function sniffImageFormat(bytes: Uint8Array): ImageFormat | null {
|
|
80
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';
|
|
81
|
+
if (ascii(bytes, 0, '\x89PNG\r\n\x1a\n')) return 'png';
|
|
82
|
+
if (ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) return 'webp';
|
|
83
|
+
if (ascii(bytes, 0, 'GIF8')) return 'gif';
|
|
84
|
+
if (isAvif(bytes)) return 'avif';
|
|
85
|
+
if (ascii(bytes, 0, '\x00\x00\x01\x00')) return 'ico';
|
|
86
|
+
return isSvg(bytes) ? 'svg' : null;
|
|
87
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lossless metadata stripping for uploads: EXIF, GPS, XMP, C2PA and anything appended after the image leave a JPEG, PNG
|
|
3
|
+
* or WebP before it is stored, while its pixels, colour profile and orientation stay. Each container is walked by an
|
|
4
|
+
* allowlist of the parts a picture needs; everything else is dropped. Pure and runtime-neutral.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A kept run of the input (`[start, end)`) or bytes written for the output. */
|
|
8
|
+
type Piece = [start: number, end: number] | Uint8Array;
|
|
9
|
+
|
|
10
|
+
/** Keep `[start, end)` of the input, joining it to the previous kept run when they touch. */
|
|
11
|
+
function keep(pieces: Piece[], start: number, end: number): void {
|
|
12
|
+
const last = pieces.at(-1);
|
|
13
|
+
if (last !== undefined && !(last instanceof Uint8Array) && last[1] === start) last[1] = end;
|
|
14
|
+
else pieces.push([start, end]);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The output, built once from the pieces; the input itself when nothing was dropped. */
|
|
18
|
+
function assemble(bytes: Uint8Array, pieces: readonly Piece[]): Uint8Array {
|
|
19
|
+
const only = pieces[0];
|
|
20
|
+
if (pieces.length === 1 && !(only instanceof Uint8Array) && only[0] === 0 && only[1] === bytes.length) return bytes;
|
|
21
|
+
let size = 0;
|
|
22
|
+
for (const piece of pieces) size += piece instanceof Uint8Array ? piece.length : piece[1] - piece[0];
|
|
23
|
+
const out = new Uint8Array(size);
|
|
24
|
+
let offset = 0;
|
|
25
|
+
for (const piece of pieces) {
|
|
26
|
+
const part = piece instanceof Uint8Array ? piece : bytes.subarray(piece[0], piece[1]);
|
|
27
|
+
out.set(part, offset);
|
|
28
|
+
offset += part.length;
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function ascii(bytes: Uint8Array, start: number, text: string): boolean {
|
|
34
|
+
if (bytes.length < start + text.length) return false;
|
|
35
|
+
for (let i = 0; i < text.length; i += 1) if (bytes[start + i] !== text.charCodeAt(i)) return false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function view(bytes: Uint8Array): DataView {
|
|
40
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The EXIF Orientation (tag 0x0112 in IFD0) of the TIFF structure at `[start, end)`, or 1 when it has none. */
|
|
44
|
+
function tiffOrientation(bytes: Uint8Array, start: number, end: number): number {
|
|
45
|
+
if (end - start < 8) return 1;
|
|
46
|
+
const little = ascii(bytes, start, 'II');
|
|
47
|
+
if (!little && !ascii(bytes, start, 'MM')) return 1;
|
|
48
|
+
const data = view(bytes);
|
|
49
|
+
const ifd = start + data.getUint32(start + 4, little);
|
|
50
|
+
if (ifd + 2 > end) return 1;
|
|
51
|
+
const count = data.getUint16(ifd, little);
|
|
52
|
+
for (let entry = ifd + 2; entry + 12 <= end && entry < ifd + 2 + count * 12; entry += 12) {
|
|
53
|
+
if (data.getUint16(entry, little) === 0x0112 && data.getUint16(entry + 2, little) === 3) {
|
|
54
|
+
const orientation = data.getUint16(entry + 8, little);
|
|
55
|
+
return orientation >= 1 && orientation <= 8 ? orientation : 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A big-endian TIFF holding only IFD0 with one Orientation entry. */
|
|
62
|
+
function orientationTiff(orientation: number): Uint8Array {
|
|
63
|
+
// biome-ignore format: one TIFF field per row
|
|
64
|
+
return Uint8Array.from([
|
|
65
|
+
0x4d, 0x4d, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x08, // "MM", 42, IFD0 at 8
|
|
66
|
+
0x00, 0x01, // one entry
|
|
67
|
+
0x01, 0x12, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, orientation, 0x00, 0x00, // Orientation, SHORT, 1 value
|
|
68
|
+
0x00, 0x00, 0x00, 0x00, // no next IFD
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* JPEG APPn markers kept: APP0 only when it is JFIF (a JFXX one holds a thumbnail with its own EXIF), APP14 (Adobe
|
|
74
|
+
* colour transform), and APP2 only when it is an ICC profile.
|
|
75
|
+
*/
|
|
76
|
+
const APP0 = 0xe0;
|
|
77
|
+
const APP1 = 0xe1;
|
|
78
|
+
const APP2 = 0xe2;
|
|
79
|
+
const APP14 = 0xee;
|
|
80
|
+
const COM = 0xfe;
|
|
81
|
+
const SOS = 0xda;
|
|
82
|
+
const EOI = 0xd9;
|
|
83
|
+
|
|
84
|
+
function isRst(marker: number): boolean {
|
|
85
|
+
return marker >= 0xd0 && marker <= 0xd7;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function stripJpeg(bytes: Uint8Array): Uint8Array | null {
|
|
89
|
+
if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
|
|
90
|
+
const pieces: Piece[] = [];
|
|
91
|
+
keep(pieces, 0, 2);
|
|
92
|
+
let orientation = 1;
|
|
93
|
+
let pos = 2;
|
|
94
|
+
while (pos < bytes.length) {
|
|
95
|
+
if (pos + 2 > bytes.length || bytes[pos] !== 0xff) return null;
|
|
96
|
+
const marker = bytes[pos + 1];
|
|
97
|
+
if (marker === 0xff) {
|
|
98
|
+
pos += 1; // fill byte
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (marker === EOI) {
|
|
102
|
+
keep(pieces, pos, pos + 2);
|
|
103
|
+
break; // everything after the primary image (MPF pictures, Ultra HDR gain maps, trailers) is dropped
|
|
104
|
+
}
|
|
105
|
+
if (marker === 0x01 || isRst(marker)) {
|
|
106
|
+
keep(pieces, pos, pos + 2);
|
|
107
|
+
pos += 2;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (pos + 4 > bytes.length) return null;
|
|
111
|
+
const length = (bytes[pos + 2] << 8) | bytes[pos + 3];
|
|
112
|
+
const end = pos + 2 + length;
|
|
113
|
+
if (length < 2 || end > bytes.length) return null;
|
|
114
|
+
const dataStart = pos + 4;
|
|
115
|
+
if (marker === APP1) {
|
|
116
|
+
if (ascii(bytes, dataStart, 'Exif\0\0')) orientation = tiffOrientation(bytes, dataStart + 6, end);
|
|
117
|
+
} else if (
|
|
118
|
+
(marker === APP0 && ascii(bytes, dataStart, 'JFIF\0')) ||
|
|
119
|
+
marker === APP14 ||
|
|
120
|
+
(marker === APP2 && ascii(bytes, dataStart, 'ICC_PROFILE\0'))
|
|
121
|
+
) {
|
|
122
|
+
keep(pieces, pos, end);
|
|
123
|
+
} else if (marker === COM || (marker & 0xf0) === 0xe0) {
|
|
124
|
+
// other APPn and comments: metadata
|
|
125
|
+
} else if (marker === SOS) {
|
|
126
|
+
// The entropy-coded scan runs to the next marker that is neither a stuffed 0xFF00 nor a restart marker.
|
|
127
|
+
let scan = end;
|
|
128
|
+
while (scan < bytes.length) {
|
|
129
|
+
if (bytes[scan] === 0xff && scan + 1 < bytes.length) {
|
|
130
|
+
const next = bytes[scan + 1];
|
|
131
|
+
if (next !== 0x00 && !isRst(next)) break;
|
|
132
|
+
scan += 2;
|
|
133
|
+
} else scan += 1;
|
|
134
|
+
}
|
|
135
|
+
keep(pieces, pos, scan);
|
|
136
|
+
pos = scan;
|
|
137
|
+
continue;
|
|
138
|
+
} else {
|
|
139
|
+
keep(pieces, pos, end); // tables, frame headers and every other structural segment
|
|
140
|
+
}
|
|
141
|
+
pos = end;
|
|
142
|
+
}
|
|
143
|
+
const first = pieces[0];
|
|
144
|
+
if (orientation !== 1 && !(first instanceof Uint8Array)) {
|
|
145
|
+
const tiff = orientationTiff(orientation);
|
|
146
|
+
const segment = new Uint8Array(4 + 6 + tiff.length);
|
|
147
|
+
segment.set([0xff, APP1, 0, 2 + 6 + tiff.length]);
|
|
148
|
+
segment.set([0x45, 0x78, 0x69, 0x66, 0, 0], 4); // "Exif\0\0"
|
|
149
|
+
segment.set(tiff, 10);
|
|
150
|
+
// Right after SOI, or after a kept JFIF APP0 that directly follows it: both always open the first kept run.
|
|
151
|
+
const cut = bytes[3] === APP0 && ascii(bytes, 6, 'JFIF\0') ? 4 + ((bytes[4] << 8) | bytes[5]) : 2;
|
|
152
|
+
const rest: Piece[] = first[1] > cut ? [[cut, first[1]]] : [];
|
|
153
|
+
pieces.splice(0, 1, [0, cut], segment, ...rest);
|
|
154
|
+
}
|
|
155
|
+
return assemble(bytes, pieces);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* PNG chunks a picture needs, its HDR colour (cICP, mDCv, cLLi) included; everything else (eXIf, tEXt/zTXt/iTXt, tIME,
|
|
160
|
+
* caBX, private chunks) is dropped.
|
|
161
|
+
*/
|
|
162
|
+
const PNG_KEPT = new Set([
|
|
163
|
+
'IHDR',
|
|
164
|
+
'PLTE',
|
|
165
|
+
'IDAT',
|
|
166
|
+
'IEND',
|
|
167
|
+
'tRNS',
|
|
168
|
+
'cHRM',
|
|
169
|
+
'gAMA',
|
|
170
|
+
'iCCP',
|
|
171
|
+
'sBIT',
|
|
172
|
+
'sRGB',
|
|
173
|
+
'bKGD',
|
|
174
|
+
'pHYs',
|
|
175
|
+
'acTL',
|
|
176
|
+
'cICP',
|
|
177
|
+
'mDCv',
|
|
178
|
+
'cLLi',
|
|
179
|
+
'fcTL',
|
|
180
|
+
'fdAT',
|
|
181
|
+
]);
|
|
182
|
+
|
|
183
|
+
function chunkType(bytes: Uint8Array, start: number): string {
|
|
184
|
+
return String.fromCharCode(bytes[start], bytes[start + 1], bytes[start + 2], bytes[start + 3]);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function stripPng(bytes: Uint8Array): Uint8Array | null {
|
|
188
|
+
if (!ascii(bytes, 0, '\x89PNG\r\n\x1a\n')) return null;
|
|
189
|
+
const data = view(bytes);
|
|
190
|
+
const pieces: Piece[] = [];
|
|
191
|
+
keep(pieces, 0, 8);
|
|
192
|
+
let pos = 8;
|
|
193
|
+
while (pos + 12 <= bytes.length) {
|
|
194
|
+
const end = pos + 12 + data.getUint32(pos);
|
|
195
|
+
if (end > bytes.length) return null;
|
|
196
|
+
const type = chunkType(bytes, pos + 4);
|
|
197
|
+
if (PNG_KEPT.has(type)) keep(pieces, pos, end);
|
|
198
|
+
if (type === 'IEND') return assemble(bytes, pieces);
|
|
199
|
+
pos = end;
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** WebP chunks a picture needs; EXIF and XMP and anything unknown are dropped. */
|
|
205
|
+
const WEBP_KEPT = new Set(['VP8 ', 'VP8L', 'VP8X', 'ALPH', 'ANIM', 'ANMF', 'ICCP']);
|
|
206
|
+
const VP8X_EXIF = 0x08;
|
|
207
|
+
const VP8X_XMP = 0x04;
|
|
208
|
+
|
|
209
|
+
function stripWebp(bytes: Uint8Array): Uint8Array | null {
|
|
210
|
+
if (!ascii(bytes, 0, 'RIFF') || !ascii(bytes, 8, 'WEBP')) return null;
|
|
211
|
+
const data = view(bytes);
|
|
212
|
+
const riffEnd = 8 + data.getUint32(4, true);
|
|
213
|
+
if (riffEnd > bytes.length) return null;
|
|
214
|
+
const header = new Uint8Array(12);
|
|
215
|
+
const pieces: Piece[] = [header];
|
|
216
|
+
let vp8x: Uint8Array | null = null;
|
|
217
|
+
let orientation = 1;
|
|
218
|
+
let pos = 12;
|
|
219
|
+
while (pos < riffEnd) {
|
|
220
|
+
if (pos + 8 > riffEnd) return null;
|
|
221
|
+
const size = data.getUint32(pos + 4, true);
|
|
222
|
+
const end = pos + 8 + size + (size & 1);
|
|
223
|
+
if (end > riffEnd) return null;
|
|
224
|
+
const type = chunkType(bytes, pos);
|
|
225
|
+
if (type === 'VP8X') {
|
|
226
|
+
if (size < 10) return null;
|
|
227
|
+
// Copied, not kept: its flags change.
|
|
228
|
+
vp8x = bytes.slice(pos, end);
|
|
229
|
+
pieces.push(vp8x);
|
|
230
|
+
} else if (WEBP_KEPT.has(type)) {
|
|
231
|
+
keep(pieces, pos, end);
|
|
232
|
+
} else if (type === 'EXIF') {
|
|
233
|
+
const tiff = ascii(bytes, pos + 8, 'Exif\0\0') ? pos + 14 : pos + 8;
|
|
234
|
+
orientation = tiffOrientation(bytes, tiff, pos + 8 + size);
|
|
235
|
+
}
|
|
236
|
+
pos = end;
|
|
237
|
+
}
|
|
238
|
+
if (vp8x !== null) {
|
|
239
|
+
vp8x[8] &= ~(VP8X_XMP | VP8X_EXIF);
|
|
240
|
+
if (orientation !== 1) {
|
|
241
|
+
// A simple WebP (no VP8X) cannot carry EXIF, so only an extended one gets its orientation back.
|
|
242
|
+
vp8x[8] |= VP8X_EXIF;
|
|
243
|
+
const tiff = orientationTiff(orientation);
|
|
244
|
+
const chunk = new Uint8Array(8 + tiff.length);
|
|
245
|
+
chunk.set([0x45, 0x58, 0x49, 0x46, tiff.length]); // "EXIF", little-endian size
|
|
246
|
+
chunk.set(tiff, 8);
|
|
247
|
+
pieces.push(chunk);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
let size = 0;
|
|
251
|
+
for (const piece of pieces) size += piece instanceof Uint8Array ? piece.length : piece[1] - piece[0];
|
|
252
|
+
header.set([0x52, 0x49, 0x46, 0x46]); // "RIFF"
|
|
253
|
+
new DataView(header.buffer).setUint32(4, size - 8, true);
|
|
254
|
+
header.set([0x57, 0x45, 0x42, 0x50], 8); // "WEBP"
|
|
255
|
+
return assemble(bytes, pieces);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* `bytes` without their metadata, read as `format`: colour profile and orientation kept, pixels untouched. `null` when
|
|
260
|
+
* the container cannot be walked. The output is built once from slices of the input.
|
|
261
|
+
*/
|
|
262
|
+
export function stripImageMetadata(bytes: Uint8Array, format: 'jpeg' | 'png' | 'webp'): Uint8Array | null {
|
|
263
|
+
if (format === 'jpeg') return stripJpeg(bytes);
|
|
264
|
+
if (format === 'png') return stripPng(bytes);
|
|
265
|
+
return stripWebp(bytes);
|
|
266
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shrinking for the Node servers, the local editor and `conloca asset add`, the way the browser shrinks before it
|
|
3
|
+
* sends: a photo whose long edge is over {@link MAX_IMAGE_EDGE} is stood upright and resized to it. `sharp` is an
|
|
4
|
+
* optional dependency, loaded only when a photo needs it. Node only, not exported.
|
|
5
|
+
*/
|
|
6
|
+
import { imageSize } from 'image-size';
|
|
7
|
+
import { JPEG_FALLBACK_QUALITY, MAX_IMAGE_EDGE, WEBP_QUALITY } from './asset-constraints.js';
|
|
8
|
+
import { sniffImageFormat } from './image-format.js';
|
|
9
|
+
import { shrinkUnavailableWarning, unreadableImageRefusal } from './upload-refusals.js';
|
|
10
|
+
|
|
11
|
+
/** The upload to store, with a warning when it needed shrinking but could not be, or the sentence it is refused with. */
|
|
12
|
+
export type ShrunkUpload = { bytes: Uint8Array; filename: string; warning?: string } | { refusal: string };
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `bytes` resized so their long edge is at most {@link MAX_IMAGE_EDGE}, for JPEG, PNG, WebP and AVIF over it: PNG stays
|
|
16
|
+
* PNG; the others become WebP named `.webp` when `acceptedFormats` takes WebP, otherwise keep their format and name.
|
|
17
|
+
* Everything else is handed back unchanged, as is a large photo when `sharp` cannot be loaded (with a warning).
|
|
18
|
+
*/
|
|
19
|
+
export async function shrinkImage(
|
|
20
|
+
bytes: Uint8Array,
|
|
21
|
+
filename: string,
|
|
22
|
+
acceptedFormats: readonly string[],
|
|
23
|
+
): Promise<ShrunkUpload> {
|
|
24
|
+
const format = sniffImageFormat(bytes);
|
|
25
|
+
if (format !== 'jpeg' && format !== 'png' && format !== 'webp' && format !== 'avif') return { bytes, filename };
|
|
26
|
+
let longEdge: number;
|
|
27
|
+
try {
|
|
28
|
+
const { width, height } = imageSize(bytes);
|
|
29
|
+
longEdge = Math.max(width, height);
|
|
30
|
+
} catch {
|
|
31
|
+
// Not measurable: the upload's own checks refuse it as unreadable.
|
|
32
|
+
return { bytes, filename };
|
|
33
|
+
}
|
|
34
|
+
if (longEdge <= MAX_IMAGE_EDGE) return { bytes, filename };
|
|
35
|
+
|
|
36
|
+
// Dynamic: sharp is an optional dependency, and a native one that can fail to load even when installed.
|
|
37
|
+
const sharp = await import('sharp').then(
|
|
38
|
+
(module) => module.default,
|
|
39
|
+
() => null,
|
|
40
|
+
);
|
|
41
|
+
if (sharp === null) return { bytes, filename, warning: shrinkUnavailableWarning(filename) };
|
|
42
|
+
const target = format === 'png' || !acceptedFormats.includes('webp') ? format : 'webp';
|
|
43
|
+
const quality = Math.round((target === 'jpeg' ? JPEG_FALLBACK_QUALITY : WEBP_QUALITY) * 100);
|
|
44
|
+
let shrunk: Uint8Array;
|
|
45
|
+
try {
|
|
46
|
+
const resized = sharp(bytes)
|
|
47
|
+
.rotate()
|
|
48
|
+
.resize({ width: MAX_IMAGE_EDGE, height: MAX_IMAGE_EDGE, fit: 'inside', withoutEnlargement: true });
|
|
49
|
+
// PNG takes no quality: sharp reads one as a request for a reduced palette.
|
|
50
|
+
shrunk = await (target === 'png' ? resized.png() : resized.toFormat(target, { quality })).toBuffer();
|
|
51
|
+
} catch {
|
|
52
|
+
return { refusal: unreadableImageRefusal(filename) };
|
|
53
|
+
}
|
|
54
|
+
if (target !== 'webp' || format === 'webp') return { bytes: shrunk, filename };
|
|
55
|
+
const dot = filename.lastIndexOf('.');
|
|
56
|
+
return { bytes: shrunk, filename: `${dot > 0 ? filename.slice(0, dot) : filename}.webp` };
|
|
57
|
+
}
|