@crossworks/content-core 0.400.13 → 0.400.15

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crossworks/content-core",
3
- "version": "0.400.13",
3
+ "version": "0.400.15",
4
4
  "description": "Browser-safe content logic — markdown, blocks, pages, tables, formulas — shared by the server and any client. Zero server deps by design: nothing here may reach @mantle/db, node-only APIs, or the network (the jackdaw-repo-split P0 boundary).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -9,6 +9,7 @@
9
9
  "./block-ids": "./src/block-ids.ts",
10
10
  "./block-list": "./src/block-list.ts",
11
11
  "./canvas": "./src/canvas.ts",
12
+ "./canvas-data": "./src/canvas-data.ts",
12
13
  "./contacts-format": "./src/contacts-format.ts",
13
14
  "./doc-to-markdown": "./src/doc-to-markdown.ts",
14
15
  "./drift-spec": "./src/drift-spec.ts",
@@ -36,8 +37,8 @@
36
37
  "./tree": "./src/tree.ts"
37
38
  },
38
39
  "dependencies": {
39
- "@mantle/client-types": "npm:@crossworks/client-types@0.400.13",
40
- "marked": "^18.1.0",
40
+ "@mantle/client-types": "npm:@crossworks/client-types@0.400.15",
41
+ "marked": "^18.1.1",
41
42
  "mathjs": "15.2.0"
42
43
  },
43
44
  "license": "SEE LICENSE IN LICENSE.md",
package/src/app-nav.ts CHANGED
@@ -26,10 +26,9 @@ import {
26
26
  type AppNavFolder,
27
27
  type AppTint,
28
28
  } from '@mantle/client-types/app-nav';
29
+ import { UUID_RE } from './uuid';
29
30
 
30
- /** Either case, as @mantle/std's UUID_RE (this published package takes no
31
- * dependency): asId lower-cases before it tests, so an id reads as before. */
32
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31
+ // Either case (./uuid): asId lower-cases before it tests, so an id reads as before.
33
32
  const LUCIDE_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
34
33
 
