@conloca/content-api 0.2.2 → 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 +82 -0
- package/dist/address-site.d.ts +6 -0
- package/dist/address-site.d.ts.map +1 -0
- package/dist/address-site.js +15 -0
- package/dist/address-site.js.map +1 -0
- 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 +15 -2
- 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/component-registry.d.ts +3 -0
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/content-utils.d.ts +4 -1
- package/dist/content-utils.d.ts.map +1 -1
- package/dist/content-utils.js +14 -1
- package/dist/content-utils.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 +174 -0
- package/dist/editor-host.d.ts.map +1 -0
- package/dist/editor-host.js +304 -0
- package/dist/editor-host.js.map +1 -0
- package/dist/filesystem-content-api.d.ts +15 -0
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +3 -2
- package/dist/filesystem-content-api.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 +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -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/site.d.ts.map +1 -1
- package/dist/site.js +3 -1
- package/dist/site.js.map +1 -1
- 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 +9 -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 +49 -6
- package/src/address-site.ts +19 -0
- 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/content-utils.ts +18 -2
- package/src/draft-media-ref.ts +46 -0
- package/src/editor-host.ts +384 -0
- package/src/filesystem-content-api.ts +3 -2
- 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 +47 -3
- package/src/lfs-attributes.ts +291 -0
- package/src/site.ts +3 -1
- package/src/skill-stamp.ts +45 -0
- package/src/svg-sanitize.ts +260 -0
- package/src/types.ts +9 -0
- package/src/upload-bytes.ts +46 -0
- package/src/upload-refusals.ts +59 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which Git LFS rule in a repository's `.gitattributes` files would catch a file, matched the way git matches them
|
|
3
|
+
* (attr.c and wildmatch.c), so the online editor can refuse an image git would store in LFS. Pure strings: the browser
|
|
4
|
+
* entry re-exports it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** One `.gitattributes` file: `dir` repo-relative without slashes at either end (`''` for the root), `text` its content. */
|
|
8
|
+
export interface GitAttributesFile {
|
|
9
|
+
dir: string;
|
|
10
|
+
text: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The eight lines the local editor wrote into the media folder's `.gitattributes` on its first upload. */
|
|
14
|
+
const AUTO_WRITTEN_LINES: readonly string[] = [
|
|
15
|
+
'*.jpg filter=lfs diff=lfs merge=lfs -text',
|
|
16
|
+
'*.jpeg filter=lfs diff=lfs merge=lfs -text',
|
|
17
|
+
'*.png filter=lfs diff=lfs merge=lfs -text',
|
|
18
|
+
'*.gif filter=lfs diff=lfs merge=lfs -text',
|
|
19
|
+
'*.svg filter=lfs diff=lfs merge=lfs -text',
|
|
20
|
+
'*.webp filter=lfs diff=lfs merge=lfs -text',
|
|
21
|
+
'*.avif filter=lfs diff=lfs merge=lfs -text',
|
|
22
|
+
'*.ico filter=lfs diff=lfs merge=lfs -text',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* True when `text`'s non-blank lines, line endings and trailing whitespace aside, are exactly the eight the local
|
|
27
|
+
* editor wrote, in any order: it appended the ones missing, so a file it wrote twice holds them reordered.
|
|
28
|
+
*/
|
|
29
|
+
export function isAutoWrittenLfsAttributes(text: string): boolean {
|
|
30
|
+
const lines = new Set(
|
|
31
|
+
text
|
|
32
|
+
.split('\n')
|
|
33
|
+
.map((line) => line.trimEnd())
|
|
34
|
+
.filter((line) => line !== ''),
|
|
35
|
+
);
|
|
36
|
+
return lines.size === AUTO_WRITTEN_LINES.length && AUTO_WRITTEN_LINES.every((line) => lines.has(line));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** An attribute's state: set, unset (`-a`), unspecified (`!a`) or a value (`a=v`). */
|
|
40
|
+
type AttributeState = boolean | null | string;
|
|
41
|
+
|
|
42
|
+
type Assignment = readonly [name: string, state: AttributeState];
|
|
43
|
+
|
|
44
|
+
interface Rule {
|
|
45
|
+
attributesPath: string;
|
|
46
|
+
pattern: string;
|
|
47
|
+
/** Matches the path relative to the file's folder, or only the file name when the pattern holds no slash. */
|
|
48
|
+
matcher: RegExp;
|
|
49
|
+
basenameOnly: boolean;
|
|
50
|
+
dir: string;
|
|
51
|
+
assignments: readonly Assignment[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const BLANK = /[ \t\r\n]+/;
|
|
55
|
+
|
|
56
|
+
/** Git's attribute names: letters, digits, `-`, `.` and `_`, not starting with `-`. */
|
|
57
|
+
const ATTRIBUTE_NAME = /^[.\w][-.\w]*$/;
|
|
58
|
+
|
|
59
|
+
const MACRO_PREFIX = '[attr]';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The LFS rule git would apply to the file at `path` (repo-relative), from the `.gitattributes` files on its way down:
|
|
63
|
+
* the file and pattern of the line that sets `filter=lfs` and is not overridden by a later line or a deeper file;
|
|
64
|
+
* `null` when none does. Matching ignores case, as on a Mac. The media folder's file is skipped when it holds only the
|
|
65
|
+
* rules the local editor wrote ({@link isAutoWrittenLfsAttributes}): those were never the site's own choice.
|
|
66
|
+
*/
|
|
67
|
+
export function lfsRuleFor(
|
|
68
|
+
path: string,
|
|
69
|
+
files: readonly GitAttributesFile[],
|
|
70
|
+
mediaFolder: string,
|
|
71
|
+
): { attributesPath: string; pattern: string } | null {
|
|
72
|
+
const applying = files
|
|
73
|
+
.filter((file) => file.dir === '' || path.startsWith(`${file.dir}/`))
|
|
74
|
+
.filter((file) => !(file.dir === mediaFolder && isAutoWrittenLfsAttributes(file.text)));
|
|
75
|
+
// Every file left is on the path's way down, so a longer folder is a deeper one.
|
|
76
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- the target lib predates toSorted; this sorts a fresh local array.
|
|
77
|
+
applying.sort((a, b) => a.dir.length - b.dir.length);
|
|
78
|
+
const macros = new Map<string, readonly Assignment[]>();
|
|
79
|
+
const rules = applying.flatMap((file) => parseAttributesFile(file, macros));
|
|
80
|
+
|
|
81
|
+
const assigned = new Map<string, { state: AttributeState; rule: Rule }>();
|
|
82
|
+
// Git walks from the last line of the deepest file up; the first state an attribute gets is the one that holds.
|
|
83
|
+
const fill = (assignments: readonly Assignment[], rule: Rule): void => {
|
|
84
|
+
// oxlint-disable-next-line unicorn/no-array-reverse -- the target lib predates toReversed; this reverses a fresh copy.
|
|
85
|
+
for (const [name, state] of [...assignments].reverse()) {
|
|
86
|
+
if (assigned.has(name)) continue;
|
|
87
|
+
assigned.set(name, { state, rule });
|
|
88
|
+
const macro = state === true ? macros.get(name) : undefined;
|
|
89
|
+
if (macro !== undefined) fill(macro, rule);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
// oxlint-disable-next-line unicorn/no-array-reverse -- the target lib predates toReversed; this reverses a fresh copy.
|
|
93
|
+
for (const rule of [...rules].reverse()) {
|
|
94
|
+
const subject = rule.basenameOnly
|
|
95
|
+
? path.slice(path.lastIndexOf('/') + 1)
|
|
96
|
+
: path.slice(rule.dir === '' ? 0 : rule.dir.length + 1);
|
|
97
|
+
if (rule.matcher.test(subject)) fill(rule.assignments, rule);
|
|
98
|
+
}
|
|
99
|
+
const filter = assigned.get('filter');
|
|
100
|
+
return filter?.state === 'lfs' ? { attributesPath: filter.rule.attributesPath, pattern: filter.rule.pattern } : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The rules of one file in order; `[attr]` macro lines of the root file go into `macros` instead. */
|
|
104
|
+
function parseAttributesFile(file: GitAttributesFile, macros: Map<string, readonly Assignment[]>): Rule[] {
|
|
105
|
+
const attributesPath = file.dir === '' ? '.gitattributes' : `${file.dir}/.gitattributes`;
|
|
106
|
+
const rules: Rule[] = [];
|
|
107
|
+
for (const raw of file.text.split('\n')) {
|
|
108
|
+
const line = raw.replace(/^[ \t\r]+/, '');
|
|
109
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
110
|
+
const quoted = line.startsWith('"') ? unquoteC(line) : null;
|
|
111
|
+
const pattern = quoted?.value ?? line.split(BLANK, 1)[0] ?? '';
|
|
112
|
+
const rest = quoted?.rest ?? line.slice(pattern.length);
|
|
113
|
+
const assignments = parseAssignments(rest);
|
|
114
|
+
if (assignments === null) continue;
|
|
115
|
+
if (pattern.startsWith(MACRO_PREFIX)) {
|
|
116
|
+
const name = pattern.slice(MACRO_PREFIX.length);
|
|
117
|
+
// Git honours macros only in the root file.
|
|
118
|
+
if (file.dir === '' && ATTRIBUTE_NAME.test(name)) macros.set(name, assignments);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
// Negative patterns are forbidden in attributes; a trailing slash names a folder, never a file.
|
|
122
|
+
if (pattern === '' || pattern.startsWith('!') || pattern.endsWith('/')) continue;
|
|
123
|
+
const basenameOnly = !pattern.includes('/');
|
|
124
|
+
const matcher = wildmatchRegExp(basenameOnly ? pattern : pattern.replace(/^\//, ''));
|
|
125
|
+
if (matcher === null) continue;
|
|
126
|
+
rules.push({ attributesPath, pattern, matcher, basenameOnly, dir: file.dir, assignments });
|
|
127
|
+
}
|
|
128
|
+
return rules;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The attribute assignments after a pattern; `null` when one names an attribute git refuses (git drops the line). */
|
|
132
|
+
function parseAssignments(text: string): Assignment[] | null {
|
|
133
|
+
const assignments: Assignment[] = [];
|
|
134
|
+
for (const token of text.split(BLANK)) {
|
|
135
|
+
if (token === '') continue;
|
|
136
|
+
const equals = token.indexOf('=');
|
|
137
|
+
const nameEnd = equals === -1 ? token.length : equals;
|
|
138
|
+
const prefix = token[0];
|
|
139
|
+
const name = prefix === '-' || prefix === '!' ? token.slice(1, nameEnd) : token.slice(0, nameEnd);
|
|
140
|
+
if (!ATTRIBUTE_NAME.test(name)) return null;
|
|
141
|
+
let state: AttributeState = equals === -1 ? true : token.slice(equals + 1);
|
|
142
|
+
if (prefix === '-') state = false;
|
|
143
|
+
if (prefix === '!') state = null;
|
|
144
|
+
assignments.push([name, state]);
|
|
145
|
+
}
|
|
146
|
+
return assignments;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const C_ESCAPES = new Map([
|
|
150
|
+
['a', 7],
|
|
151
|
+
['b', 8],
|
|
152
|
+
['f', 12],
|
|
153
|
+
['n', 10],
|
|
154
|
+
['r', 13],
|
|
155
|
+
['t', 9],
|
|
156
|
+
['v', 11],
|
|
157
|
+
['\\', 92],
|
|
158
|
+
['"', 34],
|
|
159
|
+
]);
|
|
160
|
+
|
|
161
|
+
/** A C-style quoted pattern (git's `unquote_c_style`, octal escapes being UTF-8 bytes); `null` when malformed. */
|
|
162
|
+
function unquoteC(line: string): { value: string; rest: string } | null {
|
|
163
|
+
const encoder = new TextEncoder();
|
|
164
|
+
const bytes: number[] = [];
|
|
165
|
+
for (let i = 1; i < line.length; i += 1) {
|
|
166
|
+
const char = String.fromCodePoint(line.codePointAt(i) ?? 0);
|
|
167
|
+
if (char === '"') return { value: new TextDecoder().decode(new Uint8Array(bytes)), rest: line.slice(i + 1) };
|
|
168
|
+
if (char !== '\\') {
|
|
169
|
+
bytes.push(...encoder.encode(char));
|
|
170
|
+
i += char.length - 1;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const octal = /^[0-3][0-7]{2}/.exec(line.slice(i + 1, i + 4));
|
|
174
|
+
if (octal !== null) {
|
|
175
|
+
bytes.push(Number.parseInt(octal[0], 8));
|
|
176
|
+
i += 3;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
const escaped = C_ESCAPES.get(line[i + 1] ?? '');
|
|
180
|
+
if (escaped === undefined) return null;
|
|
181
|
+
bytes.push(escaped);
|
|
182
|
+
i += 1;
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A pattern character as a regular-expression escape, valid inside and outside a class. */
|
|
188
|
+
function unit(char: string): string {
|
|
189
|
+
return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** wildmatch's POSIX classes. */
|
|
193
|
+
const POSIX_CLASSES = new Map([
|
|
194
|
+
['alnum', '0-9A-Za-z'],
|
|
195
|
+
['alpha', 'A-Za-z'],
|
|
196
|
+
['blank', ' \\t'],
|
|
197
|
+
['cntrl', '\\x00-\\x1f\\x7f'],
|
|
198
|
+
['digit', '0-9'],
|
|
199
|
+
['graph', '!-~'],
|
|
200
|
+
['lower', 'a-z'],
|
|
201
|
+
['print', ' -~'],
|
|
202
|
+
['punct', '!-/:-@\\[-`{-~'],
|
|
203
|
+
['space', ' \\t\\n\\v\\f\\r'],
|
|
204
|
+
['upper', 'A-Z'],
|
|
205
|
+
['xdigit', '0-9A-Fa-f'],
|
|
206
|
+
]);
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* A git glob as an anchored, case-insensitive RegExp with wildmatch's path rules: `*` and `?` stay within one folder,
|
|
210
|
+
* `**` between slashes spans any number of folders, `[...]` never matches a slash. `null` for a pattern wildmatch
|
|
211
|
+
* aborts on (an unclosed class, a trailing backslash), which matches nothing.
|
|
212
|
+
*/
|
|
213
|
+
function wildmatchRegExp(glob: string): RegExp | null {
|
|
214
|
+
let source = '';
|
|
215
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
216
|
+
const char = glob[i] ?? '';
|
|
217
|
+
if (char === '\\') {
|
|
218
|
+
i += 1;
|
|
219
|
+
const escaped = glob[i];
|
|
220
|
+
if (escaped === undefined) return null;
|
|
221
|
+
source += unit(escaped);
|
|
222
|
+
} else if (char === '*') {
|
|
223
|
+
let end = i;
|
|
224
|
+
while (glob[end + 1] === '*') end += 1;
|
|
225
|
+
const next = glob[end + 1];
|
|
226
|
+
if (end > i && (i === 0 || glob[i - 1] === '/') && (next === undefined || next === '/')) {
|
|
227
|
+
source += next === '/' ? '(?:.*/)?' : '.*';
|
|
228
|
+
if (next === '/') end += 1;
|
|
229
|
+
} else {
|
|
230
|
+
source += '[^/]*';
|
|
231
|
+
}
|
|
232
|
+
i = end;
|
|
233
|
+
} else if (char === '?') {
|
|
234
|
+
source += '[^/]';
|
|
235
|
+
} else if (char === '[') {
|
|
236
|
+
const characterClass = classSource(glob, i);
|
|
237
|
+
if (characterClass === null) return null;
|
|
238
|
+
source += characterClass.source;
|
|
239
|
+
i = characterClass.end;
|
|
240
|
+
} else {
|
|
241
|
+
source += unit(char);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return new RegExp(`^${source}$`, 'i');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The class opening at `glob[open]` and the index of its `]`, as wildmatch reads it; `null` when it aborts. */
|
|
248
|
+
function classSource(glob: string, open: number): { source: string; end: number } | null {
|
|
249
|
+
let i = open + 1;
|
|
250
|
+
const negated = glob[i] === '!' || glob[i] === '^';
|
|
251
|
+
if (negated) i += 1;
|
|
252
|
+
let body = '';
|
|
253
|
+
let previous: string | null = null;
|
|
254
|
+
// A `]` right after the opening is a member, not the end.
|
|
255
|
+
for (let first = true; first || glob[i] !== ']'; i += 1, first = false) {
|
|
256
|
+
const char = glob[i];
|
|
257
|
+
if (char === undefined) return null;
|
|
258
|
+
if (char === '\\') {
|
|
259
|
+
i += 1;
|
|
260
|
+
const escaped = glob[i];
|
|
261
|
+
if (escaped === undefined) return null;
|
|
262
|
+
body += unit(escaped);
|
|
263
|
+
previous = escaped;
|
|
264
|
+
} else if (char === '-' && previous !== null && glob[i + 1] !== undefined && glob[i + 1] !== ']') {
|
|
265
|
+
i += 1;
|
|
266
|
+
if (glob[i] === '\\') i += 1;
|
|
267
|
+
const last = glob[i];
|
|
268
|
+
if (last === undefined) return null;
|
|
269
|
+
// A range written backwards adds nothing in wildmatch (its start stays a member); a RegExp would throw.
|
|
270
|
+
if (previous <= last) body += `-${unit(last)}`;
|
|
271
|
+
previous = null;
|
|
272
|
+
} else if (char === '[' && glob[i + 1] === ':') {
|
|
273
|
+
const close = glob.indexOf(']', i + 2);
|
|
274
|
+
if (close === -1) return null;
|
|
275
|
+
if (close - 1 >= i + 2 && glob[close - 1] === ':') {
|
|
276
|
+
const posix = POSIX_CLASSES.get(glob.slice(i + 2, close - 1));
|
|
277
|
+
if (posix === undefined) return null;
|
|
278
|
+
body += posix;
|
|
279
|
+
previous = null;
|
|
280
|
+
i = close;
|
|
281
|
+
} else {
|
|
282
|
+
body += unit(char);
|
|
283
|
+
previous = char;
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
body += unit(char);
|
|
287
|
+
previous = char;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return { source: `(?!/)[${negated ? '^' : ''}${body}]`, end: i };
|
|
291
|
+
}
|
package/src/site.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ContentAPI } from './content-api.interface.js';
|
|
2
|
-
import { localesOf } from './content-utils.js';
|
|
2
|
+
import { isReservedPathname, localesOf } from './content-utils.js';
|
|
3
3
|
import type { SiteIndex } from './site-index.js';
|
|
4
4
|
import type { ContentManifest, CreatePageInput, CreateResult, MoveResult, SiteFilters } from './types.js';
|
|
5
5
|
|
|
@@ -134,6 +134,8 @@ export class Site {
|
|
|
134
134
|
|
|
135
135
|
// Validate pathname is available (not taken or in redirects)
|
|
136
136
|
isPathnameAvailable(pathname: string, locale: string, excludeId?: string): boolean {
|
|
137
|
+
if (isReservedPathname(pathname)) return false;
|
|
138
|
+
|
|
137
139
|
// Check if pathname is already taken
|
|
138
140
|
const existing = this.getByPathname(pathname, locale);
|
|
139
141
|
if (existing && existing.id !== excludeId) {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const CHECKSUM_LINE = /^ {2}checksum: "sha256:([0-9a-f]{64})"$/;
|
|
4
|
+
const VERSION_LINE = /^ {2}version: ".*"$/;
|
|
5
|
+
|
|
6
|
+
/** Hex sha256 of a skill page, CRLF read as LF so a Windows checkout of an unedited page hashes the same. */
|
|
7
|
+
export function skillChecksum(text: string): string {
|
|
8
|
+
return createHash('sha256').update(text.replaceAll('\r\n', '\n')).digest('hex');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** The index of the frontmatter's closing `---` line, -1 when the page opens without frontmatter. */
|
|
12
|
+
function frontmatterEnd(lines: string[]): number {
|
|
13
|
+
return lines[0] === '---' ? lines.indexOf('---', 1) : -1;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The index of the `metadata:` line inside the frontmatter, -1 when there is none. */
|
|
17
|
+
function metadataLine(lines: string[]): number {
|
|
18
|
+
const index = lines.indexOf('metadata:', 1);
|
|
19
|
+
return index !== -1 && index < frontmatterEnd(lines) ? index : -1;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The template with its release and the checksum of the template itself recorded at the end of its frontmatter. */
|
|
23
|
+
export function stampSkill(template: string, version: string): string {
|
|
24
|
+
const lines = template.split('\n');
|
|
25
|
+
const end = frontmatterEnd(lines);
|
|
26
|
+
if (end === -1) throw new Error('the skill template has no frontmatter to stamp');
|
|
27
|
+
if (metadataLine(lines) !== -1) throw new Error('the skill template already carries a metadata: block');
|
|
28
|
+
lines.splice(end, 0, 'metadata:', ` version: "${version}"`, ` checksum: "sha256:${skillChecksum(template)}"`);
|
|
29
|
+
return lines.join('\n');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Whether a skill page is still the text a release wrote: a stamped page must hash, stamp removed, to its recorded
|
|
34
|
+
* checksum; an unstamped page must hash to one of the given released checksums.
|
|
35
|
+
*/
|
|
36
|
+
export function isUneditedSkill(text: string, legacyChecksums: readonly string[]): boolean {
|
|
37
|
+
const lines = text.replaceAll('\r\n', '\n').split('\n');
|
|
38
|
+
const at = metadataLine(lines);
|
|
39
|
+
const checksum = at === -1 ? undefined : CHECKSUM_LINE.exec(lines[at + 2] ?? '')?.[1];
|
|
40
|
+
if (checksum === undefined || !VERSION_LINE.test(lines[at + 1] ?? '')) {
|
|
41
|
+
return legacyChecksums.includes(skillChecksum(text));
|
|
42
|
+
}
|
|
43
|
+
lines.splice(at, 3);
|
|
44
|
+
return skillChecksum(lines.join('\n')) === checksum;
|
|
45
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server-side SVG sanitiser: an uploaded SVG keeps its drawing and loses everything that could run or call out —
|
|
3
|
+
* scripts, event handlers, `foreignObject`, animation, external references, style that loads anything and namespaces
|
|
4
|
+
* other than SVG and XLink — and the photos embedded in it lose their metadata. Allowlist based on `svgo/browser`,
|
|
5
|
+
* which runs in Node, Bun and workerd alike. Node-free but not in the browser barrel: svgo is reached through
|
|
6
|
+
* `@conloca/content-api/upload-bytes` only.
|
|
7
|
+
*/
|
|
8
|
+
import { optimize, type XastChild, type XastElement, type XastParent } from 'svgo/browser';
|
|
9
|
+
import { stripImageMetadata } from './image-metadata.js';
|
|
10
|
+
|
|
11
|
+
/** The largest SVG the sanitiser parses, and the largest it returns once its entities are expanded. */
|
|
12
|
+
const MAX_SVG_CHARS = 5 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
/** The largest DOCTYPE internal subset parsed: room for Illustrator's namespace entities (about 1 KB), not a bomb. */
|
|
15
|
+
const MAX_DOCTYPE_SUBSET_CHARS = 4 * 1024;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Elements kept, filter primitives by their exact names; every other element goes with its subtree, and `a` is
|
|
19
|
+
* unwrapped. A prefixed name (`fe:script`) is never in the list, whatever namespace its prefix is bound to.
|
|
20
|
+
*/
|
|
21
|
+
const KEPT_ELEMENTS = new Set([
|
|
22
|
+
'svg',
|
|
23
|
+
'g',
|
|
24
|
+
'defs',
|
|
25
|
+
'symbol',
|
|
26
|
+
'use',
|
|
27
|
+
'path',
|
|
28
|
+
'rect',
|
|
29
|
+
'circle',
|
|
30
|
+
'ellipse',
|
|
31
|
+
'line',
|
|
32
|
+
'polyline',
|
|
33
|
+
'polygon',
|
|
34
|
+
'text',
|
|
35
|
+
'tspan',
|
|
36
|
+
'textPath',
|
|
37
|
+
'linearGradient',
|
|
38
|
+
'radialGradient',
|
|
39
|
+
'stop',
|
|
40
|
+
'pattern',
|
|
41
|
+
'clipPath',
|
|
42
|
+
'mask',
|
|
43
|
+
'marker',
|
|
44
|
+
'filter',
|
|
45
|
+
'image',
|
|
46
|
+
'style',
|
|
47
|
+
'title',
|
|
48
|
+
'desc',
|
|
49
|
+
'switch',
|
|
50
|
+
'feBlend',
|
|
51
|
+
'feColorMatrix',
|
|
52
|
+
'feComponentTransfer',
|
|
53
|
+
'feComposite',
|
|
54
|
+
'feConvolveMatrix',
|
|
55
|
+
'feDiffuseLighting',
|
|
56
|
+
'feDisplacementMap',
|
|
57
|
+
'feDistantLight',
|
|
58
|
+
'feDropShadow',
|
|
59
|
+
'feFlood',
|
|
60
|
+
'feFuncA',
|
|
61
|
+
'feFuncB',
|
|
62
|
+
'feFuncG',
|
|
63
|
+
'feFuncR',
|
|
64
|
+
'feGaussianBlur',
|
|
65
|
+
'feImage',
|
|
66
|
+
'feMerge',
|
|
67
|
+
'feMergeNode',
|
|
68
|
+
'feMorphology',
|
|
69
|
+
'feOffset',
|
|
70
|
+
'fePointLight',
|
|
71
|
+
'feSpecularLighting',
|
|
72
|
+
'feSpotLight',
|
|
73
|
+
'feTile',
|
|
74
|
+
'feTurbulence',
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
/** The namespaces an `xmlns` attribute may declare; any other declaration is removed with the attributes using it. */
|
|
78
|
+
const KEPT_NAMESPACES = new Set(['http://www.w3.org/2000/svg', 'http://www.w3.org/1999/xlink']);
|
|
79
|
+
|
|
80
|
+
/** A link may point inside the file or hold an embedded PNG, JPEG or WebP, nothing else. */
|
|
81
|
+
const SAFE_HREF = /^(?:#|data:image\/(?:png|jpeg|webp);base64,)/i;
|
|
82
|
+
|
|
83
|
+
/** A `url(` target that stays inside the file or is an embedded font or PNG, JPEG or WebP. */
|
|
84
|
+
const SAFE_URL_TARGET = /^(?:#|data:font\/|data:image\/(?:png|jpeg|webp);base64,)/i;
|
|
85
|
+
|
|
86
|
+
const URL_TARGET = /url\(\s*['"]?\s*([^'")\s]*)/gi;
|
|
87
|
+
|
|
88
|
+
/** An embedded raster whose metadata is stripped; Inkscape wraps the base64 over several lines. */
|
|
89
|
+
const EMBEDDED_RASTER = /data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=\s]*)/gi;
|
|
90
|
+
|
|
91
|
+
/** `text` as a URL parser reads its scheme: character references decoded, ASCII whitespace and controls dropped. */
|
|
92
|
+
function schemeText(text: string): string {
|
|
93
|
+
const decoded = text.replace(/&#(x[0-9a-f]+|[0-9]+);?/gi, (_reference, code: string) => {
|
|
94
|
+
const point = /^x/i.test(code) ? Number.parseInt(code.slice(1), 16) : Number(code);
|
|
95
|
+
return point <= 0x10ffff ? String.fromCodePoint(point) : '';
|
|
96
|
+
});
|
|
97
|
+
let scheme = '';
|
|
98
|
+
for (const char of decoded) if (char > ' ' && char !== '\x7f') scheme += char;
|
|
99
|
+
return scheme.toLowerCase();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Style or attribute text that could load something or run script; the attribute or element carrying it is removed. */
|
|
103
|
+
function isDangerous(text: string): boolean {
|
|
104
|
+
const lower = text.toLowerCase();
|
|
105
|
+
if (
|
|
106
|
+
lower.includes('@import') ||
|
|
107
|
+
lower.includes('\\') ||
|
|
108
|
+
lower.includes('expression(') ||
|
|
109
|
+
lower.includes('image-set(') ||
|
|
110
|
+
schemeText(text).includes('javascript:')
|
|
111
|
+
) {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
for (const [, target] of text.matchAll(URL_TARGET)) if (!SAFE_URL_TARGET.test(target ?? '')) return true;
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** `text` with every embedded PNG, JPEG or WebP re-encoded without its metadata; null when one cannot be read. */
|
|
119
|
+
function withStrippedRasters(text: string): string | null {
|
|
120
|
+
let unreadable = false;
|
|
121
|
+
const out = text.replace(EMBEDDED_RASTER, (embedded, type: string, data: string) => {
|
|
122
|
+
const format = type.toLowerCase();
|
|
123
|
+
let bytes: Uint8Array;
|
|
124
|
+
try {
|
|
125
|
+
bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0));
|
|
126
|
+
} catch {
|
|
127
|
+
unreadable = true;
|
|
128
|
+
return embedded;
|
|
129
|
+
}
|
|
130
|
+
const stripped =
|
|
131
|
+
format === 'png' || format === 'jpeg' || format === 'webp' ? stripImageMetadata(bytes, format) : null;
|
|
132
|
+
if (stripped === null) {
|
|
133
|
+
unreadable = true;
|
|
134
|
+
return embedded;
|
|
135
|
+
}
|
|
136
|
+
let binary = '';
|
|
137
|
+
for (let at = 0; at < stripped.length; at += 0x8000) {
|
|
138
|
+
binary += String.fromCharCode(...stripped.subarray(at, at + 0x8000));
|
|
139
|
+
}
|
|
140
|
+
return `data:image/${format};base64,${btoa(binary)}`;
|
|
141
|
+
});
|
|
142
|
+
return unreadable ? null : out;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The characters the DOCTYPE internal subsets of `text` hold, read as the parser reads them: a `]` or `>` inside quotes
|
|
147
|
+
* ends nothing. Every scan starts where the previous one stopped, so it stays linear.
|
|
148
|
+
*/
|
|
149
|
+
function doctypeSubsetChars(text: string): number {
|
|
150
|
+
const doctype = /<!DOCTYPE/gi;
|
|
151
|
+
let chars = 0;
|
|
152
|
+
while (doctype.exec(text) !== null) {
|
|
153
|
+
let inSubset = false;
|
|
154
|
+
let quote: string | null = null;
|
|
155
|
+
let at = doctype.lastIndex;
|
|
156
|
+
for (; at < text.length; at += 1) {
|
|
157
|
+
const char = text[at];
|
|
158
|
+
if (inSubset) chars += 1;
|
|
159
|
+
if (quote !== null) {
|
|
160
|
+
if (char === quote) quote = null;
|
|
161
|
+
} else if (char === '"' || char === "'") quote = char;
|
|
162
|
+
else if (inSubset) inSubset = char !== ']';
|
|
163
|
+
else if (char === '[') inSubset = true;
|
|
164
|
+
else if (char === '>') break;
|
|
165
|
+
}
|
|
166
|
+
doctype.lastIndex = at;
|
|
167
|
+
}
|
|
168
|
+
return chars;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function detach(node: XastChild, parent: XastParent): void {
|
|
172
|
+
parent.children = parent.children.filter((child) => child !== node);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function cleanAttributes(element: XastElement): void {
|
|
176
|
+
for (const [name, value] of Object.entries(element.attributes)) {
|
|
177
|
+
const lower = name.toLowerCase();
|
|
178
|
+
const colon = lower.indexOf(':');
|
|
179
|
+
const prefix = colon === -1 ? '' : lower.slice(0, colon);
|
|
180
|
+
const local = lower.slice(colon + 1);
|
|
181
|
+
const refused =
|
|
182
|
+
prefix === 'xmlns' || lower === 'xmlns'
|
|
183
|
+
? !KEPT_NAMESPACES.has(value)
|
|
184
|
+
: (prefix !== '' && prefix !== 'xlink' && prefix !== 'xml') ||
|
|
185
|
+
local.startsWith('on') ||
|
|
186
|
+
lower === 'xml:base' ||
|
|
187
|
+
(local === 'href' && !SAFE_HREF.test(value)) ||
|
|
188
|
+
isDangerous(value);
|
|
189
|
+
const cleaned = refused ? null : withStrippedRasters(value);
|
|
190
|
+
if (cleaned === null) delete element.attributes[name];
|
|
191
|
+
else element.attributes[name] = cleaned;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* `text` with only drawing left in it, or `null` when it cannot be parsed, is larger than 5 MiB before or after its
|
|
197
|
+
* entities are expanded, declares more than 4 KB in its DOCTYPE, or its root is not exactly one `<svg>` element.
|
|
198
|
+
* Undeclared namespace prefixes fail the parse; DOCTYPEs are dropped after their internal entities are expanded; an
|
|
199
|
+
* embedded photo that cannot be read goes with the attribute or style holding it.
|
|
200
|
+
*/
|
|
201
|
+
export function sanitizeSvg(text: string): string | null {
|
|
202
|
+
if (text.length > MAX_SVG_CHARS || doctypeSubsetChars(text) > MAX_DOCTYPE_SUBSET_CHARS) return null;
|
|
203
|
+
let rootIsSvg = false;
|
|
204
|
+
try {
|
|
205
|
+
const { data } = optimize(text, {
|
|
206
|
+
plugins: [
|
|
207
|
+
{
|
|
208
|
+
name: 'conlocaAllowlist',
|
|
209
|
+
fn: () => ({
|
|
210
|
+
doctype: { enter: detach },
|
|
211
|
+
instruction: {
|
|
212
|
+
enter: (node, parent) => {
|
|
213
|
+
if (node.name !== 'xml') detach(node, parent);
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
element: {
|
|
217
|
+
enter: (node, parent) => {
|
|
218
|
+
if (node.name === 'a') return;
|
|
219
|
+
const styleText =
|
|
220
|
+
node.name === 'style'
|
|
221
|
+
? node.children.map((child) => ('value' in child ? child.value : '')).join('')
|
|
222
|
+
: '';
|
|
223
|
+
if (!KEPT_ELEMENTS.has(node.name) || isDangerous(styleText)) {
|
|
224
|
+
detach(node, parent);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (node.name === 'style') {
|
|
228
|
+
for (const child of node.children) {
|
|
229
|
+
if (!('value' in child)) continue;
|
|
230
|
+
const cleaned = withStrippedRasters(child.value);
|
|
231
|
+
if (cleaned === null) {
|
|
232
|
+
detach(node, parent);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
child.value = cleaned;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
cleanAttributes(node);
|
|
239
|
+
},
|
|
240
|
+
exit: (node, parent) => {
|
|
241
|
+
// Unwrapped after its children were cleaned; a new array, so the parent's walk is not disturbed.
|
|
242
|
+
if (node.name === 'a')
|
|
243
|
+
parent.children = parent.children.flatMap((c) => (c === node ? node.children : [c]));
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
root: {
|
|
247
|
+
exit: (root) => {
|
|
248
|
+
const elements = root.children.filter((child) => child.type === 'element');
|
|
249
|
+
rootIsSvg = elements.length === 1 && elements[0]?.name === 'svg';
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
}),
|
|
253
|
+
},
|
|
254
|
+
],
|
|
255
|
+
});
|
|
256
|
+
return rootIsSvg && data.length <= MAX_SVG_CHARS ? data : null;
|
|
257
|
+
} catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -384,6 +384,15 @@ export interface SitesConfig {
|
|
|
384
384
|
domains?: {
|
|
385
385
|
[locale: string]: string;
|
|
386
386
|
};
|
|
387
|
+
/** Path the site is served under, as Astro's `base`: starts and ends with `/`; default `/`. */
|
|
388
|
+
base?: string;
|
|
389
|
+
/**
|
|
390
|
+
* Address of a separate preview deployment for this site, per locale, each an `https://` origin. Once a workspace
|
|
391
|
+
* admin confirms it, every preview link of this site opens there.
|
|
392
|
+
*/
|
|
393
|
+
previewUrl?: {
|
|
394
|
+
[locale: string]: string;
|
|
395
|
+
};
|
|
387
396
|
/**
|
|
388
397
|
* Optional filesystem path for this site's mdx-type pages.
|
|
389
398
|
* When set, .mdx files under this path are surfaced in the CMS
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every server does to an upload's bytes before it measures and names them: read the real format, give the file
|
|
3
|
+
* that format's extension, strip photo metadata and sanitise SVG. A subpath export (`@conloca/content-api/upload-bytes`),
|
|
4
|
+
* off the barrel, so svgo stays out of browser bundles.
|
|
5
|
+
*/
|
|
6
|
+
import { sniffImageFormat } from './image-format.js';
|
|
7
|
+
import { stripImageMetadata } from './image-metadata.js';
|
|
8
|
+
import { sanitizeSvg } from './svg-sanitize.js';
|
|
9
|
+
import { unreadableImageRefusal } from './upload-refusals.js';
|
|
10
|
+
|
|
11
|
+
export { sniffImageFormat } from './image-format.js';
|
|
12
|
+
|
|
13
|
+
/** The upload ready to measure and name, or the sentence it is refused with. */
|
|
14
|
+
export type ConformedUpload = { ok: true; bytes: Uint8Array; filename: string } | { ok: false; refusal: string };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `bytes` as they are stored, under `filename` with the extension of the format they actually hold (`.jpg` for
|
|
18
|
+
* JPEG): JPEG, PNG and WebP without metadata, SVG sanitised, GIF, ICO and AVIF unchanged. Bytes that are no stored
|
|
19
|
+
* image format, or that cannot be stripped or sanitised, are refused as unreadable.
|
|
20
|
+
*/
|
|
21
|
+
export function conformUploadBytes(bytes: Uint8Array, filename: string): ConformedUpload {
|
|
22
|
+
const format = sniffImageFormat(bytes);
|
|
23
|
+
const unreadable: ConformedUpload = { ok: false, refusal: unreadableImageRefusal(filename) };
|
|
24
|
+
if (format === null) return unreadable;
|
|
25
|
+
const extension = format === 'jpeg' ? 'jpg' : format;
|
|
26
|
+
const dot = filename.lastIndexOf('.');
|
|
27
|
+
const named = dot > 0 ? filename.slice(dot + 1).toLowerCase() : '';
|
|
28
|
+
const sameFormat = named === extension || (format === 'jpeg' && named === 'jpeg');
|
|
29
|
+
const stored = sameFormat ? filename : `${dot > 0 ? filename.slice(0, dot) : filename}.${extension}`;
|
|
30
|
+
|
|
31
|
+
if (format === 'jpeg' || format === 'png' || format === 'webp') {
|
|
32
|
+
const stripped = stripImageMetadata(bytes, format);
|
|
33
|
+
return stripped === null ? unreadable : { ok: true, bytes: stripped, filename: stored };
|
|
34
|
+
}
|
|
35
|
+
if (format === 'svg') {
|
|
36
|
+
let text: string;
|
|
37
|
+
try {
|
|
38
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
39
|
+
} catch {
|
|
40
|
+
return unreadable;
|
|
41
|
+
}
|
|
42
|
+
const sanitized = sanitizeSvg(text);
|
|
43
|
+
return sanitized === null ? unreadable : { ok: true, bytes: new TextEncoder().encode(sanitized), filename: stored };
|
|
44
|
+
}
|
|
45
|
+
return { ok: true, bytes, filename: stored };
|
|
46
|
+
}
|