@deveye/types 0.17.0 → 0.17.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveye/types",
3
- "version": "0.17.0",
3
+ "version": "0.17.2",
4
4
  "description": "Shared contracts (types + zod schemas) for DevEye apps",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -0,0 +1,195 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Container management on a device — entities shared by the agent, server and
5
+ * client.
6
+ *
7
+ * The agent drives the engines through their CLI (`docker` / `podman`), the way
8
+ * it already reads container logs: no daemon socket, no `bollard`, and podman
9
+ * support comes free because both take the same flags. Go templates rather than
10
+ * `--format json`: the JSON field names diverge between the two engines, the
11
+ * templates do not.
12
+ */
13
+
14
+ /** A container engine the agent found on the host. */
15
+ export const containerEngineSchema = z.enum(['docker', 'podman']);
16
+ export type ContainerEngine = z.infer<typeof containerEngineSchema>;
17
+
18
+ /**
19
+ * Normalised container state. `unknown` covers whatever an engine prints that
20
+ * we do not model, so an unexpected word never drops the container from the
21
+ * inventory.
22
+ */
23
+ export const containerStateSchema = z.enum([
24
+ 'running',
25
+ 'exited',
26
+ 'paused',
27
+ 'created',
28
+ 'restarting',
29
+ 'removing',
30
+ 'dead',
31
+ 'unknown'
32
+ ]);
33
+ export type ContainerState = z.infer<typeof containerStateSchema>;
34
+
35
+ /** One container, running or not. */
36
+ export const dockerContainerSchema = z.object({
37
+ engine: containerEngineSchema,
38
+ /** Full (untruncated) container id — what every action addresses. */
39
+ id: z.string().min(1).max(128),
40
+ name: z.string().max(256),
41
+ image: z.string().max(512),
42
+ state: containerStateSchema,
43
+ /** The engine's own wording ("Up 3 days", "Exited (0) 2 hours ago"). */
44
+ status: z.string().max(256),
45
+ /** Published port mappings, as the engine prints them. */
46
+ ports: z.string().max(512),
47
+ createdAt: z.string().max(64),
48
+ /**
49
+ * Compose labels, when the container is compose-managed. `recreate` needs
50
+ * the three of them: without a compose project there is no faithful way to
51
+ * rebuild a container's run configuration.
52
+ */
53
+ composeProject: z.string().max(256).nullable(),
54
+ composeService: z.string().max(256).nullable(),
55
+ composeWorkingDir: z.string().max(1024).nullable()
56
+ });
57
+ export type DockerContainer = z.infer<typeof dockerContainerSchema>;
58
+
59
+ /** One image present on the host. */
60
+ export const dockerImageSchema = z.object({
61
+ engine: containerEngineSchema,
62
+ id: z.string().min(1).max(128),
63
+ /** `repository:tag`, or `<none>:<none>` for a dangling layer. */
64
+ reference: z.string().max(512),
65
+ /** Human size as the engine prints it ("128MB"). */
66
+ size: z.string().max(64),
67
+ createdAt: z.string().max(64),
68
+ /** Untagged leftover: the prime candidate for a cleanup. */
69
+ dangling: z.boolean()
70
+ });
71
+ export type DockerImage = z.infer<typeof dockerImageSchema>;
72
+
73
+ export const dockerVolumeSchema = z.object({
74
+ engine: containerEngineSchema,
75
+ name: z.string().min(1).max(256),
76
+ driver: z.string().max(64),
77
+ mountpoint: z.string().max(1024)
78
+ });
79
+ export type DockerVolume = z.infer<typeof dockerVolumeSchema>;
80
+
81
+ export const dockerNetworkSchema = z.object({
82
+ engine: containerEngineSchema,
83
+ id: z.string().min(1).max(128),
84
+ name: z.string().min(1).max(256),
85
+ driver: z.string().max(64),
86
+ scope: z.string().max(64)
87
+ });
88
+ export type DockerNetwork = z.infer<typeof dockerNetworkSchema>;
89
+
90
+ /**
91
+ * What one engine answered. `reachable` false means its binary is there but the
92
+ * daemon refused (socket permissions, daemon down): the UI must say that rather
93
+ * than "no containers", which is what the user would otherwise read.
94
+ */
95
+ export const dockerEngineStatusSchema = z.object({
96
+ engine: containerEngineSchema,
97
+ reachable: z.boolean(),
98
+ /** Engine version when reachable, else why it is not. */
99
+ version: z.string().max(128).nullable(),
100
+ error: z.string().max(255).nullable()
101
+ });
102
+ export type DockerEngineStatus = z.infer<typeof dockerEngineStatusSchema>;
103
+
104
+ /**
105
+ * A device's whole container inventory. Empty `engines` means neither binary is
106
+ * installed — the honest "this host does not do containers".
107
+ */
108
+ export const dockerInventorySchema = z.object({
109
+ engines: z.array(dockerEngineStatusSchema),
110
+ containers: z.array(dockerContainerSchema),
111
+ images: z.array(dockerImageSchema),
112
+ volumes: z.array(dockerVolumeSchema),
113
+ networks: z.array(dockerNetworkSchema)
114
+ });
115
+ export type DockerInventory = z.infer<typeof dockerInventorySchema>;
116
+
117
+ /** Live resource use of one running container, from `docker stats --no-stream`. */
118
+ export const dockerStatSchema = z.object({
119
+ engine: containerEngineSchema,
120
+ id: z.string().min(1).max(128),
121
+ /** Percent of a host CPU; `null` when the engine printed something unparseable. */
122
+ cpuPercent: z.number().nullable(),
123
+ memUsedBytes: z.number().int().nonnegative().nullable(),
124
+ memLimitBytes: z.number().int().nonnegative().nullable(),
125
+ memPercent: z.number().nullable(),
126
+ netRxBytes: z.number().int().nonnegative().nullable(),
127
+ netTxBytes: z.number().int().nonnegative().nullable(),
128
+ blockReadBytes: z.number().int().nonnegative().nullable(),
129
+ blockWriteBytes: z.number().int().nonnegative().nullable(),
130
+ pids: z.number().int().nonnegative().nullable()
131
+ });
132
+ export type DockerStat = z.infer<typeof dockerStatSchema>;
133
+
134
+ /**
135
+ * What may be asked of an engine. A closed list, mirrored by a `match` in the
136
+ * agent: no argument but the target's identifier ever reaches a command line,
137
+ * and there is no shell. Anything beyond this list is the remote terminal's job,
138
+ * which is a separate permission.
139
+ */
140
+ export const dockerActionSchema = z.enum([
141
+ // Cycle de vie d'un conteneur.
142
+ 'start',
143
+ 'stop',
144
+ 'restart',
145
+ 'pause',
146
+ 'unpause',
147
+ 'kill',
148
+ // Suppressions, chacune sur sa cible.
149
+ 'removeContainer',
150
+ 'removeImage',
151
+ 'removeVolume',
152
+ 'removeNetwork',
153
+ // Nettoyages, sans cible.
154
+ 'pruneContainers',
155
+ 'pruneImages',
156
+ 'pruneVolumes',
157
+ 'pruneNetworks',
158
+ 'pruneBuildCache',
159
+ // Mise à jour d'un service.
160
+ 'pull',
161
+ 'recreate'
162
+ ]);
163
+ export type DockerAction = z.infer<typeof dockerActionSchema>;
164
+
165
+ /**
166
+ * Actions that stream their output and can run for minutes. The server holds a
167
+ * per-device lock on these, and the UI follows them live; the others answer in
168
+ * one frame.
169
+ */
170
+ export const DOCKER_LONG_ACTIONS = [
171
+ 'pull',
172
+ 'recreate',
173
+ 'pruneContainers',
174
+ 'pruneImages',
175
+ 'pruneVolumes',
176
+ 'pruneNetworks',
177
+ 'pruneBuildCache'
178
+ ] as const satisfies readonly DockerAction[];
179
+
180
+ /** Actions that need no target: they act on the whole engine. */
181
+ export const DOCKER_UNTARGETED_ACTIONS = [
182
+ 'pruneContainers',
183
+ 'pruneImages',
184
+ 'pruneVolumes',
185
+ 'pruneNetworks',
186
+ 'pruneBuildCache'
187
+ ] as const satisfies readonly DockerAction[];
188
+
189
+ export function isLongDockerAction(action: DockerAction): boolean {
190
+ return (DOCKER_LONG_ACTIONS as readonly DockerAction[]).includes(action);
191
+ }
192
+
193
+ export function isUntargetedDockerAction(action: DockerAction): boolean {
194
+ return (DOCKER_UNTARGETED_ACTIONS as readonly DockerAction[]).includes(action);
195
+ }
@@ -39,6 +39,13 @@ export interface FeatureDescriptor {
39
39
  * d'écran (« Réglages de ce service »). Absent quand `hasItems` est faux.
40
40
  */
41
41
  itemNoun?: string;
42
+ /**
43
+ * Le genre de `itemNoun`, sans quoi les intitulés qui le précèdent d'un
44
+ * déterminant ne peuvent pas s'accorder (« cette note » contre « cet
45
+ * appareil »). Masculin par défaut : c'est le cas le plus courant, et un
46
+ * module qui l'omet lit au moins juste la moitié du temps.
47
+ */
48
+ itemNounGender?: 'm' | 'f';
42
49
  /**
43
50
  * Les sources de la fonctionnalité : des réglages d'espace réutilisables
44
51
  * (un jeton, une destination) que chaque élément ne fait que désigner.
@@ -117,6 +124,7 @@ export const FEATURE_REGISTRY: readonly (FeatureDescriptor & { id: WorkspaceFeat
117
124
  notifies: false,
118
125
  hasItems: true,
119
126
  itemNoun: 'note',
127
+ itemNounGender: 'f',
120
128
  shareTier: 'perItem'
121
129
  },
122
130
  {
@@ -183,6 +191,7 @@ export const FEATURE_REGISTRY: readonly (FeatureDescriptor & { id: WorkspaceFeat
183
191
  notifies: true,
184
192
  hasItems: true,
185
193
  itemNoun: 'cible',
194
+ itemNounGender: 'f',
186
195
  sources: {
187
196
  hint: 'Les accès Dokploy de l’espace (adresse de l’instance et clé d’API). Chaque cible en désigne un ; corriger un accès corrige d’un coup toutes les cibles qui s’en servent.'
188
197
  },
@@ -197,6 +206,7 @@ export const FEATURE_REGISTRY: readonly (FeatureDescriptor & { id: WorkspaceFeat
197
206
  notifies: true,
198
207
  hasItems: true,
199
208
  itemNoun: 'base',
209
+ itemNounGender: 'f',
200
210
  shareTier: 'open'
201
211
  },
202
212
  {
@@ -309,6 +319,57 @@ export function featureLabel(id: FeatureId): string {
309
319
  return featureDescriptor(id).label;
310
320
  }
311
321
 
322
+ /**
323
+ * Élision devant voyelle ou h muet. Le `h` aspiré ferait exception, mais aucun
324
+ * nom d'élément n'en commence, et un module qui en introduirait un lirait mal
325
+ * une fois plutôt que de faire porter le doute à tous les autres.
326
+ */
327
+ function elides(noun: string): boolean {
328
+ const first = noun
329
+ .normalize('NFD')
330
+ .replace(/[\u0300-\u036f]/g, '')
331
+ .charAt(0)
332
+ .toLowerCase();
333
+ return 'aeiouyh'.includes(first);
334
+ }
335
+
336
+ function capitalise(s: string): string {
337
+ return s.charAt(0).toUpperCase() + s.slice(1);
338
+ }
339
+
340
+ /**
341
+ * Le nom d'un élément décliné, pour les intitulés qui le précèdent d'un
342
+ * déterminant : « cet appareil », « cette note », « le dépôt ». Sans ces
343
+ * formes, une phrase écrite une fois pour toutes lit faux dès que le nom
344
+ * change de genre ou commence par une voyelle. Le repli est « élément »,
345
+ * masculin, comme le mot lui-même.
346
+ */
347
+ export function itemNounForms(id: FeatureId): {
348
+ /** « appareil » */
349
+ noun: string;
350
+ /** « cet appareil » */
351
+ dem: string;
352
+ /** « Cet appareil » */
353
+ Dem: string;
354
+ /** « l'appareil » */
355
+ def: string;
356
+ /** « L'appareil » */
357
+ Def: string;
358
+ /** « de l'appareil » */
359
+ ofThe: string;
360
+ } {
361
+ const d = maybeFeatureDescriptor(id);
362
+ const noun = d?.itemNoun ?? 'élément';
363
+ const feminine = (d?.itemNounGender ?? 'm') === 'f';
364
+ const vowel = elides(noun);
365
+
366
+ const dem = feminine ? `cette ${noun}` : vowel ? `cet ${noun}` : `ce ${noun}`;
367
+ const def = vowel ? `l\u2019${noun}` : `${feminine ? 'la' : 'le'} ${noun}`;
368
+ const ofThe = vowel ? `de l\u2019${noun}` : feminine ? `de la ${noun}` : `du ${noun}`;
369
+
370
+ return { noun, dem, Dem: capitalise(dem), def, Def: capitalise(def), ofThe };
371
+ }
372
+
312
373
  /**
313
374
  * Les deux `never` : `password` vit toujours à l'étage gardé ; `cloudsync`
314
375
  * range ses contenus dans un magasin de blobs chiffrés par la BMK, pas par une
@@ -57,10 +57,57 @@ export const itemShareStateSchema = z.object({
57
57
  /** Les espaces de l'appelant, l'origine comprise et marquée. */
58
58
  workspaces: z.array(itemShareSchema),
59
59
  /** Renseigné quand le partage est impossible ; les cases sont alors inertes. */
60
- blocker: shareBlockerSchema.nullable()
60
+ blocker: shareBlockerSchema.nullable(),
61
+ /**
62
+ * L'élément peut changer d'espace : sa fonctionnalité sait le re-chiffrer,
63
+ * il est chez lui ici, et l'appelant a le droit de l'y écrire. Faux ne dit
64
+ * pas pourquoi : c'est `share.movePreview`, une fois la cible choisie, qui
65
+ * porte les motifs.
66
+ */
67
+ movable: z.boolean().default(false)
61
68
  });
