@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
@@ -0,0 +1,478 @@
1
+ /**
2
+ * The `fields` message: unsaved rich text, images, toggles and dates, as an
3
+ * editor changes them, for the overlay to show before the save. Pure: no DOM,
4
+ * no globals, so it is tested under plain `node --test`. The overlay
5
+ * (`./index.ts`) does the DOM half. Its one import, `./markdown.js`, is pure
6
+ * too.
7
+ *
8
+ * admin -> site fields { entryId, fields: [{ field, kind, value, saved }] }
9
+ *
10
+ * kind "html" value, saved: the HTML field's HTML, as the editor stores it
11
+ * kind "markdown" value, saved: a Rich Text field's value: markdown source,
12
+ * or the HTML Capa's rich text editor writes into it
13
+ * kind "image" value, saved: { url, alt } | null
14
+ * kind "boolean" value, saved: "true" | "false"
15
+ * kind "date" value, saved: "YYYY-MM-DD" | ""
16
+ *
17
+ * Sent only to an overlay whose `ready` lists "fields" (`SITE_FEATURES`), and
18
+ * only where the project has the feature on, so an older overlay never gets
19
+ * one; it would drop an unknown type anyway.
20
+ *
21
+ * THE RULE IS THE TEXT PATCH'S: change only what the page drew from the saved
22
+ * value, exactly, so whatever the site does to a value on its own (a
23
+ * sanitizer, a date format, a resized image URL, markup around it) is either
24
+ * reproduced or left alone until the save re-renders it.
25
+ *
26
+ * html an element whose content IS the saved HTML (compared after the
27
+ * sanitizer below, whitespace aside) gets the new HTML, sanitized,
28
+ * built node by node, never through `innerHTML`.
29
+ * markdown the page shows the site's own rendering of the saved markdown,
30
+ * which nothing here can reproduce, so the element is found by
31
+ * its tag alone: the element `capaAttrs` tagged with the field
32
+ * gets the new value rendered (`richTextHtml`), then put through
33
+ * the same sanitizer as html. A page that tags no element for the
34
+ * field is left as it is.
35
+ * image an `<img>` or `<source>` whose `src` or `srcset` holds the saved
36
+ * image's URL gets the new one in its place, so the site's resize
37
+ * parameters stay; its `alt` follows while it reads the saved alt.
38
+ * boolean an element tagged `data-capa-shown-when` is shown while the value
39
+ * is that, and hidden otherwise; text that reads "true" or "false"
40
+ * follows as text.
41
+ * date text the site formatted from the saved day with a format this
42
+ * module can reproduce (`findDateFormat`) gets the new day in the
43
+ * same format, and a `<time datetime>` follows.
44
+ */
45
+ import { renderMarkdown } from "./markdown.js";
46
+ /** A `fields` message past these is refused whole, like a `patch`. */
47
+ export const FIELDS_MAX_FIELDS = 500;
48
+ export const FIELDS_MAX_LENGTH = 100_000;
49
+ const DATE_VALUE = /^(\d{4}-\d{2}-\d{2})?$/;
50
+ function image(raw) {
51
+ if (raw === null)
52
+ return null;
53
+ if (typeof raw !== "object" || Array.isArray(raw))
54
+ return undefined;
55
+ const m = raw;
56
+ if (typeof m.url !== "string" || m.url === "" || m.url.length > 4096)
57
+ return undefined;
58
+ if (typeof m.alt !== "string" || m.alt.length > FIELDS_MAX_LENGTH)
59
+ return undefined;
60
+ return { url: m.url, alt: m.alt };
61
+ }
62
+ /** The fields of a `fields` message, checked, or null to refuse the message whole. */
63
+ export function acceptLiveFields(raw) {
64
+ if (!Array.isArray(raw) || raw.length > FIELDS_MAX_FIELDS)
65
+ return null;
66
+ const out = [];
67
+ for (const item of raw) {
68
+ if (typeof item !== "object" || item === null)
69
+ return null;
70
+ const f = item;
71
+ if (typeof f.field !== "string" || f.field === "")
72
+ return null;
73
+ switch (f.kind) {
74
+ case "html":
75
+ case "markdown":
76
+ if (typeof f.value !== "string" || typeof f.saved !== "string")
77
+ return null;
78
+ if (f.value.length > FIELDS_MAX_LENGTH || f.saved.length > FIELDS_MAX_LENGTH)
79
+ return null;
80
+ out.push({ field: f.field, kind: f.kind, value: f.value, saved: f.saved });
81
+ break;
82
+ case "boolean":
83
+ if ((f.value !== "true" && f.value !== "false") || (f.saved !== "true" && f.saved !== "false"))
84
+ return null;
85
+ out.push({ field: f.field, kind: "boolean", value: f.value, saved: f.saved });
86
+ break;
87
+ case "date":
88
+ if (typeof f.value !== "string" || typeof f.saved !== "string")
89
+ return null;
90
+ if (!DATE_VALUE.test(f.value) || !DATE_VALUE.test(f.saved))
91
+ return null;
92
+ out.push({ field: f.field, kind: "date", value: f.value, saved: f.saved });
93
+ break;
94
+ case "image": {
95
+ const value = image(f.value);
96
+ const saved = image(f.saved);
97
+ if (value === undefined || saved === undefined)
98
+ return null;
99
+ out.push({ field: f.field, kind: "image", value, saved });
100
+ break;
101
+ }
102
+ default:
103
+ // A kind this overlay does not know: a newer admin. Skip it, keep the rest.
104
+ break;
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
110
+ const RAW_TEXT = new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript"]);
111
+ const MAX_DEPTH = 64;
112
+ const ENTITIES = {
113
+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®",
114
+ trade: "™", hellip: "…", mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’",
115
+ ldquo: "“", rdquo: "”", bull: "•", middot: "·", euro: "€", pound: "£",
116
+ yen: "¥", cent: "¢", deg: "°", times: "×", divide: "÷", laquo: "«", raquo: "»",
117
+ };
118
+ function decodeEntities(text) {
119
+ return text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (whole, entity) => {
120
+ if (entity[0] === "#") {
121
+ const code = entity[1] === "x" || entity[1] === "X" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10);
122
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
123
+ }
124
+ return ENTITIES[entity.toLowerCase()] ?? whole;
125
+ });
126
+ }
127
+ const TAG_OPEN = /<([a-zA-Z][a-zA-Z0-9-]*)/y;
128
+ const TAG_CLOSE = /<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>/y;
129
+ const ATTRIBUTE = /\s+([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/y;
130
+ const TAG_END = /\s*(\/?)>/y;
131
+ /**
132
+ * The HTML as a tree, or null when it is not markup this module reads with
133
+ * confidence (an unclosed tag or comment, nesting deeper than 64). Strict on
134
+ * purpose: rich text from Capa's editor is well formed, and a value that is
135
+ * not is left for the save to show.
136
+ */
137
+ export function parseHtml(html) {
138
+ const root = { tag: "#root", attrs: [], children: [] };
139
+ const stack = [root];
140
+ let i = 0;
141
+ const text = (value) => {
142
+ if (value !== "")
143
+ stack[stack.length - 1].children.push(decodeEntities(value));
144
+ };
145
+ while (i < html.length) {
146
+ const lt = html.indexOf("<", i);
147
+ if (lt === -1) {
148
+ text(html.slice(i));
149
+ break;
150
+ }
151
+ text(html.slice(i, lt));
152
+ i = lt;
153
+ if (html.startsWith("<!--", i)) {
154
+ const end = html.indexOf("-->", i + 4);
155
+ if (end === -1)
156
+ return null;
157
+ i = end + 3;
158
+ continue;
159
+ }
160
+ TAG_CLOSE.lastIndex = i;
161
+ const close = TAG_CLOSE.exec(html);
162
+ if (close) {
163
+ const tag = close[1].toLowerCase();
164
+ const at = stack.map((e) => e.tag).lastIndexOf(tag);
165
+ if (at > 0)
166
+ stack.length = at;
167
+ i = TAG_CLOSE.lastIndex;
168
+ continue;
169
+ }
170
+ TAG_OPEN.lastIndex = i;
171
+ const open = TAG_OPEN.exec(html);
172
+ if (!open) {
173
+ text("<");
174
+ i += 1;
175
+ continue;
176
+ }
177
+ const tag = open[1].toLowerCase();
178
+ let at = TAG_OPEN.lastIndex;
179
+ const attrs = [];
180
+ for (;;) {
181
+ ATTRIBUTE.lastIndex = at;
182
+ const a = ATTRIBUTE.exec(html);
183
+ if (!a)
184
+ break;
185
+ attrs.push([a[1].toLowerCase(), decodeEntities(a[2] ?? a[3] ?? a[4] ?? "")]);
186
+ at = ATTRIBUTE.lastIndex;
187
+ }
188
+ TAG_END.lastIndex = at;
189
+ const end = TAG_END.exec(html);
190
+ if (!end)
191
+ return null;
192
+ i = TAG_END.lastIndex;
193
+ const element = { tag, attrs, children: [] };
194
+ stack[stack.length - 1].children.push(element);
195
+ if (RAW_TEXT.has(tag)) {
196
+ // Its content is not markup, and nothing that comes in one is kept.
197
+ const closeAt = html.toLowerCase().indexOf(`</${tag}`, i);
198
+ if (closeAt === -1)
199
+ return null;
200
+ const gt = html.indexOf(">", closeAt);
201
+ if (gt === -1)
202
+ return null;
203
+ i = gt + 1;
204
+ continue;
205
+ }
206
+ if (VOID.has(tag) || end[1] === "/")
207
+ continue;
208
+ if (stack.length > MAX_DEPTH)
209
+ return null;
210
+ stack.push(element);
211
+ }
212
+ return root.children;
213
+ }
214
+ /** Elements whose content is kept, without the element, when they are not allowed. Everything else not allowed goes with its content. */
215
+ const DROPPED_WHOLE = new Set([
216
+ "script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "form", "input",
217
+ "button", "textarea", "select", "option", "title", "head", "link", "meta", "base", "frame", "frameset",
218
+ "noembed", "noframes", "xmp", "video", "audio", "canvas", "applet", "dialog", "portal",
219
+ ]);
220
+ /** What the editors' rich text is made of (Quill's output, and markdown's rules), and the attributes each keeps. */
221
+ const ALLOWED = {
222
+ p: [], br: [], hr: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], blockquote: [], pre: ["data-language"],
223
+ ol: [], ul: [], li: ["data-list"], strong: [], b: [], em: [], i: [], u: [], s: [], strike: [], del: [],
224
+ sub: [], sup: [], code: [], span: [], a: ["href", "target", "rel"], img: ["src", "alt", "width", "height"],
225
+ };
226
+ const QUILL_CLASS = /^ql-[a-z0-9-]{1,40}$/;
227
+ const COLOUR = /^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+\s*)?\)|[a-z]{3,20})$/i;
228
+ /** A link target the page may follow: http(s), mailto, tel, or a path or fragment on the site. */
229
+ export function safeHref(href) {
230
+ const value = href.trim();
231
+ if (value === "")
232
+ return false;
233
+ if (/^(\/(?!\/)|#|\?|\.\.?\/)/.test(value))
234
+ return true;
235
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value);
236
+ if (!scheme)
237
+ return !/[\s\\]/.test(value) && !value.startsWith("//");
238
+ return ["http", "https", "mailto", "tel"].includes(scheme[1].toLowerCase());
239
+ }
240
+ /** An image address the page may load: an absolute http(s) URL. */
241
+ export function safeImageUrl(url) {
242
+ return /^https?:\/\/[^\s"'<>\\]+$/i.test(url.trim());
243
+ }
244
+ function keptStyle(style) {
245
+ const kept = [];
246
+ for (const part of style.split(";")) {
247
+ const colon = part.indexOf(":");
248
+ if (colon === -1)
249
+ continue;
250
+ const name = part.slice(0, colon).trim().toLowerCase();
251
+ const value = part.slice(colon + 1).trim();
252
+ if ((name === "color" || name === "background-color") && COLOUR.test(value))
253
+ kept.push(`${name}: ${value}`);
254
+ }
255
+ return kept.length > 0 ? kept.join("; ") : null;
256
+ }
257
+ function keptAttrs(tag, attrs) {
258
+ const own = ALLOWED[tag] ?? [];
259
+ const out = [];
260
+ for (const [name, value] of attrs) {
261
+ if (name === "class") {
262
+ const classes = value.split(/\s+/).filter((c) => QUILL_CLASS.test(c));
263
+ if (classes.length > 0)
264
+ out.push(["class", classes.join(" ")]);
265
+ }
266
+ else if (name === "style") {
267
+ const style = keptStyle(value);
268
+ if (style)
269
+ out.push(["style", style]);
270
+ }
271
+ else if (own.includes(name)) {
272
+ if (name === "href" && !safeHref(value))
273
+ continue;
274
+ if (name === "src" && !safeImageUrl(value))
275
+ continue;
276
+ if (name === "target" && value !== "_blank" && value !== "_self")
277
+ continue;
278
+ if ((name === "width" || name === "height") && !/^\d{1,5}$/.test(value))
279
+ continue;
280
+ out.push([name, value]);
281
+ }
282
+ }
283
+ if (tag === "a" && out.some(([n, v]) => n === "target" && v === "_blank") && !out.some(([n]) => n === "rel")) {
284
+ out.push(["rel", "noopener noreferrer"]);
285
+ }
286
+ return out;
287
+ }
288
+ /**
289
+ * Rich text cut down to what the editor makes: its blocks, its inline marks,
290
+ * links that go somewhere safe, http(s) images, Quill's `ql-` classes, and a
291
+ * colour. Scripts, frames, forms, embeds and every event handler are gone,
292
+ * with their content; any other element is unwrapped to its content.
293
+ */
294
+ export function sanitizeHtml(nodes, depth = 0) {
295
+ const out = [];
296
+ if (depth > MAX_DEPTH)
297
+ return out;
298
+ for (const node of nodes) {
299
+ if (typeof node === "string") {
300
+ out.push(node);
301
+ continue;
302
+ }
303
+ if (DROPPED_WHOLE.has(node.tag))
304
+ continue;
305
+ const children = VOID.has(node.tag) ? [] : sanitizeHtml(node.children, depth + 1);
306
+ if (!(node.tag in ALLOWED)) {
307
+ out.push(...children);
308
+ continue;
309
+ }
310
+ if (node.tag === "img" && !node.attrs.some(([n, v]) => n === "src" && safeImageUrl(v)))
311
+ continue;
312
+ out.push({ tag: node.tag, attrs: keptAttrs(node.tag, node.attrs), children });
313
+ }
314
+ return out;
315
+ }
316
+ /**
317
+ * One string per tree, for "does this element show exactly the saved rich
318
+ * text": attributes sorted, text with its runs of whitespace as one space,
319
+ * and text that is only whitespace left out, since a template's indentation
320
+ * between blocks is not content.
321
+ */
322
+ export function canonicalHtml(nodes) {
323
+ let out = "";
324
+ for (const node of nodes) {
325
+ if (typeof node === "string") {
326
+ const text = node.replace(/\s+/g, " ");
327
+ if (text.trim() !== "")
328
+ out += JSON.stringify(text);
329
+ continue;
330
+ }
331
+ const attrs = [...node.attrs].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
332
+ out += `<${node.tag}${attrs.map(([n, v]) => ` ${n}=${JSON.stringify(v)}`).join("")}>${canonicalHtml(node.children)}</${node.tag}>`;
333
+ }
334
+ return out;
335
+ }
336
+ /** The saved or new rich text, parsed and sanitized, with its canonical form. Null for HTML `parseHtml` refuses. */
337
+ export function preparedHtml(html) {
338
+ const parsed = parseHtml(html);
339
+ if (parsed === null)
340
+ return null;
341
+ const nodes = sanitizeHtml(parsed);
342
+ return { nodes, canonical: canonicalHtml(nodes) };
343
+ }
344
+ // -------------------------------------------------------------- markdown ---
345
+ /** An element tag at the start: `<p>`, `<div class="x">`, `<h1>`, `<!-- -->`. The admin's own rule (`markdown-field.ts`). */
346
+ const LEADING_TAG = /^<(?:[a-z][a-z0-9-]*(?:\s[^>]*)?\/?|!--[\s\S]*?--)>/i;
347
+ /**
348
+ * A Rich Text value as HTML for the sanitizer, the way the admin's editor
349
+ * reads it: HTML the editor wrote stays as it is, and markdown source is
350
+ * rendered (`renderMarkdown`). Never written to a page as it is: the overlay
351
+ * puts it through `preparedHtml` first.
352
+ */
353
+ export function richTextHtml(value) {
354
+ if (value === "")
355
+ return "";
356
+ return LEADING_TAG.test(value.trim()) ? value : renderMarkdown(value);
357
+ }
358
+ // ----------------------------------------------------------------- image ---
359
+ function pathOf(url) {
360
+ try {
361
+ const u = new URL(url);
362
+ return u.pathname.length > 1 ? { origin: u.origin, path: u.pathname } : null;
363
+ }
364
+ catch {
365
+ return null;
366
+ }
367
+ }
368
+ /**
369
+ * An `src` or `srcset` with the saved image swapped for the new one, or null
370
+ * when it does not hold the saved image. The saved URL is looked for as it
371
+ * is and URL-encoded (`/_next/image?url=...`), then, when both images are on
372
+ * the same host, by path alone, so an image service on another host that
373
+ * keeps the file's path (`https://img.example/t/a.jpg?w=800`) is followed.
374
+ * Whatever the site added around it, a width or a format, stays.
375
+ */
376
+ export function swapImageUrl(attr, saved, value) {
377
+ if (!saved || !value || !safeImageUrl(value))
378
+ return null;
379
+ const pairs = [
380
+ [saved, value],
381
+ [encodeURIComponent(saved), encodeURIComponent(value)],
382
+ ];
383
+ const from = pathOf(saved);
384
+ const to = pathOf(value);
385
+ if (from && to && from.origin === to.origin) {
386
+ pairs.push([from.path, to.path], [encodeURIComponent(from.path), encodeURIComponent(to.path)]);
387
+ }
388
+ for (const [a, b] of pairs) {
389
+ if (a.length > 1 && attr.includes(a))
390
+ return attr.split(a).join(b);
391
+ }
392
+ return null;
393
+ }
394
+ // ------------------------------------------------------------------ date ---
395
+ /** The formats a site is likely to print a day in, by id. */
396
+ const DATE_OPTIONS = {
397
+ full: { dateStyle: "full" },
398
+ long: { dateStyle: "long" },
399
+ medium: { dateStyle: "medium" },
400
+ short: { dateStyle: "short" },
401
+ dmy: { year: "numeric", month: "long", day: "numeric" },
402
+ dmyShort: { year: "numeric", month: "short", day: "numeric" },
403
+ dm: { month: "long", day: "numeric" },
404
+ dmShort: { month: "short", day: "numeric" },
405
+ numeric: { year: "numeric", month: "2-digit", day: "2-digit" },
406
+ weekday: { weekday: "long", year: "numeric", month: "long", day: "numeric" },
407
+ weekdayShort: { weekday: "short", month: "short", day: "numeric" },
408
+ my: { month: "long", year: "numeric" },
409
+ };
410
+ function dayOf(value) {
411
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
412
+ if (!m)
413
+ return null;
414
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
415
+ return Number.isNaN(d.getTime()) ? null : d;
416
+ }
417
+ /**
418
+ * A day as a format prints it. `raw` is the stored day (`2026-11-01`), `iso`
419
+ * the instant the API sends (`2026-11-01T00:00:00.000Z`), and
420
+ * `intl:<locale>:<id>` an `Intl.DateTimeFormat` in UTC, which is the day as
421
+ * stored: a calendar day is kept at midnight UTC. "" for an empty day.
422
+ */
423
+ export function formatDateAs(format, value) {
424
+ if (value === "")
425
+ return "";
426
+ const day = dayOf(value);
427
+ if (!day)
428
+ return null;
429
+ if (format === "raw")
430
+ return value;
431
+ if (format === "iso")
432
+ return day.toISOString();
433
+ const m = /^intl:([^:]*):(\w+)$/.exec(format);
434
+ if (!m || !DATE_OPTIONS[m[2]])
435
+ return null;
436
+ try {
437
+ return new Intl.DateTimeFormat(m[1] || undefined, { ...DATE_OPTIONS[m[2]], timeZone: "UTC" }).format(day);
438
+ }
439
+ catch {
440
+ return null;
441
+ }
442
+ }
443
+ /**
444
+ * The format the site printed the saved day in, when `text` is exactly the
445
+ * saved day in one of them (`formatDateAs`), trying the page's locales in
446
+ * order. Null when none reproduces it, and the text is left for the save.
447
+ */
448
+ export function findDateFormat(text, saved, locales) {
449
+ const wanted = text.trim();
450
+ if (wanted === "" || !dayOf(saved))
451
+ return null;
452
+ const formats = ["raw", "iso"];
453
+ const seen = new Set();
454
+ for (const locale of locales) {
455
+ const key = locale ?? "";
456
+ if (seen.has(key))
457
+ continue;
458
+ seen.add(key);
459
+ for (const id of Object.keys(DATE_OPTIONS))
460
+ formats.push(`intl:${key}:${id}`);
461
+ }
462
+ for (const format of formats) {
463
+ if (formatDateAs(format, saved) === wanted)
464
+ return format;
465
+ }
466
+ return null;
467
+ }
468
+ /** A `<time datetime>` with the saved day, in the same shape, or null when it is not the saved day. */
469
+ export function swapDatetime(datetime, saved, value) {
470
+ const day = dayOf(saved);
471
+ if (!day)
472
+ return null;
473
+ if (datetime === saved)
474
+ return value;
475
+ if (datetime === day.toISOString())
476
+ return value === "" ? "" : (dayOf(value)?.toISOString() ?? null);
477
+ return null;
478
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * A small markdown renderer, for live preview of Rich Text before the save
3
+ * (`./live-fields.ts`, kind "markdown"). Pure: no DOM, no globals, no
4
+ * imports, so it is tested under plain `node --test`.
5
+ *
6
+ * WHY ITS OWN. The package ships with no runtime dependencies, and the overlay
7
+ * adds nothing to a bundle that does not call it. A full CommonMark renderer
8
+ * would be the biggest thing in the overlay, for a view that lasts only until
9
+ * the save, when the site renders the field itself.
10
+ *
11
+ * WHAT IT READS. The blocks and marks a Rich Text field is written with:
12
+ *
13
+ * # to ###### headings, and setext (=== and --- under a line)
14
+ * paragraphs, with a hard break for two trailing spaces or a backslash
15
+ * **strong**, __strong__, *em*, _em_, ***both***, ~~strike~~
16
+ * [links](url "title"), [reference][links], <autolinks>, bare https:// URLs
17
+ * ![images](url)
18
+ * - * + bullet and 1. 1) ordered lists, nested, tight or loose
19
+ * `code`, ``` and ~~~ fences, and four-space indented code
20
+ * > blockquotes, nested
21
+ * --- *** ___ rules
22
+ * \ escapes, and HTML written into the markdown, passed through
23
+ *
24
+ * NOT SAFE ON ITS OWN, ON PURPOSE. It writes what the markdown says, raw HTML
25
+ * and `javascript:` links included. The overlay puts the result through the
26
+ * same parser and sanitizer as an HTML field (`preparedHtml`), which is what
27
+ * keeps scripts, handlers and unsafe links off the page. Text it writes is
28
+ * escaped, so only markup the source wrote reaches that sanitizer as markup.
29
+ *
30
+ * BOUNDED. Every scan is capped, so a 100,000-character value renders in
31
+ * linear time, and nesting stops at 32 levels.
32
+ */
33
+ /**
34
+ * Markdown as HTML, for the overlay's sanitizer: never written to a page as
35
+ * it is. Link reference definitions (`[label]: url`) are read first and give
36
+ * no output of their own.
37
+ */
38
+ export declare function renderMarkdown(source: string): string;