@deveye/types 0.19.0 → 0.19.2

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.
@@ -63,9 +63,76 @@ declare module 'deveye-sdk-client' {
63
63
  disabled?: boolean;
64
64
  'aria-label'?: string;
65
65
  }>;
66
+ /**
67
+ * The app's number field: a native number input between two ± buttons.
68
+ * `null` is an empty field. What is being typed is never rewritten while
69
+ * the field has focus; the value is clamped to `min`/`max` on blur. `live`
70
+ * reports every in-range keystroke, for what shows at once (a preview).
71
+ * On the focused field only, the wheel steps by `step`, by fifty steps with
72
+ * Ctrl or Shift held; anywhere else it scrolls the page.
73
+ */
74
+ export const NumberInput: ComponentType<{
75
+ value: number | null;
76
+ onChange: (value: number | null) => void;
77
+ min?: number;
78
+ max?: number;
79
+ step?: number;
80
+ placeholder?: string;
81
+ disabled?: boolean;
82
+ live?: boolean;
83
+ /** For a wrapping `<label htmlFor>`: without it, clicking the label would press "−". */
84
+ id?: string;
85
+ 'aria-label'?: string;
86
+ className?: string;
87
+ }>;
88
+ /** One choice of a `SearchSelect`. `prefix` is decorative (a flag, an avatar); `keywords` widen what the search reads. */
89
+ export interface SearchSelectOption<T extends string = string> {
90
+ value: T;
91
+ label: string;
92
+ prefix?: ReactNode;
93
+ detail?: string;
94
+ keywords?: readonly string[];
95
+ }
96
+ /**
97
+ * A dropdown one can search in (accent- and case-insensitive), for a list too
98
+ * long to scan: currencies, units, countries. Under ten choices or so,
99
+ * `SelectInput` stays simpler. Safe inside a Dialog: the panel is portaled.
100
+ */
101
+ export function SearchSelect<T extends string>(props: {
102
+ value: T;
103
+ options: readonly SearchSelectOption<T>[];
104
+ onChange: (value: T) => void;
105
+ 'aria-label': string;
106
+ /** What the trigger shows when no option carries the current value. */
107
+ placeholder?: string;
108
+ searchPlaceholder?: string;
109
+ emptyText?: string;
110
+ disabled?: boolean;
111
+ className?: string;
112
+ }): ReactNode;
113
+ /**
114
+ * A labelled range input. `valueLabel` is how the value reads ("24", "80 %");
115
+ * `marks` sit under the track; `indicator` draws a discreet tick at a
116
+ * reference value (decorative: say what it means in `hint`).
117
+ */
118
+ export const Slider: ComponentType<{
119
+ value: number;
120
+ onChange: (value: number) => void;
121
+ min: number;
122
+ max: number;
123
+ step?: number;
124
+ label: string;
125
+ valueLabel?: string;
126
+ marks?: readonly string[];
127
+ indicator?: number;
128
+ hint?: string;
129
+ disabled?: boolean;
130
+ className?: string;
131
+ }>;
66
132
  export function SegmentedControl<T extends string>(props: {
67
133
  value: T;
68
- options: readonly { value: T; label: string; title?: string }[];
134
+ /** `detail`: a small line under the label, what the choice amounts to here ("Original", then "30 fps"). */
135
+ options: readonly { value: T; label: string; title?: string; detail?: string }[];
69
136
  onChange: (value: T) => void;
70
137
  /** Étire le groupe sur la ligne, chaque choix en prenant une part égale. */
71
138
  fullWidth?: boolean;
@@ -98,6 +165,22 @@ declare module 'deveye-sdk-client' {
98
165
  onPick?: (value: T) => void;
99
166
  'aria-label'?: string;
100
167
  }): ReactNode;
168
+ /** One choice of a `CountBadge`: what it counts, and whether it asks to be seen. */
169
+ export interface CountBadgeProps {
170
+ count: number;
171
+ /** `accent` (default): unread, something to act on. `neutral`: a plain count. */
172
+ tone?: 'accent' | 'neutral';
173
+ /** Above it, the badge reads "99+". Default 99. */
174
+ max?: number;
175
+ /** Needed when the number alone does not say what it counts. */
176
+ 'aria-label'?: string;
177
+ className?: string;
178
+ }
179
+ /**
180
+ * A counter pill: a number in a round. Round on one digit, a capsule beyond,
181
+ * its content centred both ways, which plain padding does not give.
182
+ */
183
+ export const CountBadge: ComponentType<CountBadgeProps>;
101
184
  /**
102
185
  * Le bouton d'enregistrement d'un panneau de réglages : « Enregistrement… »
103
186
  * pendant l'aller-retour, « Enregistré » quelques secondes, puis l'intitulé
@@ -463,19 +546,40 @@ declare module 'deveye-sdk-client' {
463
546
  * `undefined`. Use it on every `<a href>` you do not write yourself.
464
547
  */
465
548
  export function safeHref(url: string | null | undefined): string | undefined;
549
+ /**
550
+ * A v4 UUID, secure context or not. `crypto.randomUUID` is only exposed over
551
+ * HTTPS or on localhost, so an instance served in the clear on a LAN address
552
+ * does not have it: use this instead of calling it yourself.
553
+ */
554
+ export function randomUuid(): string;
555
+ /**
556
+ * Writes `value` to the clipboard and says whether it worked: on `false` the
557
+ * gesture still needs to be confirmed some other way, never silently dropped.
558
+ * `navigator.clipboard` only exists in a secure context, so this falls back to
559
+ * an offscreen selection. Never call the browser API directly.
560
+ */
561
+ export function copyText(value: string): Promise<boolean>;
466
562
  /**
467
563
  * The DevEye version this interface was built from: what an agent's
468
564
  * reported version is compared against to offer a self-update.
469
565
  */
470
566
  export const APP_VERSION: string;
471
567
  /**
472
- * A validated GET on one of the app's HTTP routes (the session cookie
473
- * rides along; an expired access token is renewed and the call replayed
568
+ * A validated GET on one of the app's HTTP routes, authenticated as the
569
+ * session is (an expired access token is renewed and the call replayed
474
570
  * once). For the routes that stay HTTP because they serve binaries.
571
+ *
572
+ * Always pass a PATH, never an absolute URL: the active workspace may live
573
+ * on a remote DevEye instance, and the host routes the call there.
475
574
  */
476
575
  export function httpGet<T>(path: string, outputSchema?: ZodType<T>): Promise<T>;
477
- /** Renews the access cookie before a raw `fetch` that bypasses the client (a download). */
478
- export function ensureFreshAccess(): Promise<void>;
576
+ /**
577
+ * A raw `fetch` on one of the app's HTTP routes, for a response that is not
578
+ * the usual JSON envelope (a binary to download). Same routing and
579
+ * authentication as {@link httpGet}; a bare `fetch('/api/...')` would reach
580
+ * the wrong server from a remote workspace.
581
+ */
582
+ export function httpFetch(path: string, init?: RequestInit): Promise<Response>;
479
583
  /**
480
584
  * The account's plan, kept live. `null` while loading AND when this DevEye
481
585
  * has no plan provider (everything unlimited): never read it as "free".
@@ -0,0 +1,374 @@
1
+ import assert from 'node:assert/strict';
2
+ import { describe, it } from 'node:test';
3
+
4
+ import {
5
+ exportItemTree,
6
+ FeatureError,
7
+ importItemTree,
8
+ itemTierOf,
9
+ itemTreeProblem,
10
+ movableCellsOf,
11
+ type ItemTree,
12
+ type SdkCipher,
13
+ type SdkQueryable
14
+ } from './server';
15
+
16
+ /**
17
+ * La copie d'un élément. Ce qui se vérifie ici est ce qui ne pardonne pas : une
18
+ * copie accrochée à l'original, une cellule recopiée sous une clé que la
19
+ * destination n'a pas, et un paquet venu d'un navigateur qui écrirait ailleurs
20
+ * que dans l'arbre.
21
+ */
22
+
23
+ type Row = Record<string, unknown>;
24
+
25
+ /** La lecture d'une table qui pend à l'élément par une autre. */
26
+ const SCOPED_READ = new RegExp(
27
+ '^SELECT \\* FROM (\\w+) WHERE (\\w+) IN ' +
28
+ '\\(SELECT (\\w+) FROM (\\w+) WHERE (\\w+) = \\?\\)'
29
+ );
30
+
31
+ /** Une base qui ne comprend que le SQL du moteur : lectures par propriétaire, insertions, une mise à jour. */
32
+ function fakeDb(tables: Record<string, { columns: string[]; rows: Row[] }>) {
33
+ let nextId = 1000;
34
+ const q: SdkQueryable = {
35
+ query: async <T extends object>(sql: string, params: unknown[] = []) => {
36
+ const show = /^SHOW COLUMNS FROM (\w+)/.exec(sql);
37
+ if (show) {
38
+ return tables[show[1]].columns.map((Field) => ({
39
+ Field,
40
+ Extra: ''
41
+ })) as unknown as T[];
42
+ }
43
+ if (/^SELECT COALESCE\(MAX/.test(sql)) return [{ next: 12 }] as unknown as T[];
44
+ const taken =
45
+ /^SELECT COUNT\(\*\) AS n FROM (\w+) WHERE (\w+) = \? AND (\w+) = \?/.exec(sql);
46
+ if (taken) {
47
+ const n = tables[taken[1]].rows.filter(
48
+ (r) => r[taken[2]] === params[0] && r[taken[3]] === params[1]
49
+ ).length;
50
+ return [{ n }] as unknown as T[];
51
+ }
52
+ const tier = /^SELECT (\w+) AS tier FROM (\w+) WHERE (\w+) = \?/.exec(sql);
53
+ if (tier) {
54
+ return tables[tier[2]].rows
55
+ .filter((r) => r[tier[3]] === params[0])
56
+ .map((r) => ({ tier: r[tier[1]] })) as unknown as T[];
57
+ }
58
+ const scoped = SCOPED_READ.exec(sql);
59
+ if (scoped) {
60
+ const parents = new Set(
61
+ tables[scoped[4]].rows
62
+ .filter((r) => r[scoped[5]] === params[0])
63
+ .map((r) => r[scoped[3]])
64
+ );
65
+ return tables[scoped[1]].rows.filter((r) =>
66
+ parents.has(r[scoped[2]])
67
+ ) as unknown as T[];
68
+ }
69
+ const read = /^SELECT \* FROM (\w+) WHERE (\w+) = \?/.exec(sql);
70
+ if (read) {
71
+ return tables[read[1]].rows.filter(
72
+ (r) => r[read[2]] === params[0]
73
+ ) as unknown as T[];
74
+ }
75
+ throw new Error(`SQL inattendu : ${sql}`);
76
+ },
77
+ execute: async (sql: string, params: unknown[] = []) => {
78
+ const insert = /^INSERT INTO (\w+) \(([^)]*)\)/.exec(sql);
79
+ if (insert) {
80
+ const names = insert[2].split(', ');
81
+ const row: Row = Object.fromEntries(names.map((n, i) => [n, params[i]]));
82
+ // Une table de liaison n'a pas d'identifiant à donner.
83
+ if (row.id === undefined && tables[insert[1]].columns.includes('id')) {
84
+ row.id = nextId++;
85
+ }
86
+ tables[insert[1]].rows.push(row);
87
+ return { affectedRows: 1, insertId: typeof row.id === 'number' ? row.id : 0 };
88
+ }
89
+ const update = /^UPDATE (\w+) SET (\w+) = \? WHERE (\w+) = \?/.exec(sql);
90
+ if (update) {
91
+ for (const r of tables[update[1]].rows) {
92
+ if (r[update[3]] === params[1]) r[update[2]] = params[0];
93
+ }
94
+ return { affectedRows: 1, insertId: 0 };
95
+ }
96
+ throw new Error(`SQL inattendu : ${sql}`);
97
+ }
98
+ };
99
+ return q;
100
+ }
101
+
102
+ function cipherOf(tag: string): SdkCipher {
103
+ return {
104
+ encrypt: async (plain) => `${tag}:${plain}`,
105
+ decrypt: async (blob) => blob.slice(tag.length + 1),
106
+ tryDecrypt: async (blob) => (blob.startsWith(`${tag}:`) ? blob.slice(tag.length + 1) : null)
107
+ };
108
+ }
109
+
110
+ const into = (tag: string) => ({ workspaceId: 42, userId: 5, cipher: cipherOf(tag) });
111
+
112
+ const TREE: ItemTree = [
113
+ {
114
+ table: 'boards',
115
+ idColumn: 'id',
116
+ ownerColumn: 'id',
117
+ workspaceColumn: 'workspace_id',
118
+ userColumn: 'user_id',
119
+ orderColumn: 'sort_order',
120
+ sealed: ['content', 'last_error'],
121
+ omit: ['credential_id', 'last_error'],
122
+ tier: { column: 'tier', open: 'open', private: 'guarded' }
123
+ },
124
+ {
125
+ table: 'columns',
126
+ idColumn: 'id',
127
+ ownerColumn: 'board_id',
128
+ workspaceColumn: 'workspace_id',
129
+ sealed: ['content']
130
+ },
131
+ {
132
+ table: 'cards',
133
+ idColumn: 'id',
134
+ ownerColumn: 'board_id',
135
+ sealed: ['content'],
136
+ refs: { column_id: 'columns', parent_id: 'cards' }
137
+ },
138
+ {
139
+ table: 'deps',
140
+ ownerColumn: 'board_id',
141
+ refs: { card_id: 'cards', blocked_by: 'cards' }
142
+ },
143
+ {
144
+ table: 'labels',
145
+ idColumn: 'id',
146
+ ownerColumn: 'card_id',
147
+ ownerScope: 'SELECT id FROM cards WHERE board_id = ?',
148
+ refs: { card_id: 'cards' },
149
+ sealed: ['content']
150
+ },
151
+ { table: 'history', idColumn: 'id', ownerColumn: 'board_id', sealed: ['content'], cache: true }
152
+ ];
153
+
154
+ function seed(): Record<string, { columns: string[]; rows: Row[] }> {
155
+ return {
156
+ boards: {
157
+ columns: [
158
+ 'id',
159
+ 'workspace_id',
160
+ 'user_id',
161
+ 'tier',
162
+ 'content',
163
+ 'last_error',
164
+ 'sort_order',
165
+ 'credential_id'
166
+ ],
167
+ rows: [
168
+ {
169
+ id: 1,
170
+ workspace_id: 7,
171
+ user_id: 3,
172
+ tier: 'open',
173
+ content: 'A:tableau',
174
+ last_error: 'A:oups',
175
+ sort_order: 4,
176
+ credential_id: 9
177
+ }
178
+ ]
179
+ },
180
+ columns: {
181
+ columns: ['id', 'board_id', 'workspace_id', 'content'],
182
+ rows: [
183
+ { id: 10, board_id: 1, workspace_id: 7, content: 'A:à faire' },
184
+ { id: 11, board_id: 1, workspace_id: 7, content: 'A:fait' }
185
+ ]
186
+ },
187
+ cards: {
188
+ columns: ['id', 'board_id', 'column_id', 'parent_id', 'content'],
189
+ rows: [
190
+ // L'enfant avant son parent : l'auto-référence ne peut pas se poser à l'insertion.
191
+ { id: 20, board_id: 1, column_id: 11, parent_id: 21, content: 'A:sous-carte' },
192
+ { id: 21, board_id: 1, column_id: 10, parent_id: null, content: 'A:carte' }
193
+ ]
194
+ },
195
+ deps: {
196
+ columns: ['board_id', 'card_id', 'blocked_by'],
197
+ rows: [{ board_id: 1, card_id: 20, blocked_by: 21 }]
198
+ },
199
+ labels: {
200
+ columns: ['id', 'card_id', 'content'],
201
+ rows: [{ id: 30, card_id: 20, content: 'A:urgent' }]
202
+ },
203
+ history: {
204
+ columns: ['id', 'board_id', 'content'],
205
+ rows: [{ id: 40, board_id: 1, content: 'A:ancien' }]
206
+ }
207
+ };
208
+ }
209
+
210
+ describe('copie d’un élément', () => {
211
+ it('recopie l’arbre entier sous de nouveaux ids, sous l’autre clé, accroché à la copie', async () => {
212
+ const source = seed();
213
+ const rows = await exportItemTree(fakeDb(source), TREE, 1, cipherOf('A'));
214
+
215
+ // En clair, sans ce qui ne voyage pas : ni espace, ni palier, ni omis, ni cache.
216
+ assert.deepEqual(rows.boards, [{ id: 1, content: 'tableau' }]);
217
+ assert.equal(rows.history, undefined);
218
+
219
+ const target = seed();
220
+ for (const t of Object.values(target)) t.rows.length = 0;
221
+ const newId = await importItemTree(fakeDb(target), TREE, rows, into('B'));
222
+
223
+ assert.deepEqual(target.boards.rows, [
224
+ {
225
+ id: 1000,
226
+ workspace_id: 42,
227
+ user_id: 5,
228
+ sort_order: 12,
229
+ tier: 'open',
230
+ content: 'B:tableau'
231
+ }
232
+ ]);
233
+ assert.equal(newId, '1000');
234
+ assert.deepEqual(
235
+ target.columns.rows.map((r) => [r.board_id, r.workspace_id, r.content]),
236
+ [
237
+ [1000, 42, 'B:à faire'],
238
+ [1000, 42, 'B:fait']
239
+ ]
240
+ );
241
+ const [child, parent] = target.cards.rows;
242
+ assert.equal(child.board_id, 1000);
243
+ assert.equal(child.column_id, target.columns.rows[1].id);
244
+ assert.equal(child.parent_id, parent.id, 'l’auto-référence suit la copie');
245
+ assert.equal(target.labels.rows[0].card_id, child.id);
246
+ assert.deepEqual(
247
+ target.deps.rows,
248
+ [{ board_id: 1000, card_id: child.id, blocked_by: parent.id }],
249
+ 'une table de liaison suit la copie des deux côtés'
250
+ );
251
+ assert.equal(target.history.rows.length, 0);
252
+ });
253
+
254
+ it('annule tout si une cellule résiste, avant d’avoir rien rendu', async () => {
255
+ const source = seed();
256
+ source.cards.rows[1].content = 'AUTRE:illisible';
257
+ await assert.rejects(exportItemTree(fakeDb(source), TREE, 1, cipherOf('A')), FeatureError);
258
+ });
259
+
260
+ it('scelle selon le palier que la destination a retenu', async () => {
261
+ const source = seed();
262
+ source.boards.rows[0].tier = 'guarded';
263
+ assert.equal(await itemTierOf(fakeDb(source), TREE, 1), 'private');
264
+ assert.equal(await itemTierOf(fakeDb(source), TREE, 99), null);
265
+
266
+ const rows = await exportItemTree(fakeDb(source), TREE, 1, cipherOf('A'));
267
+ const target = seed();
268
+ for (const t of Object.values(target)) t.rows.length = 0;
269
+ await importItemTree(fakeDb(target), TREE, rows, { ...into('P'), tier: 'private' });
270
+ assert.equal(target.boards.rows[0].tier, 'guarded');
271
+ assert.equal(target.boards.rows[0].content, 'P:tableau');
272
+ });
273
+
274
+ it('refuse un paquet qui écrirait hors de l’arbre', async () => {
275
+ const target = seed();
276
+ const q = fakeDb(target);
277
+ const good = { boards: [{ id: 1, content: 'x' }] };
278
+ await assert.rejects(
279
+ importItemTree(q, TREE, { ...good, users: [{ id: 1 }] }, into('B')),
280
+ /Table/
281
+ );
282
+ await assert.rejects(
283
+ importItemTree(q, TREE, { ...good, history: [{ id: 1 }] }, into('B')),
284
+ /Table/
285
+ );
286
+ for (const column of [
287
+ 'workspace_id',
288
+ 'user_id',
289
+ 'sort_order',
290
+ 'tier',
291
+ 'credential_id',
292
+ 'role'
293
+ ]) {
294
+ await assert.rejects(
295
+ importItemTree(
296
+ q,
297
+ TREE,
298
+ { boards: [{ id: 1, content: 'x', [column]: 1 }] },
299
+ into('B')
300
+ ),
301
+ /Colonne/,
302
+ column
303
+ );
304
+ }
305
+ await assert.rejects(importItemTree(q, TREE, { boards: [] }, into('B')), /exactement un/);
306
+ await assert.rejects(
307
+ importItemTree(
308
+ q,
309
+ TREE,
310
+ { ...good, cards: [{ id: 5, column_id: 999, content: 'x' }] },
311
+ into('B')
312
+ ),
313
+ /orpheline/
314
+ );
315
+ });
316
+
317
+ it('refuse un élément que la destination tient déjà sous le même nom', async () => {
318
+ const tree: ItemTree = [
319
+ { ...TREE[0], unique: { column: 'name_ref', message: 'Déjà là.' } }
320
+ ];
321
+ const target = seed();
322
+ target.boards.columns.push('name_ref');
323
+ target.boards.rows = [{ id: 2, workspace_id: 42, name_ref: 'abc' }];
324
+ const rows = { boards: [{ id: 1, content: 'x', name_ref: 'abc' }] };
325
+ await assert.rejects(importItemTree(fakeDb(target), tree, rows, into('B')), /Déjà là/);
326
+ // Le même nom dans un AUTRE espace ne gêne pas.
327
+ target.boards.rows[0].workspace_id = 7;
328
+ await importItemTree(fakeDb(target), tree, rows, into('B'));
329
+ });
330
+
331
+ it('ne laisse pas un enfant s’accrocher à l’élément d’un autre', async () => {
332
+ const target = seed();
333
+ for (const t of Object.values(target)) t.rows.length = 0;
334
+ const rows = {
335
+ boards: [{ id: 1, content: 'x' }],
336
+ columns: [{ id: 10, board_id: 555, content: 'y' }]
337
+ };
338
+ await importItemTree(fakeDb(target), TREE, rows, into('B'));
339
+ assert.equal(target.columns.rows[0].board_id, 1000);
340
+ });
341
+ });
342
+
343
+ const LABELS = TREE.find((t) => t.table === 'labels')!;
344
+
345
+ describe('arbre d’un élément', () => {
346
+ it('donne au déplacement toutes ses cellules, caches compris', () => {
347
+ const cells = movableCellsOf(TREE);
348
+ assert.equal(cells.length, 6);
349
+ assert.ok(cells.some((c) => c.table === 'history' && c.column === 'content'));
350
+ assert.equal(
351
+ cells.find((c) => c.table === 'labels')?.ownerScope,
352
+ 'SELECT id FROM cards WHERE board_id = ?'
353
+ );
354
+ });
355
+
356
+ it('refuse au démarrage un arbre mal formé', () => {
357
+ assert.equal(itemTreeProblem(TREE), null);
358
+ assert.match(itemTreeProblem([]) ?? '', /empty/);
359
+ assert.match(
360
+ itemTreeProblem([TREE[0], { table: 'x', ownerColumn: 'b', sealed: ['c'] }]) ?? '',
361
+ /link table/
362
+ );
363
+ assert.match(itemTreeProblem([{ ...TREE[0], ownerColumn: 'x' }]) ?? '', /root/);
364
+ assert.match(itemTreeProblem([TREE[0], TREE[2]]) ?? '', /before/);
365
+ assert.match(
366
+ itemTreeProblem([TREE[0], { ...TREE[1], table: 'columns; DROP' }]) ?? '',
367
+ /identifier/
368
+ );
369
+ assert.match(
370
+ itemTreeProblem([TREE[0], TREE[1], TREE[2], { ...LABELS, refs: {} }]) ?? '',
371
+ /scoped/
372
+ );
373
+ });
374
+ });