35
34
  function asId(raw: unknown): string | undefined {
@@ -0,0 +1,125 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ CANVAS_DATA_CANVAS_MAX_BYTES,
4
+ CANVAS_DATA_CANVAS_MAX_KEYS,
5
+ CANVAS_DATA_MAX_DEPTH,
6
+ CANVAS_DATA_MINE_ALL_MAX_BYTES,
7
+ CANVAS_DATA_MINE_ALL_MAX_KEYS,
8
+ CANVAS_DATA_VALUE_MAX_BYTES,
9
+ canvasDataValue,
10
+ isCanvasDataBucket,
11
+ isCanvasDataKey,
12
+ isCanvasDataLoginId,
13
+ isCanvasDataOp,
14
+ readCanvasDataJson,
15
+ utf8Bytes,
16
+ } from './canvas-data';
17
+
18
+ describe('canvas data contract', () => {
19
+ it('knows its two buckets and nothing else', () => {
20
+ expect(isCanvasDataBucket('shared')).toBe(true);
21
+ expect(isCanvasDataBucket('mine')).toBe(true);
22
+ for (const b of ['', 'Shared', 'others', 'all', null, 1, {}]) {
23
+ expect(isCanvasDataBucket(b)).toBe(false);
24
+ }
25
+ });
26
+
27
+ it('takes a login id as the store gives it: a lowercase uuid', () => {
28
+ expect(isCanvasDataLoginId('00000000-0000-4000-8000-00000000000a')).toBe(true);
29
+ for (const v of ['00000000-0000-4000-8000-00000000000A', 'not-a-uuid', '', null, 1]) {
30
+ expect(isCanvasDataLoginId(v), String(v)).toBe(false);
31
+ }
32
+ });
33
+
34
+ it('takes plain keys only', () => {
35
+ for (const k of ['a', 'markup', 'page-2:marks', 'votes/v1', 'A_b.c', 'x'.repeat(128)]) {
36
+ expect(isCanvasDataKey(k), k).toBe(true);
37
+ }
38
+ for (const k of [
39
+ '',
40
+ '-lead',
41
+ '.hidden',
42
+ '/root',
43
+ 'x'.repeat(129),
44
+ 'a b',
45
+ 'a\nb',
46
+ 'é',
47
+ '../x',
48
+ 'a?b',
49
+ 'a#b',
50
+ 'a%2F',
51
+ 1,
52
+ null,
53
+ ['a'],
54
+ ]) {
55
+ expect(isCanvasDataKey(k), String(k)).toBe(false);
56
+ }
57
+ });
58
+
59
+ it('knows its operations', () => {
60
+ expect(isCanvasDataOp('get')).toBe(true);
61
+ expect(isCanvasDataOp('constructor')).toBe(false);
62
+ expect(isCanvasDataOp('__proto__')).toBe(false);
63
+ });
64
+
65
+ it('counts UTF-8 bytes as Node does', () => {
66
+ for (const s of ['', 'abc', 'é', '€', '😀', 'a😀b€é', '\ud800', '\udc00x']) {
67
+ expect(utf8Bytes(s), JSON.stringify(s)).toBe(new TextEncoder().encode(s).length);
68
+ }
69
+ });
70
+
71
+ it('reads JSON text and refuses anything else', () => {
72
+ const ok = readCanvasDataJson('{"a":[1,2,{"b":null}]}');
73
+ expect(ok).toEqual({
74
+ ok: true,
75
+ value: { a: [1, 2, { b: null }] },
76
+ text: '{"a":[1,2,{"b":null}]}',
77
+ bytes: 22,
78
+ });
79
+ expect(readCanvasDataJson('{bad')).toEqual({ ok: false, error: 'value must be JSON' });
80
+ expect(readCanvasDataJson(42)).toEqual({ ok: false, error: 'value must be JSON' });
81
+ expect(readCanvasDataJson(undefined)).toEqual({ ok: false, error: 'value must be JSON' });
82
+ });
83
+
84
+ it('refuses a value over the cap, counted in bytes', () => {
85
+ const fits = JSON.stringify('x'.repeat(CANVAS_DATA_VALUE_MAX_BYTES - 2));
86
+ expect(readCanvasDataJson(fits).ok).toBe(true);
87
+ const over = JSON.stringify('x'.repeat(CANVAS_DATA_VALUE_MAX_BYTES - 1));
88
+ expect(readCanvasDataJson(over).ok).toBe(false);
89
+ // Fewer characters than the cap, more bytes.
90
+ const wide = JSON.stringify('€'.repeat(CANVAS_DATA_VALUE_MAX_BYTES / 2));
91
+ expect(wide.length).toBeLessThan(CANVAS_DATA_VALUE_MAX_BYTES);
92
+ expect(readCanvasDataJson(wide).ok).toBe(false);
93
+ });
94
+
95
+ it('keeps a parsed value only when it is JSON', () => {
96
+ expect(canvasDataValue(undefined).ok).toBe(false);
97
+ expect(canvasDataValue(() => 1).ok).toBe(false);
98
+ const cyclic: Record<string, unknown> = {};
99
+ cyclic.self = cyclic;
100
+ expect(canvasDataValue(cyclic).ok).toBe(false);
101
+ expect(canvasDataValue(10n).ok).toBe(false);
102
+ // A Date keeps its JSON form, as JSON.stringify writes it.
103
+ const d = canvasDataValue({ at: new Date(0) });
104
+ expect(d.ok && d.value).toEqual({ at: '1970-01-01T00:00:00.000Z' });
105
+ });
106
+
107
+ it('refuses a value nested deeper than the cap', () => {
108
+ const nest = (n: number) => '['.repeat(n) + ']'.repeat(n);
109
+ expect(readCanvasDataJson(nest(CANVAS_DATA_MAX_DEPTH)).ok).toBe(true);
110
+ expect(readCanvasDataJson(nest(CANVAS_DATA_MAX_DEPTH + 1))).toEqual({
111
+ ok: false,
112
+ error: `value nests deeper than ${CANVAS_DATA_MAX_DEPTH} levels`,
113
+ });
114
+ let deep: unknown = 1;
115
+ for (let i = 0; i < 100; i++) deep = { a: deep };
116
+ expect(canvasDataValue(deep).ok).toBe(false);
117
+ // Wide is fine: depth, not size.
118
+ expect(canvasDataValue({ a: [1, 2, 3], b: { c: [{}, []] } }).ok).toBe(true);
119
+ });
120
+
121
+ it('keeps readers to 75% of the canvas', () => {
122
+ expect(CANVAS_DATA_MINE_ALL_MAX_BYTES).toBe((CANVAS_DATA_CANVAS_MAX_BYTES * 3) / 4);
123
+ expect(CANVAS_DATA_MINE_ALL_MAX_KEYS).toBe((CANVAS_DATA_CANVAS_MAX_KEYS * 3) / 4);
124
+ });
125
+ });
@@ -0,0 +1,245 @@
1
+ /**
2
+ * The canvas data store's contract (DWG phase 7a): what a Present canvas may
3
+ * keep through `mantle.data`, shared by the frame's helper (share-ui
4
+ * canvas-frame-html), the host that forwards its calls (share-ui
5
+ * canvas-sandbox), the brain's route and the content layer. Pure: no server
6
+ * or browser dependency.
7
+ *
8
+ * A canvas runs sandboxed, with no network, no cookies and no storage. It
9
+ * asks its PARENT page over postMessage; the parent forwards each call to
10
+ * the brain as the signed-in user, and binds the canvas: a message names
11
+ * neither a canvas nor a login. So everything a message carries is hostile
12
+ * until these checks pass, on the host and again on the brain.
13
+ *
14
+ * Two buckets, on the canvas's own item rights:
15
+ * - `shared`: every reader of the canvas reads it; only a user with Write on
16
+ * the canvas writes it (the right a source save asks).
17
+ * - `mine`: every reader writes their own entries only. A plain reader reads
18
+ * their own; a user with Write on the canvas (its owner too) reads
19
+ * everyone's, may remove any of them and may clear the canvas's data.
20
+ *
21
+ * Who wrote an entry: a `shared` entry shows the writer's name to every
22
+ * reader, and the writer's login id only to a user with Write on the canvas.
23
+ */
24
+
25
+ import { UUID_RE } from './uuid';
26
+
27
+ export const CANVAS_DATA_BUCKETS = ['shared', 'mine'] as const;
28
+ export type CanvasDataBucket = (typeof CANVAS_DATA_BUCKETS)[number];
29
+
30
+ /** One value, in UTF-8 bytes, as the brain stores it (its JSON text with a
31
+ * space after each `,` and `:`), which is what every cap counts. The
32
+ * compact text checked here is never longer, so it is a first bound; the
33
+ * brain's definer has the last word. */
34
+ export const CANVAS_DATA_VALUE_MAX_BYTES = 64 * 1024;
35
+ /** All values of one canvas, both buckets, every login. */
36
+ export const CANVAS_DATA_CANVAS_MAX_BYTES = 1024 * 1024;
37
+ /** Entries of one canvas, both buckets, every login. */
38
+ export const CANVAS_DATA_CANVAS_MAX_KEYS = 1000;
39
+ /** One login's `mine` entries on one canvas: no single reader fills the
40
+ * canvas's budget for everyone else. */
41
+ export const CANVAS_DATA_MINE_MAX_BYTES = 256 * 1024;
42
+ export const CANVAS_DATA_MINE_MAX_KEYS = 200;
43
+ /** Every login's `mine` entries together on one canvas: 75% of the canvas's
44
+ * caps, so readers never fill it and `shared` always keeps a quarter. */
45
+ export const CANVAS_DATA_MINE_ALL_MAX_BYTES = (CANVAS_DATA_CANVAS_MAX_BYTES * 3) / 4;
46
+ export const CANVAS_DATA_MINE_ALL_MAX_KEYS = (CANVAS_DATA_CANVAS_MAX_KEYS * 3) / 4;
47
+ /** How deep a value's arrays and objects may nest. */
48
+ export const CANVAS_DATA_MAX_DEPTH = 64;
49
+
50
+ /** A key: 1 to 128 characters, a letter or digit first, then letters,
51
+ * digits and `_ - . : /`. Plain enough to show, log and put in a URL. */
52
+ export const CANVAS_DATA_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}$/;
53
+
54
+ /** How long the host waits on the brain for one forwarded call, and the
55
+ * frame on the host. */
56
+ export const CANVAS_DATA_CALL_TIMEOUT_MS = 30_000;
57
+
58
+ /** The operations a canvas may ask for. */
59
+ export const CANVAS_DATA_OPS = ['get', 'set', 'delete', 'list', 'info', 'clear'] as const;
60
+ export type CanvasDataOp = (typeof CANVAS_DATA_OPS)[number];
61
+
62
+ /** One stored entry as the brain answers it. `by` is the login that owns a
63
+ * `mine` entry (or last wrote a `shared` one). Its `id` is left out of a
64
+ * `shared` entry for a reader without Write on the canvas: the name only. */
65
+ export type CanvasDataEntry = {
66
+ key: string;
67
+ value: unknown;
68
+ updatedAt: string;
69
+ by?: { id?: string; name: string | null };
70
+ };
71
+
72
+ /** What the store says about the reader of this canvas. */
73
+ export type CanvasDataInfo = {
74
+ /** The reader may write the `shared` bucket (Write on the canvas), remove
75
+ * another viewer's `mine` entry and clear the canvas's data. */
76
+ canWriteShared: boolean;
77
+ /** The reader may list everyone's `mine` entries (Write on the canvas). */
78
+ readsEveryone: boolean;
79
+ /** The reader's own login id: their `mine` entries carry it in `by`. */
80
+ me: string | null;
81
+ /** The canvas is a read-only copy: nothing is written. */
82
+ readOnly: boolean;
83
+ };
84
+
85
+ export function isCanvasDataBucket(v: unknown): v is CanvasDataBucket {
86
+ return typeof v === 'string' && (CANVAS_DATA_BUCKETS as readonly string[]).includes(v);
87
+ }
88
+
89
+ export function isCanvasDataKey(v: unknown): v is string {
90
+ return typeof v === 'string' && CANVAS_DATA_KEY_RE.test(v);
91
+ }
92
+
93
+ /** An entry's `by.id`, as `delete(key, { bucket: 'mine', by })` names it:
94
+ * a uuid as the store gives it, lowercase only. */
95
+ export function isCanvasDataLoginId(v: unknown): v is string {
96
+ return typeof v === 'string' && UUID_RE.test(v) && v === v.toLowerCase();
97
+ }
98
+
99
+ export function isCanvasDataOp(v: unknown): v is CanvasDataOp {
100
+ return typeof v === 'string' && (CANVAS_DATA_OPS as readonly string[]).includes(v);
101
+ }
102
+
103
+ /** UTF-8 byte length of a string, without a Buffer or a TextEncoder (both
104
+ * sides run it). */
105
+ export function utf8Bytes(s: string): number {
106
+ let n = 0;
107
+ for (let i = 0; i < s.length; i++) {
108
+ const c = s.charCodeAt(i);
109
+ if (c < 0x80) n += 1;
110
+ else if (c < 0x800) n += 2;
111
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
112
+ const d = s.charCodeAt(i + 1);
113
+ if (d >= 0xdc00 && d <= 0xdfff) {
114
+ n += 4;
115
+ i++;
116
+ } else n += 3;
117
+ } else n += 3;
118
+ }
119
+ return n;
120
+ }
121
+
122
+ /** Whether a JSON value nests deeper than `max` arrays and objects (walked
123
+ * without recursion: the value is at most a value's size). */
124
+ function nestsDeeper(value: unknown, max: number): boolean {
125
+ const stack: { v: unknown; d: number }[] = [{ v: value, d: 0 }];
126
+ while (stack.length > 0) {
127
+ const { v, d } = stack.pop()!;
128
+ if (v === null || typeof v !== 'object') continue;
129
+ if (d + 1 > max) return true;
130
+ for (const child of Array.isArray(v) ? v : Object.values(v as Record<string, unknown>)) {
131
+ if (child !== null && typeof child === 'object') stack.push({ v: child, d: d + 1 });
132
+ }
133
+ }
134
+ return false;
135
+ }
136
+
137
+ /**
138
+ * A value's JSON text, checked: JSON only (what JSON.parse gives back), at
139
+ * most CANVAS_DATA_VALUE_MAX_BYTES, nested at most CANVAS_DATA_MAX_DEPTH. `json` is the text a caller sent; the
140
+ * answer is the parsed value and its compact text, which the brain's
141
+ * definer takes (and sizes again as it stores it: what the caps count).
142
+ */
143
+ export function readCanvasDataJson(
144
+ json: unknown,
145
+ ): { ok: true; value: unknown; text: string; bytes: number } | { ok: false; error: string } {
146
+ if (typeof json !== 'string') return { ok: false, error: 'value must be JSON' };
147
+ // A cheap first bound: a string is never fewer bytes than characters.
148
+ if (json.length > CANVAS_DATA_VALUE_MAX_BYTES) return { ok: false, error: tooBig() };
149
+ let value: unknown;
150
+ try {
151
+ value = JSON.parse(json);
152
+ } catch {
153
+ return { ok: false, error: 'value must be JSON' };
154
+ }
155
+ return canvasDataValue(value);
156
+ }
157
+
158
+ /** A parsed value, checked as readCanvasDataJson checks its text. */
159
+ export function canvasDataValue(
160
+ value: unknown,
161
+ ): { ok: true; value: unknown; text: string; bytes: number } | { ok: false; error: string } {
162
+ let text: string | undefined;
163
+ try {
164
+ text = JSON.stringify(value);
165
+ } catch {
166
+ return { ok: false, error: 'value must be JSON' };
167
+ }
168
+ if (text === undefined) return { ok: false, error: 'value must be JSON' };
169
+ const bytes = utf8Bytes(text);
170
+ if (bytes > CANVAS_DATA_VALUE_MAX_BYTES) return { ok: false, error: tooBig() };
171
+ const parsed = JSON.parse(text) as unknown;
172
+ if (nestsDeeper(parsed, CANVAS_DATA_MAX_DEPTH)) {
173
+ return { ok: false, error: `value nests deeper than ${CANVAS_DATA_MAX_DEPTH} levels` };
174
+ }
175
+ return { ok: true, value: parsed, text, bytes };
176
+ }
177
+
178
+ /** The refusal for a value over CANVAS_DATA_VALUE_MAX_BYTES, here or as
179
+ * the brain stores it. */
180
+ export const CANVAS_DATA_TOO_BIG_ERROR = `value is over ${CANVAS_DATA_VALUE_MAX_BYTES / 1024} KB`;
181
+
182
+ function tooBig(): string {
183
+ return CANVAS_DATA_TOO_BIG_ERROR;
184
+ }
185
+
186
+ /** The refusal when a write would pass a cap, the same words everywhere. */
187
+ export const CANVAS_DATA_FULL_ERROR =
188
+ `the canvas's data is full: ${CANVAS_DATA_CANVAS_MAX_BYTES / 1024 / 1024} MB and ` +
189
+ `${CANVAS_DATA_CANVAS_MAX_KEYS} entries per canvas (viewers' own entries together ` +
190
+ `${CANVAS_DATA_MINE_ALL_MAX_BYTES / 1024} KB and ${CANVAS_DATA_MINE_ALL_MAX_KEYS}), ` +
191
+ `${CANVAS_DATA_MINE_MAX_BYTES / 1024} KB and ${CANVAS_DATA_MINE_MAX_KEYS} entries of your own`;
192
+
193
+ /**
194
+ * How a canvas author uses the store, ONE text for every author: the
195
+ * canvas_authoring skill (in-app agents) sets it in as a section, and
196
+ * canvas_library 'data' (what an MCP client reads) answers it with a full
197
+ * example canvas. Markdown, no heading of its own. The caps come from the
198
+ * constants above, so the words never drift from the checks.
199
+ */
200
+ export const CANVAS_DATA_HOWTO = `Only when a canvas must keep something people add (notes, suggestions, votes, a saved layout, meeting marks). A canvas that only shows things stays plain: no store calls.
201
+
202
+ The frame gives every canvas \`mantle.data\` (no import, no network: the page around the canvas saves it for the signed-in viewer, for this canvas only):
203
+
204
+ - \`await mantle.data.get(key, { bucket })\`: the value, or \`undefined\`.
205
+ - \`await mantle.data.set(key, value, { bucket })\`: save (made or replaced).
206
+ - \`await mantle.data.delete(key, { bucket, by })\`: \`by\` (an entry's \`by.id\`) removes another viewer's \`'mine'\` entry: Write only.
207
+ - \`await mantle.data.list({ bucket, everyone })\`: \`[{ key, value, updatedAt, by: { id, name } }]\`; a \`'shared'\` entry's \`by.id\` only for a user with Write.
208
+ - \`await mantle.data.clear()\`: remove every entry of the canvas, both buckets: Write only.
209
+ - \`await mantle.data.info()\`: \`{ canWriteShared, readsEveryone, me, readOnly }\`.
210
+
211
+ Buckets (\`bucket\` defaults to \`'shared'\`):
212
+
213
+ - \`'shared'\`: one value per key for everyone who can open the canvas. Only a user with Write on the canvas may write it (layouts, meeting marks).
214
+ - \`'mine'\`: each viewer's own entries; any viewer writes their own (suggestions, votes). A user with Write on the canvas reads everyone's with \`list({ bucket: 'mine', everyone: true })\`; others see only their own.
215
+
216
+ Rules:
217
+
218
+ - Values are small JSON: at most ${CANVAS_DATA_VALUE_MAX_BYTES / 1024} KB each, ${CANVAS_DATA_CANVAS_MAX_BYTES / 1024 / 1024} MB and ${CANVAS_DATA_CANVAS_MAX_KEYS} entries per canvas (\`'mine'\` together at most ${CANVAS_DATA_MINE_ALL_MAX_BYTES / 1024} KB and ${CANVAS_DATA_MINE_ALL_MAX_KEYS}), ${CANVAS_DATA_MINE_MAX_BYTES / 1024} KB and ${CANVAS_DATA_MINE_MAX_KEYS} entries per viewer in \`'mine'\`. Keys: letters, digits and \`_ - . : /\`, up to 128, a letter or digit first.
219
+ - Data arrives after the first paint: draw the canvas first, then fill it in. The picture a save returns, the poster and exports show the canvas with no data.
220
+ - Every call returns a promise that can reject (no right, full, offline): catch it and say so on the canvas; never lose what the viewer typed.
221
+ - Another viewer wrote what you read: show it as text (\`textContent\`), never as HTML.
222
+ - Never store secrets, passwords or keys. A photo or a big file goes in Files; keep only its id here.
223
+ - Saving data never changes the canvas or makes a new version of it.
224
+ - A canvas with an element whose \`id\` or \`name\` is \`mantle\` has no \`mantle.data\`: the name stays that element's.
225
+
226
+ \`\`\`html
227
+ <textarea id="notes" class="h-40 w-full rounded-md border border-border bg-card p-4 text-xl"></textarea>
228
+ <ul id="ideas" class="text-xl"></ul>
229
+ <script type="module">
230
+ const notes = document.getElementById('notes');
231
+ const info = await mantle.data.info();
232
+ notes.readOnly = !info.canWriteShared;
233
+ notes.value = (await mantle.data.get('notes')) ?? '';
234
+ notes.addEventListener('change', () =>
235
+ mantle.data.set('notes', notes.value).catch((e) => (notes.title = e.message)));
236
+ // A viewer's suggestion: their own entry in 'mine'.
237
+ const suggest = (text) => mantle.data.set('idea-' + Date.now(), { text }, { bucket: 'mine' });
238
+ const ideas = await mantle.data.list({ bucket: 'mine', everyone: info.readsEveryone });
239
+ for (const e of ideas) {
240
+ const li = document.createElement('li');
241
+ li.textContent = (e.by?.name ?? 'Someone') + ': ' + e.value.text;
242
+ document.getElementById('ideas').append(li);
243
+ }
244
+ </script>
245
+ \`\`\``;
@@ -0,0 +1,203 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ HOME_DESK_BYTES_MAX,
4
+ HOME_DESK_ITEMS_MAX,
5
+ projectHomeDesk,
6
+ projectHomeDeskVersion,
7
+ validateHomeDeskWrite,
8
+ } from './profile-projections';
9
+
10
+ const desk = (over: Record<string, unknown> = {}) => ({
11
+ v: 1,
12
+ items: [
13
+ { id: 'clock', x: 0, y: 0, w: 3, h: 2 },
14
+ { id: 'kind:notes', x: 0, y: 2, w: 7, h: 3 },
15
+ ],
16
+ counts: { notes: 6 },
17
+ icons: true,
18
+ clock: 'analog',
19
+ ...over,
20
+ });
21
+
22
+ describe('projectHomeDesk', () => {
23
+ it('keeps a well-formed desk as written', () => {
24
+ expect(projectHomeDesk(desk())).toEqual(desk());
25
+ });
26
+
27
+ it('keeps an id it does not know: the client owns what a widget is', () => {
28
+ const items = [{ id: 'some-later-widget', x: 1, y: 1, w: 2, h: 2 }];
29
+ expect(projectHomeDesk(desk({ items }))?.items).toEqual(items);
30
+ });
31
+
32
+ it('drops a bad item, not the desk', () => {
33
+ const out = projectHomeDesk(
34
+ desk({
35
+ items: [
36
+ { id: 'clock', x: 0, y: 0, w: 3, h: 2 },
37
+ { id: 'clock', x: 5, y: 5, w: 3, h: 2 }, // a repeat keeps the first
38
+ { id: '', x: 0, y: 0, w: 1, h: 1 },
39
+ { id: 'x'.repeat(161), x: 0, y: 0, w: 1, h: 1 },
40
+ { id: 'theme', x: -1, y: 0, w: 1, h: 1 },
41
+ { id: 'focus', x: 0, y: 0, w: 1, h: Number.POSITIVE_INFINITY },
42
+ { id: 'drift', x: '1', y: 0, w: 1, h: 1 },
43
+ null,
44
+ 'calendar',
45
+ ],
46
+ }),
47
+ );
48
+ expect(out?.items).toEqual([{ id: 'clock', x: 0, y: 0, w: 3, h: 2 }]);
49
+ });
50
+
51
+ it('defaults the settings it cannot read', () => {
52
+ const out = projectHomeDesk({
53
+ v: 1,
54
+ items: [],
55
+ counts: { notes: 'x', '': 3 },
56
+ clock: 'sundial',
57
+ });
58
+ expect(out).toEqual({ v: 1, items: [], counts: {}, icons: true, clock: 'digital' });
59
+ });
60
+
61
+ it('is undefined for anything that is not a v1 desk', () => {
62
+ expect(projectHomeDesk(null)).toBeUndefined();
63
+ expect(projectHomeDesk([])).toBeUndefined();
64
+ expect(projectHomeDesk({ v: 2, items: [] })).toBeUndefined();
65
+ expect(projectHomeDesk({ v: 1, items: {} })).toBeUndefined();
66
+ });
67
+
68
+ it('caps the items and the size', () => {
69
+ const many = Array.from({ length: HOME_DESK_ITEMS_MAX + 5 }, (_, i) => ({
70
+ id: `pin:${i}`,
71
+ x: 0,
72
+ y: i,
73
+ w: 1,
74
+ h: 1,
75
+ }));
76
+ expect(projectHomeDesk(desk({ items: many }))?.items).toHaveLength(HOME_DESK_ITEMS_MAX);
77
+ const big = Array.from({ length: HOME_DESK_ITEMS_MAX }, (_, i) => ({
78
+ id: `pin:${String(i).padStart(150, '0')}`,
79
+ x: 0,
80
+ y: i,
81
+ w: 1,
82
+ h: 1,
83
+ }));
84
+ expect(JSON.stringify(desk({ items: big })).length).toBeGreaterThan(HOME_DESK_BYTES_MAX);
85
+ expect(projectHomeDesk(desk({ items: big }))).toBeUndefined();
86
+ });
87
+
88
+ it('counts the size cap in UTF-8 bytes, not characters', () => {
89
+ const items = (ch: string) =>
90
+ Array.from({ length: 150 }, (_, i) => ({
91
+ id: `${ch.repeat(100)}${i}`,
92
+ x: 0,
93
+ y: i,
94
+ w: 1,
95
+ h: 1,
96
+ }));
97
+ // The same character count either way: under the cap as characters.
98
+ const wide = desk({ items: items('\u20ac') });
99
+ const narrow = desk({ items: items('e') });
100
+ expect(JSON.stringify(wide).length).toBe(JSON.stringify(narrow).length);
101
+ expect(JSON.stringify(wide).length).toBeLessThan(HOME_DESK_BYTES_MAX);
102
+ expect(new TextEncoder().encode(JSON.stringify(wide)).length).toBeGreaterThan(
103
+ HOME_DESK_BYTES_MAX,
104
+ );
105
+ // Three bytes a euro sign: over the cap as stored, so refused whole.
106
+ expect(projectHomeDesk(wide)).toBeUndefined();
107
+ expect(projectHomeDesk(narrow)?.items).toHaveLength(150);
108
+ });
109
+ });
110
+
111
+ describe('validateHomeDeskWrite: strict on write', () => {
112
+ it('keeps a well-formed desk as sent', () => {
113
+ expect(validateHomeDeskWrite(desk())).toEqual(desk());
114
+ // An empty desk on purpose (every widget taken off) is a desk.
115
+ expect(validateHomeDeskWrite(desk({ items: [], counts: {} }))).toEqual(
116
+ desk({ items: [], counts: {} }),
117
+ );
118
+ // Settings left out take their defaults, as on read.
119
+ expect(validateHomeDeskWrite({ v: 1, items: [] })).toEqual({
120
+ v: 1,
121
+ items: [],
122
+ counts: {},
123
+ icons: true,
124
+ clock: 'digital',
125
+ });
126
+ });
127
+
128
+ it('refuses a desk with any item the read would drop, never saving what is left', () => {
129
+ const good = { id: 'clock', x: 0, y: 0, w: 3, h: 2 };
130
+ for (const bad of [
131
+ { id: 'clock', x: 5, y: 5, w: 3, h: 2 },
132
+ { id: '', x: 0, y: 0, w: 1, h: 1 },
133
+ { id: 'x'.repeat(161), x: 0, y: 0, w: 1, h: 1 },
134
+ { id: 'theme', x: -1, y: 0, w: 1, h: 1 },
135
+ { id: 'drift', x: '1', y: 0, w: 1, h: 1 },
136
+ null,
137
+ 'calendar',
138
+ ]) {
139
+ expect(validateHomeDeskWrite(desk({ items: [good, bad] })), JSON.stringify(bad)).toBe(
140
+ undefined,
141
+ );
142
+ }
143
+ // Garbage alone is not an empty desk.
144
+ expect(validateHomeDeskWrite(desk({ items: [null, 7, 'x'] }))).toBeUndefined();
145
+ // The read keeps what it can of the same desk.
146
+ expect(projectHomeDesk(desk({ items: [good, null] }))?.items).toEqual([good]);
147
+ });
148
+
149
+ it('refuses a list the cap would cut', () => {
150
+ const items = (n: number) =>
151
+ Array.from({ length: n }, (_, i) => ({ id: `pin:${i}`, x: 0, y: i, w: 1, h: 1 }));
152
+ expect(validateHomeDeskWrite(desk({ items: items(HOME_DESK_ITEMS_MAX) }))?.items).toHaveLength(
153
+ HOME_DESK_ITEMS_MAX,
154
+ );
155
+ expect(validateHomeDeskWrite(desk({ items: items(HOME_DESK_ITEMS_MAX + 1) }))).toBeUndefined();
156
+ });
157
+
158
+ it('refuses an id or a key that is not printable ASCII (a NUL, a lone surrogate, a space)', () => {
159
+ for (const id of ['a\u0000b', '\ud800', 'x\udfff', 'has space', 'tab\t', 'café', '€']) {
160
+ const items = [{ id, x: 0, y: 0, w: 1, h: 1 }];
161
+ expect(validateHomeDeskWrite(desk({ items })), JSON.stringify(id)).toBeUndefined();
162
+ expect(validateHomeDeskWrite(desk({ counts: { [id]: 3 } })), JSON.stringify(id)).toBe(
163
+ undefined,
164
+ );
165
+ }
166
+ // The read stays loose: a desk already stored keeps such an id.
167
+ expect(projectHomeDesk(desk({ items: [{ id: 'café', x: 0, y: 0, w: 1, h: 1 }] }))).toBeTruthy();
168
+ });
169
+
170
+ it('refuses counts and settings the read would change', () => {
171
+ expect(validateHomeDeskWrite(desk({ counts: { notes: 'x' } }))).toBeUndefined();
172
+ expect(validateHomeDeskWrite(desk({ counts: { notes: -1 } }))).toBeUndefined();
173
+ expect(validateHomeDeskWrite(desk({ counts: [] }))).toBeUndefined();
174
+ expect(validateHomeDeskWrite(desk({ counts: 'notes' }))).toBeUndefined();
175
+ expect(validateHomeDeskWrite(desk({ icons: 'no' }))).toBeUndefined();
176
+ expect(validateHomeDeskWrite(desk({ clock: 'sundial' }))).toBeUndefined();
177
+ });
178
+
179
+ it('refuses what is not a v1 desk, and a desk over the size cap', () => {
180
+ expect(validateHomeDeskWrite(null)).toBeUndefined();
181
+ expect(validateHomeDeskWrite({ v: 2, items: [] })).toBeUndefined();
182
+ const big = Array.from({ length: HOME_DESK_ITEMS_MAX }, (_, i) => ({
183
+ id: `pin:${String(i).padStart(150, '0')}`,
184
+ x: 0,
185
+ y: i,
186
+ w: 1,
187
+ h: 1,
188
+ }));
189
+ expect(validateHomeDeskWrite(desk({ items: big }))).toBeUndefined();
190
+ });
191
+ });
192
+
193
+ describe('projectHomeDeskVersion', () => {
194
+ it('is the stored whole number, else 0 (never saved, or saved before the version)', () => {
195
+ expect(projectHomeDeskVersion(undefined)).toBe(0);
196
+ expect(projectHomeDeskVersion(null)).toBe(0);
197
+ expect(projectHomeDeskVersion(0)).toBe(0);
198
+ expect(projectHomeDeskVersion(7)).toBe(7);
199
+ for (const bad of [-1, 1.5, '3', Number.NaN, Number.MAX_SAFE_INTEGER + 1, {}]) {
200
+ expect(projectHomeDeskVersion(bad), String(bad)).toBe(0);
201
+ }
202
+ });
203
+ });
@@ -11,13 +11,15 @@
11
11
  * can project a value without pulling @mantle/db — and `postgres` — into the