62
69
  export type ItemShareState = z.infer<typeof itemShareStateSchema>;
63
70
 
71
+ /**
72
+ * Une liaison que le déplacement va rompre. Une liaison ne traverse jamais un
73
+ * espace : ce qui vise l'élément depuis celui qu'il quitte est retiré, et
74
+ * l'écran le nomme avant de confirmer.
75
+ */
76
+ export const itemMoveDependencySchema = z.object({
77
+ feature: featureIdSchema,
78
+ itemId: z.string().min(1).max(64),
79
+ /** Son intitulé sous le codec de son espace ; « Élément disparu » si illisible. */
80
+ label: z.string(),
81
+ /** Pourquoi elle ne peut pas suivre, dit à la place de l'utilisateur. */
82
+ reason: z.string()
83
+ });
84
+ export type ItemMoveDependency = z.infer<typeof itemMoveDependencySchema>;
85
+
86
+ /**
87
+ * Ce qu'un déplacement ferait, calculé sans rien écrire. C'est le contenu du
88
+ * popup de confirmation : ce qui l'empêche, ce qu'il détruit, ce qu'il emmène.
89
+ */
90
+ export const itemMovePreviewSchema = z.object({
91
+ workspaceId: z.number().int().positive(),
92
+ workspaceName: z.string(),
93
+ /** L'espace d'origine, nommé : la phrase du popup le cite. */
94
+ homeWorkspaceName: z.string(),
95
+ /**
96
+ * L'origine est un espace partagé : ses autres membres perdront l'accès.
97
+ * Dit plutôt que gardé, la suppression n'exigeant pas davantage.
98
+ */
99
+ losesSharedAccess: z.boolean(),
100
+ /** Vide = le déplacement est possible. Sinon la première phrase est le motif affiché. */
101
+ blockers: z.array(z.string()),
102
+ /** Ce qui sera détruit ou retiré, nommé : projections, restrictions, historique. */
103
+ drops: z.array(z.string()),
104
+ /** Cellules chiffrées à convertir, pour annoncer l'ampleur plutôt que faire attendre. */
105
+ rows: z.number().int().nonnegative(),
106
+ /** Les liaisons rompues, nommées une par une. */
107
+ dependencies: z.array(itemMoveDependencySchema)
108
+ });
109
+ export type ItemMovePreview = z.infer<typeof itemMovePreviewSchema>;
110
+
64
111
  /**
65
112
  * Ce qu'un rôle peut faire sur un élément, **en surcharge** de ce que la
66
113
  * fonctionnalité lui donne : `none` masque, `read` passe en lecture seule,
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { deviceSchema, terminalUser } from '../domain/device';
3
3
  import { fileMutateOpSchema, fileSearchFilterSchema } from '../domain/deviceFiles';
4
+ import { containerEngineSchema, dockerActionSchema } from '../domain/deviceDocker';
4
5
  import {
5
6
  deviceLogAnchorSchema,
6
7
  deviceLogFilterSchema,
@@ -136,6 +137,49 @@ export const agentUpgradePackages = {
136
137
  output: z.object({ ok: z.boolean() })
137
138
  };
138
139
 
140
+ /**
141
+ * Ask the agent for its container inventory (containers, images, volumes,
142
+ * networks, plus which engines answered). Needs the `docker` permission on
143
+ * Appareils + agent online. The command only acknowledges; the inventory
144
+ * arrives as a `device.dockerInventory` push event (the caller must be
145
+ * subscribed to the device).
146
+ */
147
+ export const agentDockerInventory = {
148
+ command: 'agent.dockerInventory' as const,
149
+ input: z.object({ deviceId }),
150
+ output: z.object({ ok: z.boolean() })
151
+ };
152
+
153
+ /**
154
+ * Ask the agent for a one-shot resource sample of the running containers. The
155
+ * panel polls it while it is open; nothing is stored, the series lives in the
156
+ * browser. Streams back as `device.dockerStats`.
157
+ */
158
+ export const agentDockerStats = {
159
+ command: 'agent.dockerStats' as const,
160
+ input: z.object({ deviceId }),
161
+ output: z.object({ ok: z.boolean() })
162
+ };
163
+
164
+ /**
165
+ * Act on a container, image, volume or network. `opId` correlates the streamed
166
+ * output (`device.dockerProgress`) and the outcome (`device.dockerDone`) back
167
+ * to this request. The long actions (pull, recreate, the prunes) take a
168
+ * per-device lock: a second one is refused while the first runs.
169
+ */
170
+ export const agentDockerAction = {
171
+ command: 'agent.dockerAction' as const,
172
+ input: z.object({
173
+ deviceId,
174
+ opId: z.string().min(1).max(64),
175
+ engine: containerEngineSchema,
176
+ action: dockerActionSchema,
177
+ /** L'identifiant de la cible ; nul pour les nettoyages, qui n'en ont pas. */
178
+ target: z.string().max(512).nullable().optional()
179
+ }),
180
+ output: z.object({ ok: z.boolean() })
181
+ };
182
+
139
183
  /**
140
184
  * Ask the agent to enumerate the log sources present on the device (system journal,
141
185
  * Docker containers, log files…). Needs the `logs` permission on Appareils +
@@ -295,6 +339,9 @@ export const agentCommands = [
295
339
  agentElevate,
296
340
  agentDropPrivileges,
297
341
  agentUpdate,
342
+ agentDockerInventory,
343
+ agentDockerStats,
344
+ agentDockerAction,
298
345
  agentListPackages,
299
346
  agentUpgradePackages,
300
347
  agentLogSources,
@@ -4,6 +4,7 @@ import {
4
4
  itemAccessSchema,
5
5
  itemExtraOverridesSchema,
6
6
  itemGrantStateSchema,
7
+ itemMovePreviewSchema,
7
8
  itemRefSchema,
8
9
  itemShareStateSchema
9
10
  } from '../domain/sharing';
@@ -77,4 +78,37 @@ export const itemGrantSet = {
77
78
  output: itemGrantStateSchema
78
79
  };
79
80
 
80
- export const sharingCommands = [shareGet, shareSet, itemGrantList, itemGrantSet] as const;
81
+ /**
82
+ * Ce qu'un déplacement vers cet espace ferait, sans rien écrire : ce qui
83
+ * l'empêche, ce qu'il détruit, les liaisons qui suivent et celles qu'on peut
84
+ * emmener. Le popup de confirmation n'affiche rien d'autre.
85
+ */
86
+ export const itemMovePreview = {
87
+ command: 'share.movePreview' as const,
88
+ input: itemRefSchema.extend({ workspaceId: z.number().int().positive() }),
89
+ output: itemMovePreviewSchema
90
+ };
91
+
92
+ /**
93
+ * Déplace l'élément : sa donnée est déchiffrée sous la clé de son espace et
94
+ * re-chiffrée sous celle de la cible. La seule opération du système qui change
95
+ * un blob de clé, et donc la seule qui ne se rejoue pas.
96
+ *
97
+ * Il arrive nu : ses projections, les surcharges de rôle posées dessus, sa route
98
+ * de notification et les liaisons qui le visaient tombent, toutes désignant
99
+ * l'espace qu'il quitte.
100
+ */
101
+ export const itemMove = {
102
+ command: 'share.move' as const,
103
+ input: itemRefSchema.extend({ workspaceId: z.number().int().positive() }),
104
+ output: z.object({ workspaceId: z.number().int().positive() })
105
+ };
106
+
107
+ export const sharingCommands = [
108
+ shareGet,
109
+ shareSet,
110
+ itemGrantList,
111
+ itemGrantSet,
112
+ itemMovePreview,
113
+ itemMove
114
+ ] as const;
package/src/index.ts CHANGED
@@ -31,6 +31,13 @@ export {
31
31
  AGENT_LOG_LINES,
32
32
  AGENT_LOG_QUERY,
33
33
  AGENT_LOG_SOURCES,
34
+ AGENT_DOCKER_ACTION,
35
+ AGENT_DOCKER_DONE,
36
+ AGENT_DOCKER_INVENTORY,
37
+ AGENT_DOCKER_INVENTORY_RESULT,
38
+ AGENT_DOCKER_PROGRESS,
39
+ AGENT_DOCKER_STATS,
40
+ AGENT_DOCKER_STATS_RESULT,
34
41
  AGENT_LOG_SOURCES_RESULT,
35
42
  AGENT_METRICS_BATCH,
36
43
  AGENT_PKG_DONE,
@@ -84,6 +91,11 @@ export {
84
91
  agentLifecyclePayloadSchema,
85
92
  agentLogLinesPayloadSchema,
86
93
  agentLogQueryPayloadSchema,
94
+ agentDockerActionPayloadSchema,
95
+ agentDockerDonePayloadSchema,
96
+ agentDockerInventoryResultPayloadSchema,
97
+ agentDockerProgressPayloadSchema,
98
+ agentDockerStatsResultPayloadSchema,
87
99
  agentLogSourcesResultPayloadSchema,
88
100
  agentPkgDonePayloadSchema,
89
101
  agentPkgListResultPayloadSchema,
@@ -133,6 +145,10 @@ export {
133
145
  DEVICE_FILES_OP_EVENT,
134
146
  DEVICE_FILES_USAGE_EVENT,
135
147
  DEVICE_LOG_LINES_EVENT,
148
+ DEVICE_DOCKER_DONE_EVENT,
149
+ DEVICE_DOCKER_INVENTORY_EVENT,
150
+ DEVICE_DOCKER_PROGRESS_EVENT,
151
+ DEVICE_DOCKER_STATS_EVENT,
136
152
  DEVICE_LOG_SOURCES_EVENT,
137
153
  DEVICE_POWER_EVENT,
138
154
  DEVICE_PRESENCE_EVENT,
@@ -146,6 +162,10 @@ export {
146
162
  deviceFilesOpPushSchema,
147
163
  deviceFilesUsagePushSchema,
148
164
  deviceLogLinesPushSchema,
165
+ deviceDockerDonePushSchema,
166
+ deviceDockerInventoryPushSchema,
167
+ deviceDockerProgressPushSchema,
168
+ deviceDockerStatsPushSchema,
149
169
  deviceLogSourcesPushSchema,
150
170
  devicePowerPushSchema,
151
171
  devicePresenceSchema,
@@ -212,6 +232,11 @@ export type {
212
232
  DeviceFilesOpPush,
213
233
  DeviceFilesUsagePush,
214
234
  DeviceLogLinesPush,
235
+ AgentDockerActionPayload,
236
+ DeviceDockerDonePush,
237
+ DeviceDockerInventoryPush,
238
+ DeviceDockerProgressPush,
239
+ DeviceDockerStatsPush,
215
240
  DeviceLogSourcesPush,
216
241
  DevicePowerPush,
217
242
  DevicePresence,
@@ -251,6 +276,34 @@ export {
251
276
  deviceLogSourceKindSchema,
252
277
  deviceLogSourceSchema
253
278
  } from './domain/deviceLogs';
279
+ export {
280
+ containerEngineSchema,
281
+ containerStateSchema,
282
+ DOCKER_LONG_ACTIONS,
283
+ DOCKER_UNTARGETED_ACTIONS,
284
+ dockerActionSchema,
285
+ dockerContainerSchema,
286
+ dockerEngineStatusSchema,
287
+ dockerImageSchema,
288
+ dockerInventorySchema,
289
+ dockerNetworkSchema,
290
+ dockerStatSchema,
291
+ dockerVolumeSchema,
292
+ isLongDockerAction,
293
+ isUntargetedDockerAction
294
+ } from './domain/deviceDocker';
295
+ export type {
296
+ ContainerEngine,
297
+ ContainerState,
298
+ DockerAction,
299
+ DockerContainer,
300
+ DockerEngineStatus,
301
+ DockerImage,
302
+ DockerInventory,
303
+ DockerNetwork,
304
+ DockerStat,
305
+ DockerVolume
306
+ } from './domain/deviceDocker';
254
307
  export {
255
308
  cloudSyncProgressSchema,
256
309
  cloudSyncShareStateSchema,
@@ -552,6 +605,7 @@ export {
552
605
  allFeatureDescriptors,
553
606
  featureDescriptor,
554
607
  featureLabel,
608
+ itemNounForms,
555
609
  maybeFeatureDescriptor,
556
610
  registerExternalFeature
557
611
  } from './domain/featureRegistry';
@@ -561,6 +615,8 @@ export {
561
615
  itemAccessSchema,
562
616
  itemExtraOverridesSchema,
563
617
  itemGrantStateSchema,
618
+ itemMoveDependencySchema,
619
+ itemMovePreviewSchema,
564
620
  itemRefSchema,
565
621
  itemRoleGrantSchema,
566
622
  itemRoleGrantViewSchema,
@@ -573,6 +629,8 @@ export type {
573
629
  ItemAccess,
574
630
  ItemExtraOverrides,
575
631
  ItemGrantState,
632
+ ItemMoveDependency,
633
+ ItemMovePreview,
576
634
  ItemRef,
577
635
  ItemRoleGrant,
578
636
  ItemRoleGrantRow,
@@ -585,6 +643,8 @@ export type {
585
643
  export {
586
644
  itemGrantList,
587
645
  itemGrantSet,
646
+ itemMove,
647
+ itemMovePreview,
588
648
  shareGet,
589
649
  shareSet,
590
650
  sharingCommands
@@ -677,6 +737,9 @@ export {
677
737
  agentFilesMutate,
678
738
  agentFilesSearch,
679
739
  agentFilesUpload,
740
+ agentDockerAction,
741
+ agentDockerInventory,
742
+ agentDockerStats,
680
743
  agentLifecycle,
681
744
  agentListPackages,
682
745
  agentLogQuery,
@@ -27,6 +27,12 @@ import {
27
27
  deviceLogLineSchema,
28
28
  deviceLogSourceSchema
29
29
  } from '../domain/deviceLogs';
30
+ import {
31
+ containerEngineSchema,
32
+ dockerActionSchema,
33
+ dockerInventorySchema,
34
+ dockerStatSchema
35
+ } from '../domain/deviceDocker';
30
36
  import { metricsBatchSchema, metricSnapshotSchema } from '../domain/metrics';
31
37
  import { packageManagerIdSchema, packageManagerSchema } from '../domain/packages';
32
38
  import {
@@ -129,6 +135,43 @@ export const agentPkgDonePayloadSchema = z.object({
129
135
  error: z.string().max(500).optional()
130
136
  });
131
137
 
138
+ /** Agent's reply to `docker.inventory`: the host's whole container inventory. */
139
+ export const AGENT_DOCKER_INVENTORY_RESULT = 'docker.inventoryResult' as const;
140
+
141
+ export const agentDockerInventoryResultPayloadSchema = z.object({
142
+ deviceId: z.uuid(),
143
+ inventory: dockerInventorySchema
144
+ });
145
+
146
+ /** Agent's reply to `docker.stats`: a one-shot resource sample per running container. */
147
+ export const AGENT_DOCKER_STATS_RESULT = 'docker.statsResult' as const;
148
+
149
+ export const agentDockerStatsResultPayloadSchema = z.object({
150
+ deviceId: z.uuid(),
151
+ stats: z.array(dockerStatSchema)
152
+ });
153
+
154
+ /** Live output line of a long `docker.action` (pull, prune, recreate). */
155
+ export const AGENT_DOCKER_PROGRESS = 'docker.progress' as const;
156
+
157
+ export const agentDockerProgressPayloadSchema = z.object({
158
+ deviceId: z.uuid(),
159
+ /** Correlates back to the originating `docker.action` (echoed verbatim). */
160
+ opId: z.string().max(64),
161
+ line: z.string().max(2000)
162
+ });
163
+
164
+ /** Final outcome of a `docker.action`. */
165
+ export const AGENT_DOCKER_DONE = 'docker.done' as const;
166
+
167
+ export const agentDockerDonePayloadSchema = z.object({
168
+ deviceId: z.uuid(),
169
+ opId: z.string().max(64),
170
+ action: dockerActionSchema,
171
+ ok: z.boolean(),
172
+ error: z.string().max(500).optional()
173
+ });
174
+
132
175
  /** Agent's reply to `agent.service`: outcome of a persistence/privilege change. */
133
176
  export const AGENT_SERVICE_RESULT = 'agent.serviceResult' as const;
134
177
 
@@ -448,6 +491,22 @@ export const agentClientMessageSchema = z.discriminatedUnion('command', [
448
491
  command: z.literal(AGENT_POWER_RESULT),
449
492
  payload: agentPowerResultPayloadSchema
450
493
  }),
494
+ z.object({
495
+ command: z.literal(AGENT_DOCKER_INVENTORY_RESULT),
496
+ payload: agentDockerInventoryResultPayloadSchema
497
+ }),
498
+ z.object({
499
+ command: z.literal(AGENT_DOCKER_STATS_RESULT),
500
+ payload: agentDockerStatsResultPayloadSchema
501
+ }),
502
+ z.object({
503
+ command: z.literal(AGENT_DOCKER_PROGRESS),
504
+ payload: agentDockerProgressPayloadSchema
505
+ }),
506
+ z.object({
507
+ command: z.literal(AGENT_DOCKER_DONE),
508
+ payload: agentDockerDonePayloadSchema
509
+ }),
451
510
  z.object({
452
511
  command: z.literal(AGENT_LOG_SOURCES_RESULT),
453
512
  payload: agentLogSourcesResultPayloadSchema
@@ -574,6 +633,28 @@ export const AGENT_PKG_UPGRADE = 'pkg.upgrade' as const;
574
633
  export const agentPkgUpgradePayloadSchema = z.object({ manager: packageManagerIdSchema });
575
634
  export type AgentPkgUpgradePayload = z.infer<typeof agentPkgUpgradePayloadSchema>;
576
635
 
636
+ /** Ask the agent for its container inventory (`docker.inventoryResult`). */
637
+ export const AGENT_DOCKER_INVENTORY = 'docker.inventory' as const;
638
+
639
+ /** Ask the agent for a one-shot resource sample of the running containers. */
640
+ export const AGENT_DOCKER_STATS = 'docker.stats' as const;
641
+
642
+ /**
643
+ * Ask the agent to act on a container, image, volume or network. `opId`
644
+ * correlates the streamed output and the outcome back to this order. `target`
645
+ * is the object's own identifier, and it is the ONLY caller-supplied value that
646
+ * reaches a command line; the untargeted actions (the prunes) carry none.
647
+ */
648
+ export const AGENT_DOCKER_ACTION = 'docker.action' as const;
649
+
650
+ export const agentDockerActionPayloadSchema = z.object({
651
+ opId: z.string().min(1).max(64),
652
+ engine: containerEngineSchema,
653
+ action: dockerActionSchema,
654
+ target: z.string().max(512).nullable()
655
+ });
656
+ export type AgentDockerActionPayload = z.infer<typeof agentDockerActionPayloadSchema>;
657
+
577
658
  /** Ask the agent to perform a system power action (`agent.powerResult` reports the outcome). */
578
659
  export const AGENT_POWER = 'agent.power' as const;
579
660
 
@@ -943,6 +1024,18 @@ export const agentServerMessageSchema = z.discriminatedUnion('command', [
943
1024
  command: z.literal(AGENT_PKG_UPGRADE),
944
1025
  payload: agentPkgUpgradePayloadSchema
945
1026
  }),
1027
+ z.object({
1028
+ command: z.literal(AGENT_DOCKER_INVENTORY),
1029
+ payload: z.object({})
1030
+ }),
1031
+ z.object({
1032
+ command: z.literal(AGENT_DOCKER_STATS),
1033
+ payload: z.object({})
1034
+ }),
1035
+ z.object({
1036
+ command: z.literal(AGENT_DOCKER_ACTION),
1037
+ payload: agentDockerActionPayloadSchema
1038
+ }),
946
1039
  z.object({
947
1040
  command: z.literal(AGENT_POWER),
948
1041
  payload: agentPowerPayloadSchema
@@ -1043,6 +1136,11 @@ export const DEVICE_POWER_EVENT = 'device.powerResult' as const;
1043
1136
  * subscribers exactly like the power result.
1044
1137
  */
1045
1138
  export const DEVICE_SERVICE_EVENT = 'device.serviceResult' as const;
1139
+ /** Container inventory, live stats sample, and action progress/outcome. */
1140
+ export const DEVICE_DOCKER_INVENTORY_EVENT = 'device.dockerInventory' as const;
1141
+ export const DEVICE_DOCKER_STATS_EVENT = 'device.dockerStats' as const;
1142
+ export const DEVICE_DOCKER_PROGRESS_EVENT = 'device.dockerProgress' as const;
1143
+ export const DEVICE_DOCKER_DONE_EVENT = 'device.dockerDone' as const;
1046
1144
  /** Device log sources inventory + queried log lines, fanned to subscribers. */
1047
1145
  export const DEVICE_LOG_SOURCES_EVENT = 'device.logSources' as const;
1048
1146
  export const DEVICE_LOG_LINES_EVENT = 'device.logLines' as const;
@@ -1080,6 +1178,17 @@ export const packageProgressPushSchema = agentPkgProgressPayloadSchema;
1080
1178
  export const packageDonePushSchema = agentPkgDonePayloadSchema;
1081
1179
  export const devicePowerPushSchema = agentPowerResultPayloadSchema;
1082
1180
  export const deviceServicePushSchema = agentServiceResultPayloadSchema;
1181
+ /**
1182
+ * L'inventaire, enrichi par le serveur de ce que l'agent ignore : l'action
1183
+ * longue déjà en cours sur cet appareil. Sans ce champ, un second écran
1184
+ * relancerait le même `prune`.
1185
+ */
1186
+ export const deviceDockerInventoryPushSchema = agentDockerInventoryResultPayloadSchema.extend({
1187
+ running: z.string().max(64).nullable().default(null)
1188
+ });
1189
+ export const deviceDockerStatsPushSchema = agentDockerStatsResultPayloadSchema;
1190
+ export const deviceDockerProgressPushSchema = agentDockerProgressPayloadSchema;
1191
+ export const deviceDockerDonePushSchema = agentDockerDonePayloadSchema;
1083
1192
  export const deviceLogSourcesPushSchema = agentLogSourcesResultPayloadSchema;
1084
1193
  export const deviceLogLinesPushSchema = agentLogLinesPayloadSchema;
1085
1194
  export const deviceTermOutputPushSchema = agentTermOutputPayloadSchema;
@@ -1105,6 +1214,11 @@ export type CloudSyncProgressPush = z.infer<typeof cloudSyncProgressPushSchema>;
1105
1214
  export type CloudSyncStatePush = z.infer<typeof cloudSyncStatePushSchema>;
1106
1215
  export type CloudSyncChunkPush = z.infer<typeof cloudSyncChunkPushSchema>;
1107
1216
 
1217
+ export type DeviceDockerInventoryPush = z.infer<typeof deviceDockerInventoryPushSchema>;
1218
+ export type DeviceDockerStatsPush = z.infer<typeof deviceDockerStatsPushSchema>;
1219
+ export type DeviceDockerProgressPush = z.infer<typeof deviceDockerProgressPushSchema>;
1220
+ export type DeviceDockerDonePush = z.infer<typeof deviceDockerDonePushSchema>;
1221
+
1108
1222
  export type PackageListPush = z.infer<typeof packageListPushSchema>;
1109
1223
  export type PackageStartedPush = z.infer<typeof packageStartedPushSchema>;
1110
1224
  export type PackageProgressPush = z.infer<typeof packageProgressPushSchema>;
@@ -66,10 +66,25 @@ declare module 'deveye-sdk-client' {
66
66
  value: T;
67
67
  options: readonly { value: T; label: string; title?: string }[];
68
68
  onChange: (value: T) => void;
69
+ /** Étire le groupe sur la ligne, chaque choix en prenant une part égale. */
70
+ fullWidth?: boolean;
69
71
  className?: string;
70
72
  'aria-label'?: string;
71
73
  disabled?: boolean;
72
74
  }): ReactNode;
75
+ /**
76
+ * Le bouton d'enregistrement d'un panneau de réglages : « Enregistrement… »
77
+ * pendant l'aller-retour, « Enregistré » quelques secondes, puis l'intitulé
78
+ * de départ. Les erreurs restent au panneau, elles ne s'effacent pas seules.
79
+ */
80
+ export const SaveButton: ComponentType<{
81
+ onSave: () => Promise<unknown> | unknown;
82
+ children?: string;
83
+ disabled?: boolean;
84
+ variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
85
+ icon?: string;
86
+ title?: string;
87
+ }>;
73
88
  export const Dialog: ComponentType<{
74
89
  open: boolean;
75
90
  onClose: () => void;
@@ -60,7 +60,7 @@ export type ExtraPermissionSpec =
60
60
  };
61
61
 
62
62
  /** Hard cap on `extraPermissions`: keeps role editors legible. */
63
- export const MAX_EXTRA_PERMISSIONS = 4;
63
+ export const MAX_EXTRA_PERMISSIONS = 10;
64
64
 
65
65
  const EXTRA_KEY_PATTERN = /^[a-z][a-zA-Z0-9]{1,23}$/;
66
66
 
@@ -0,0 +1,140 @@
1
+ import assert from 'node:assert/strict';
2
+ import { describe, it } from 'node:test';
3
+
4
+ import {
5
+ countMovableCells,
6
+ FeatureError,
7
+ resealCells,
8
+ type MovableCell,
9
+ type SdkCipher,
10
+ type SdkQueryable
11
+ } from './server';
12
+
13
+ /**
14
+ * Le rescellement d'un élément qui change d'espace. Ce qui se vérifie ici est
15
+ * ce qui ne pardonne pas : une seule cellule illisible doit tout annuler AVANT
16
+ * la première écriture, un arbre à moitié converti étant définitivement illisible
17
+ * sans que rien puisse le détecter.
18
+ */
19
+
20
+ interface Row {
21
+ row_id: number;
22
+ value: string;
23
+ }
24
+
25
+ /**
26
+ * Un queryable qui ne comprend du SQL que la table et la colonne lues, et qui
27
+ * retient ce qu'on a tenté d'écrire.
28
+ */
29
+ function fakeQ(cells: Record<string, Row[]>) {
30
+ const writes: { sql: string; params: unknown[] }[] = [];
31
+ const q: SdkQueryable = {
32
+ query: async <T extends object>(sql: string, params?: unknown[]) => {
33
+ void params;
34
+ const count = /SELECT COUNT\(\*\) AS n FROM (\w+)\s+WHERE (\w+)/.exec(sql);
35
+ if (count) {
36
+ return [
37
+ { n: (cells[`${count[1]}.${columnOf(sql)}`] ?? []).length }
38
+ ] as unknown as T[];
39
+ }
40
+ const read = /AS row_id, (\w+) AS value\s+FROM (\w+)/.exec(sql);
41
+ return (read ? (cells[`${read[2]}.${read[1]}`] ?? []) : []) as unknown as T[];
42
+ },
43
+ execute: async (sql: string, params?: unknown[]) => {
44
+ writes.push({ sql, params: params ?? [] });
45
+ return { affectedRows: 1, insertId: 0 };
46
+ }
47
+ };
48
+ return { q, writes };
49
+ }
50
+
51
+ /** La colonne d'un COUNT, que le SQL ne nomme que dans son `WHERE`. */
52
+ function columnOf(sql: string): string {
53
+ return /AND (\w+) IS NOT NULL/.exec(sql)?.[1] ?? '';
54
+ }
55
+
56
+ function cipherOf(tag: string): SdkCipher {
57
+ return {
58
+ encrypt: async (plain) => `${tag}:${plain}`,
59
+ decrypt: async (blob) => blob.slice(tag.length + 1),
60
+ tryDecrypt: async (blob) => (blob.startsWith(`${tag}:`) ? blob.slice(tag.length + 1) : null)
61
+ };
62
+ }
63
+
64
+ const ciphers = { from: cipherOf('A'), to: cipherOf('B') };
65
+
66
+ const CELLS: MovableCell[] = [
67
+ { table: 'ft_x_items', idColumn: 'id', ownerColumn: 'id', column: 'content' },
68
+ { table: 'ft_x_children', idColumn: 'id', ownerColumn: 'item_id', column: 'body' }
69
+ ];
70
+
71
+ describe('resealCells', () => {
72
+ it('rescelle chaque cellule sous la clé cible, la garde du propriétaire comprise', async () => {
73
+ const { q, writes } = fakeQ({
74
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
75
+ 'ft_x_children.body': [
76
+ { row_id: 1, value: 'A:un' },
77
+ { row_id: 2, value: 'A:deux' }
78
+ ]
79
+ });
80
+
81
+ assert.equal(await resealCells(q, CELLS, 7, ciphers), 3);
82
+ assert.deepEqual(
83
+ writes.map((w) => w.params),
84
+ [
85
+ ['B:corps', 7, 7],
86
+ ['B:un', 1, 7],
87
+ ['B:deux', 2, 7]
88
+ ]
89
+ );
90
+ // La ligne se cible par son identifiant ET son propriétaire : une
91
+ // conversion ne peut pas déborder sur un voisin.
92
+ assert.match(writes[1]!.sql, /WHERE id = \? AND item_id = \?/);
93
+ });
94
+
95
+ it('annule tout sur une cellule illisible, sans avoir écrit une seule ligne', async () => {
96
+ const { q, writes } = fakeQ({
97
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
98
+ // Scellée sous une troisième clé : la conversion doit renoncer.
99
+ 'ft_x_children.body': [{ row_id: 1, value: 'Z:perdu' }]
100
+ });
101
+
102
+ await assert.rejects(
103
+ resealCells(q, CELLS, 7, ciphers),
104
+ (err: unknown) => err instanceof FeatureError && /illisible/.test(err.message)
105
+ );
106
+ assert.equal(writes.length, 0);
107
+ });
108
+
109
+ it('suit un sous-parcours pour une ligne qui pend indirectement', async () => {
110
+ const indirect: MovableCell[] = [
111
+ {
112
+ table: 'ft_x_leaves',
113
+ idColumn: 'id',
114
+ ownerColumn: 'child_id',
115
+ ownerScope: 'SELECT id FROM ft_x_children WHERE item_id = ?',
116
+ column: 'body'
117
+ }
118
+ ];
119
+ const { q, writes } = fakeQ({ 'ft_x_leaves.body': [{ row_id: 5, value: 'A:feuille' }] });
120
+
121
+ await resealCells(q, indirect, 7, ciphers);
122
+ assert.match(
123
+ writes[0]!.sql,
124
+ /WHERE id = \? AND child_id IN \(SELECT id FROM ft_x_children WHERE item_id = \?\)/
125
+ );
126
+ assert.deepEqual(writes[0]!.params, ['B:feuille', 5, 7]);
127
+ });
128
+
129
+ it('compte ce qu’il y aurait à convertir sans rien convertir', async () => {
130
+ const { q, writes } = fakeQ({
131
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
132
+ 'ft_x_children.body': [
133
+ { row_id: 1, value: 'A:un' },
134
+ { row_id: 2, value: 'A:deux' }
135
+ ]
136
+ });
137
+ assert.equal(await countMovableCells(q, CELLS, 7), 3);
138
+ assert.equal(writes.length, 0);
139
+ });
140
+ });
@@ -261,6 +261,16 @@ export interface ProjectsUsageProvider {
261
261
  usageOf(feature: string, itemId: number, workspaceId: number): Promise<readonly ProjectUsage[]>;
262
262
  /** How many projects of the workspace link each item of this feature (absent = zero). */
263
263
  countByItem(feature: string, workspaceId: number): Promise<ReadonlyMap<number, number>>;
264
+ /**
265
+ * The item leaves the workspace: drop every link pointing at it from
266
+ * there, and answer how many projects lost one. A link never spans two
267
+ * workspaces, so a departing item takes none with it; left alone the rows
268
+ * would keep naming an item that lives elsewhere now.
269
+ *
270
+ * Called by the app when an item is moved out, not by the module that owns
271
+ * the item. Idempotent, and zero for a feature that links nothing.
272
+ */
273
+ detach(feature: string, itemId: number, workspaceId: number): Promise<number>;
264
274
  /**
265
275
  * Writes one line in a project's timeline (a deployment triggered from a
266
276
  * project's tab). Open tier only: an event aimed at a guarded project is
package/src/sdk/server.ts CHANGED
@@ -835,6 +835,186 @@ export interface FeatureItemsEntry<Repo = unknown> {
835
835
  * HOME workspace.
836
836
  */
837
837
  shareable?(repo: Repo, itemId: string, workspaceId: number): Promise<boolean>;
838
+ /**
839
+ * Move this item to another workspace. The ONLY operation of the whole
840
+ * system that re-encrypts (read under key A, written under key B); every
841
+ * other one keeps a blob under the key it was sealed with. Omit it and
842
+ * your items cannot be moved: the screen offers nothing and `item.move`
843
+ * refuses. That default is the safe one, and staying on it is a valid
844
+ * answer for a feature whose item depends on a workspace source (a
845
+ * credential, a destination) that cannot follow it.
846
+ */
847
+ move?: FeatureItemsMove<Repo>;
848
+ }
849
+
850
+ /**
851
+ * What moving one item would cost, decided while it is still at home and
852
+ * before a single row is written.
853
+ */
854
+ export interface SdkMovePlan {
855
+ /**
856
+ * Why the move is impossible, in sentences the screen shows as they are.
857
+ * Empty means it can go. Put the decisive one first: a name already taken
858
+ * in the target, a source of the origin workspace that cannot follow.
859
+ */
860
+ blockers: readonly string[];
861
+ /**
862
+ * What the move destroys, named one by one, for the confirmation to list
863
+ * verbatim: a history left behind, a setting that means nothing there.
864
+ * Say it here or the caller discovers it afterwards.
865
+ */
866
+ drops: readonly string[];
867
+ /**
868
+ * Encrypted cells to convert, so the confirmation can say how much rather
869
+ * than spin. An estimate is fine; zero is a legitimate answer.
870
+ */
871
+ rows: number;
872
+ }
873
+
874
+ /** See {@link FeatureItemsEntry.move}. */
875
+ export interface FeatureItemsMove<Repo = unknown> {
876
+ /**
877
+ * Everything the confirmation must say, and every refusal, with the item
878
+ * still at home and nothing written yet. Answer for THAT target: a name
879
+ * collision or a missing source is decidable only against it.
880
+ */
881
+ plan(ctx: FeatureItemsMovePlanContext<Repo>): Promise<SdkMovePlan>;
882
+ /**
883
+ * Re-home the item: `workspace_id` on every row it owns, and every
884
+ * encrypted cell read with `ciphers.from` and written with `ciphers.to`.
885
+ *
886
+ * Read and convert EVERYTHING before the first write. A tree half
887
+ * converted is unreadable forever and nothing can detect it: one encrypted
888
+ * blob is indistinguishable from another. `reencryptProjectTree` in the
889
+ * Projects module is the reference implementation.
890
+ */
891
+ apply(ctx: FeatureItemsMoveContext<Repo>): Promise<void>;
892
+ }
893
+
894
+ /** The handles {@link FeatureItemsMove.plan} works with. Reads only. */
895
+ export interface FeatureItemsMovePlanContext<Repo = unknown> {
896
+ /** Not transactional: planning writes nothing. {@link countMovableCells} takes it. */
897
+ q: SdkQueryable;
898
+ repo: Repo;
899
+ itemId: string;
900
+ fromWorkspaceId: number;
901
+ toWorkspaceId: number;
902
+ }
903
+
904
+ /** The handles {@link FeatureItemsMove.apply} works with. */
905
+ export interface FeatureItemsMoveContext<Repo = unknown> {
906
+ /**
907
+ * Transactional: what you write here commits with the app's own cleanup,
908
+ * or rolls back with it. Write through this, NEVER through `repo`, which
909
+ * is bound to the pool and would land outside the transaction.
910
+ */
911
+ q: SdkQueryable;
912
+ /** Your repo. For reads only, see `q`. */
913
+ repo: Repo;
914
+ itemId: string;
915
+ fromWorkspaceId: number;
916
+ toWorkspaceId: number;
917
+ /** The open ciphers of the two workspaces: decrypt with `from`, seal with `to`. */
918
+ ciphers: { from: SdkCipher; to: SdkCipher };
919
+ }
920
+
921
+ /**
922
+ * One column of encrypted text hanging off an item, for {@link resealCells}.
923
+ *
924
+ * ⚠️ The list you build out of these is held BY HAND: an encrypted column left
925
+ * out of it stays under the old key and becomes unreadable, and nothing can
926
+ * detect it, one encrypted blob being indistinguishable from another. Revisit
927
+ * it whenever you add an encrypted column.
928
+ */
929
+ export interface MovableCell {
930
+ table: string;
931
+ /** Identifying column of the row, to rewrite exactly one. */
932
+ idColumn: string;
933
+ /** Column tying the row to the item. */
934
+ ownerColumn: string;
935
+ column: string;
936
+ /**
937
+ * For a row hanging off the item INDIRECTLY: a SQL subquery selecting the
938
+ * `ownerColumn` values that belong to it, taking the item's id as its only
939
+ * `?` (a mail account's messages hang off its folders:
940
+ * `SELECT id FROM mail_folders WHERE account_id = ?`).
941
+ *
942
+ * Interpolated into the query, so it must be a literal written in your
943
+ * module, exactly like `table` and `column`. Never build it from input.
944
+ */
945
+ ownerScope?: string;
946
+ }
947
+
948
+ /** `WHERE` fragment tying a cell's rows to the item, subquery included. */
949
+ function ownerFilter(cell: MovableCell): string {
950
+ return cell.ownerScope
951
+ ? `${cell.ownerColumn} IN (${cell.ownerScope})`
952
+ : `${cell.ownerColumn} = ?`;
953
+ }
954
+
955
+ /** How many cells {@link resealCells} would convert: a `plan`'s `rows`. */
956
+ export async function countMovableCells(
957
+ q: SdkQueryable,
958
+ cells: readonly MovableCell[],
959
+ ownerId: string | number
960
+ ): Promise<number> {
961
+ let total = 0;
962
+ for (const cell of cells) {
963
+ const rows = await q.query<{ n: number }>(
964
+ `SELECT COUNT(*) AS n FROM ${cell.table}
965
+ WHERE ${ownerFilter(cell)} AND ${cell.column} IS NOT NULL AND ${cell.column} <> ''`,
966
+ [ownerId]
967
+ );
968
+ total += Number(rows[0]?.n ?? 0);
969
+ }
970
+ return total;
971
+ }
972
+
973
+ /**
974
+ * Re-seals every encrypted cell of an item from one workspace's key to
975
+ * another's, for a `move`'s `apply`.
976
+ *
977
+ * Reads and converts EVERYTHING before the first write, and throws before
978
+ * writing anything if one cell resists: half a converted tree is unreadable
979
+ * forever. Call it before you change the item's `workspace_id`, so a failure
980
+ * leaves the item where it was.
981
+ */
982
+ export async function resealCells(
983
+ q: SdkQueryable,
984
+ cells: readonly MovableCell[],
985
+ ownerId: string | number,
986
+ ciphers: { from: SdkCipher; to: SdkCipher }
987
+ ): Promise<number> {
988
+ const pending: { cell: MovableCell; id: string | number; value: string }[] = [];
989
+ for (const cell of cells) {
990
+ // A cell that is empty has nothing to convert, and that is the common
991
+ // case for an error message or an optional body.
992
+ const rows = await q.query<{ row_id: string | number; value: string }>(
993
+ `SELECT ${cell.idColumn} AS row_id, ${cell.column} AS value FROM ${cell.table}
994
+ WHERE ${ownerFilter(cell)} AND ${cell.column} IS NOT NULL AND ${cell.column} <> ''`,
995
+ [ownerId]
996
+ );
997
+ for (const row of rows) {
998
+ const plain = await ciphers.from.tryDecrypt(String(row.value));
999
+ if (plain === null) {
1000
+ throw new FeatureError(
1001
+ 'internal',
1002
+ `Une ligne de ${cell.table} est illisible : déplacement annulé, rien n’a été modifié.`
1003
+ );
1004
+ }
1005
+ pending.push({ cell, id: row.row_id, value: await ciphers.to.encrypt(plain) });
1006
+ }
1007
+ }
1008
+
1009
+ for (const { cell, id, value } of pending) {
1010
+ // La garde du propriétaire dans le `WHERE` même quand l'identifiant
1011
+ // suffit : une conversion ne peut alors pas déborder sur un voisin.
1012
+ await q.execute(
1013
+ `UPDATE ${cell.table} SET ${cell.column} = ? WHERE ${cell.idColumn} = ? AND ${ownerFilter(cell)}`,
1014
+ [value, id, ownerId]
1015
+ );
1016
+ }
1017
+ return pending.length;
838
1018
  }
839
1019
 
840
1020
  // Le conteneur chiffré que CloudSync et Backup partagent (voir `devb.ts`).