12
12
  * browser bundle. content-core keeps its ZERO-runtime-dependency rule: the only
13
13
  * import here is `import type` from @mantle/client-types, which the compiler
14
- * erases entirely, and the one UUID regex is inlined rather than reaching for
15
- * @mantle/std (runtime code, and this file needs five characters of it).
14
+ * erases entirely, and the UUID regex is content-core's own (./uuid) rather
15
+ * than @mantle/std's (runtime code, and this file needs five characters of it).
16
16
  *
17
17
  * @mantle/content re-exports every name below, so nothing downstream moved.
18
18
  */
19
19
 
20
20
  import type {
21
+ HomeDesk,
22
+ HomeDeskItem,
21
23
  OnboardingModelChoices,
22
24
  ProfilePreferences,
23
25
  ReminderChannel,
@@ -34,6 +36,7 @@ import {
34
36
  } from './thinking-tiers';
35
37
  import { FRESH_APPEARANCE } from '@mantle/client-types/fresh-appearance';
36
38
  import { DRIFT_SPEC_MAX, decodeDriftSpec } from './drift-spec';
39
+ import { UUID_RE } from './uuid';
37
40
  import {
38
41
  APP_OPENS_MAX,
39
42
  APP_PINS_MAX,
@@ -46,9 +49,6 @@ export { projectAppNav } from './app-nav';
46
49
 
47
50
  export type { OnboardingModelChoices, ProfilePreferences, ReminderChannel, ThoughtTrailMode };
48
51
 
49
- /** Inlined from @mantle/std: content-core takes no runtime dependencies. */
50
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
51
-
52
52
  /** Resolve the live-streaming preference to a definite boolean — ON unless the
53
53
  * user explicitly turned it off. Use this everywhere instead of reading the
54
54
  * optional field directly, so "unset" reliably means on. */
@@ -509,6 +509,107 @@ export function projectNavFavorites(raw: unknown): string[] | undefined {
509
509
  return out.length > 0 ? out : undefined;
510
510
  }
511
511
 
512
+ /** The Desk's bounds. Generous (a full desk is a few KB); they bound
513
+ * the stored jsonb, not the layout. */
514
+ export const HOME_DESK_ITEMS_MAX = 400;
515
+ export const HOME_DESK_ID_MAX = 160;
516
+ export const HOME_DESK_COUNTS_MAX = 32;
517
+ export const HOME_DESK_COORD_MAX = 10_000;
518
+ export const HOME_DESK_BYTES_MAX = 32_768;
519
+
520
+ const deskCoord = (n: unknown): n is number =>
521
+ typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= HOME_DESK_COORD_MAX;
522
+
523
+ /**
524
+ * Project stored `homeDesk`. Loose on purpose: the client owns what a widget
525
+ * id means and each widget's bounds (and parses again on read), so the brain
526
+ * keeps only the SHAPE sound. Each item is checked on its own (one bad entry
527
+ * drops that widget, not the desk), repeats of an id keep the first, and the
528
+ * whole is capped. Undefined for anything that is not a v1 desk.
529
+ */
530
+ export function projectHomeDesk(raw: unknown): HomeDesk | undefined {
531
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined;
532
+ const d = raw as Record<string, unknown>;
533
+ if (d.v !== 1 || !Array.isArray(d.items)) return undefined;
534
+ const items: HomeDeskItem[] = [];
535
+ const seen = new Set<string>();
536
+ for (const v of d.items as unknown[]) {
537
+ if (typeof v !== 'object' || v === null) continue;
538
+ const { id, x, y, w, h } = v as Record<string, unknown>;
539
+ if (typeof id !== 'string' || id.length === 0 || id.length > HOME_DESK_ID_MAX) continue;
540
+ if (seen.has(id) || ![x, y, w, h].every(deskCoord)) continue;
541
+ seen.add(id);
542
+ items.push({ id, x: x as number, y: y as number, w: w as number, h: h as number });
543
+ if (items.length >= HOME_DESK_ITEMS_MAX) break;
544
+ }
545
+ const counts: Record<string, number> = {};
546
+ if (typeof d.counts === 'object' && d.counts !== null && !Array.isArray(d.counts)) {
547
+ for (const [k, n] of Object.entries(d.counts as Record<string, unknown>)) {
548
+ if (Object.keys(counts).length >= HOME_DESK_COUNTS_MAX) break;
549
+ if (k.length > 0 && k.length <= 32 && deskCoord(n)) counts[k] = n;
550
+ }
551
+ }
552
+ const desk: HomeDesk = {
553
+ v: 1,
554
+ items,
555
+ counts,
556
+ icons: d.icons !== false,
557
+ clock: d.clock === 'analog' ? 'analog' : 'digital',
558
+ };
559
+ // The cap is BYTES as stored (UTF-8), not UTF-16 code units: an id of
560
+ // non-Latin text is up to 3 bytes a character.
561
+ return utf8Bytes(JSON.stringify(desk)) <= HOME_DESK_BYTES_MAX ? desk : undefined;
562
+ }
563
+
564
+ /** What a desk item id and a counts key may hold on WRITE: printable ASCII,
565
+ * no space. A NUL or a lone surrogate would never reach the jsonb column
566
+ * (a 500); refused as a 400 instead. */
567
+ const HOME_DESK_KEY_RE = /^[\x21-\x7e]+$/;
568
+
569
+ /**
570
+ * The WRITE side of `projectHomeDesk`, for PUT /api/profile/home-desk only:
571
+ * strict where the read is loose. The desk projected, or undefined (a 400)
572
+ * when the projection would have changed what was sent: an item or a count
573
+ * dropped, the list cut at the cap, an id or a key that is not printable
574
+ * ASCII, a setting of the wrong type. So a save is kept as sent or refused
575
+ * whole, and garbage never saves as an empty desk. The read side
576
+ * (`projectHomeDesk`, loadHomeDesk) stays loose, so a desk already stored is
577
+ * never lost to a stricter rule.
578
+ */
579
+ export function validateHomeDeskWrite(raw: unknown): HomeDesk | undefined {
580
+ const desk = projectHomeDesk(raw);
581
+ if (!desk) return undefined;
582
+ const d = raw as Record<string, unknown>;
583
+ if ((d.items as unknown[]).length !== desk.items.length) return undefined;
584
+ if (!desk.items.every((i) => HOME_DESK_KEY_RE.test(i.id))) return undefined;
585
+ if (d.counts !== undefined) {
586
+ if (typeof d.counts !== 'object' || d.counts === null || Array.isArray(d.counts)) {
587
+ return undefined;
588
+ }
589
+ const keys = Object.keys(d.counts);
590
+ if (keys.length !== Object.keys(desk.counts).length) return undefined;
591
+ if (!keys.every((k) => HOME_DESK_KEY_RE.test(k))) return undefined;
592
+ }
593
+ if (d.icons !== undefined && typeof d.icons !== 'boolean') return undefined;
594
+ if (d.clock !== undefined && d.clock !== 'digital' && d.clock !== 'analog') return undefined;
595
+ return desk;
596
+ }
597
+
598
+ /**
599
+ * Project the stored desk's version (`homeDeskVersion`, beside `homeDesk` on
600
+ * the login's profile row): a whole number from 0, the count of saves that
601
+ * landed. 0 when the desk was never saved, or saved before it had one.
602
+ */
603
+ export function projectHomeDeskVersion(raw: unknown): number {
604
+ return typeof raw === 'number' && Number.isSafeInteger(raw) && raw >= 0 ? raw : 0;
605
+ }
606
+
607
+ const utf8 = new TextEncoder();
608
+ /** The UTF-8 size of `s` in bytes (TextEncoder: in Node and the browser). */
609
+ function utf8Bytes(s: string): number {
610
+ return utf8.encode(s).length;
611
+ }
612
+
512
613
  /** Project stored `appOpens`: well-formed counters only, keeping the
513
614
  * APP_OPENS_MAX most recently opened. */
514
615
  export function projectAppOpens(raw: unknown): Record<string, AppOpenStat> | undefined {
package/src/uuid.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @mantle/content-core · uuid
3
+ *
4
+ * The one UUID regex of this published package, as @mantle/std's UUID_RE
5
+ * (either case): content-core takes no runtime dependency, so it keeps its
6
+ * own copy, here only. app-nav, profile-projections and canvas-data read it.
7
+ */
8
+ export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;