@myrialabs/clopen 0.3.16 → 0.3.18

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.
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Files Image Edit Operation
3
+ *
4
+ * Applies a declarative `ImageEditRecipe` (crop/resize/rotate/flip/filters/
5
+ * compression) to an image on disk with sharp and writes the result either back
6
+ * over the original or to a new copy.
7
+ *
8
+ * The recipe is small JSON and the source is read server-side from disk, so no
9
+ * large binary crosses the wire in either direction — this fits the existing
10
+ * WS-http router rather than the streaming HTTP upload route.
11
+ */
12
+
13
+ import { t } from 'elysia';
14
+ import { stat as fsStat } from 'node:fs/promises';
15
+
16
+ import { createRouter } from '$shared/utils/ws-server';
17
+ import { debug } from '$shared/utils/logger';
18
+ import type { ImageEditRecipe } from '$shared/types/filesystem';
19
+ import { processImageEdit } from '../../files/image-processing';
20
+ import { requireFilePathAccess } from './path-access';
21
+
22
+ const cropSchema = t.Object({
23
+ left: t.Number(),
24
+ top: t.Number(),
25
+ width: t.Number(),
26
+ height: t.Number()
27
+ });
28
+
29
+ const recipeSchema = t.Object({
30
+ crop: t.Optional(cropSchema),
31
+ resize: t.Optional(t.Object({ width: t.Number(), height: t.Number() })),
32
+ rotate: t.Optional(
33
+ t.Union([t.Literal(0), t.Literal(90), t.Literal(180), t.Literal(270)])
34
+ ),
35
+ flipH: t.Optional(t.Boolean()),
36
+ flipV: t.Optional(t.Boolean()),
37
+ brightness: t.Optional(t.Number()),
38
+ saturation: t.Optional(t.Number()),
39
+ contrast: t.Optional(t.Number()),
40
+ hue: t.Optional(t.Number()),
41
+ blur: t.Optional(t.Number()),
42
+ grayscale: t.Optional(t.Boolean()),
43
+ sepia: t.Optional(t.Boolean()),
44
+ invert: t.Optional(t.Boolean()),
45
+ background: t.Optional(t.String()),
46
+ regions: t.Optional(
47
+ t.Array(
48
+ t.Object({
49
+ type: t.Union([t.Literal('blur'), t.Literal('pixelate')]),
50
+ left: t.Number(),
51
+ top: t.Number(),
52
+ width: t.Number(),
53
+ height: t.Number(),
54
+ strength: t.Number()
55
+ })
56
+ )
57
+ ),
58
+ annotations: t.Optional(
59
+ t.Array(
60
+ t.Object({
61
+ color: t.String(),
62
+ size: t.Number(),
63
+ opacity: t.Optional(t.Number()),
64
+ points: t.Array(t.Object({ x: t.Number(), y: t.Number() }))
65
+ })
66
+ )
67
+ ),
68
+ output: t.Object({
69
+ format: t.Union([
70
+ t.Literal('png'),
71
+ t.Literal('jpeg'),
72
+ t.Literal('webp'),
73
+ t.Literal('gif'),
74
+ t.Literal('avif')
75
+ ]),
76
+ compress: t.Optional(t.Boolean()),
77
+ quality: t.Optional(t.Number()),
78
+ lossless: t.Optional(t.Boolean())
79
+ })
80
+ });
81
+
82
+ export const imageEditHandler = createRouter()
83
+ // Dry-run: apply the recipe and report the resulting byte size without
84
+ // writing anything — drives the editor's live "Result size" readout, so it
85
+ // matches the real save exactly (same codec) instead of a browser estimate.
86
+ .http('files:estimate-image', {
87
+ data: t.Object({
88
+ sourcePath: t.String(),
89
+ recipe: recipeSchema
90
+ }),
91
+ response: t.Object({
92
+ size: t.Number(),
93
+ width: t.Number(),
94
+ height: t.Number()
95
+ })
96
+ }, async ({ data, conn }) => {
97
+ const sourcePath = await requireFilePathAccess(conn, data.sourcePath);
98
+ // Fast mode: lower encoder effort so the live estimate stays responsive
99
+ // on very large images / upscales. The real save uses full effort.
100
+ const result = await processImageEdit(sourcePath, data.recipe as ImageEditRecipe, true);
101
+ return { size: result.size, width: result.width, height: result.height };
102
+ })
103
+
104
+ .http('files:edit-image', {
105
+ data: t.Object({
106
+ sourcePath: t.String(),
107
+ targetPath: t.String(),
108
+ // true = write over targetPath even if it exists; false = refuse if it exists.
109
+ overwrite: t.Boolean(),
110
+ recipe: recipeSchema,
111
+ // Optimistic concurrency token: the disk mtime the editor based its
112
+ // source on. Only checked when overwriting an existing file.
113
+ baseModified: t.Optional(t.String())
114
+ }),
115
+ response: t.Object({
116
+ message: t.String(),
117
+ path: t.String(),
118
+ size: t.Number(),
119
+ width: t.Number(),
120
+ height: t.Number(),
121
+ modified: t.String()
122
+ })
123
+ }, async ({ data, conn }) => {
124
+ const sourcePath = await requireFilePathAccess(conn, data.sourcePath);
125
+ const targetPath = await requireFilePathAccess(conn, data.targetPath);
126
+
127
+ const targetStat = await fsStat(targetPath).catch(() => null);
128
+
129
+ if (data.overwrite) {
130
+ // Refuse to clobber a version newer than the one the editor loaded.
131
+ if (targetStat && data.baseModified && targetStat.mtime.toISOString() !== data.baseModified) {
132
+ throw new Error('FILE_CONFLICT: file changed on disk since it was opened in the editor');
133
+ }
134
+ } else if (targetStat) {
135
+ throw new Error('File already exists');
136
+ }
137
+
138
+ const recipe = data.recipe as ImageEditRecipe;
139
+ debug.log('file', 'Edit image operation:', {
140
+ sourcePath,
141
+ targetPath,
142
+ overwrite: data.overwrite,
143
+ format: recipe.output.format
144
+ });
145
+
146
+ const result = await processImageEdit(sourcePath, recipe);
147
+ await Bun.write(targetPath, result.data);
148
+
149
+ const stats = await fsStat(targetPath);
150
+ return {
151
+ message: data.overwrite ? 'Image saved successfully' : 'Image saved as a new file',
152
+ path: targetPath,
153
+ size: result.size,
154
+ width: result.width,
155
+ height: result.height,
156
+ modified: stats.mtime.toISOString()
157
+ };
158
+ });
@@ -13,6 +13,7 @@
13
13
  import { createRouter } from '$shared/utils/ws-server';
14
14
  import { readHandler } from './read';
15
15
  import { writeHandler } from './write';
16
+ import { imageEditHandler } from './image-edit';
16
17
  import { fileSearchHandler } from './search';
17
18
  import { watchHandler } from './watch';
18
19
  import { filesStateHandler } from './state';
@@ -24,6 +25,9 @@ export const filesRouter = createRouter()
24
25
  // Write Operations (HTTP)
25
26
  .merge(writeHandler)
26
27
 
28
+ // Image Edit Operation (HTTP)
29
+ .merge(imageEditHandler)
30
+
27
31
  // Search Operations (HTTP)
28
32
  .merge(fileSearchHandler)
29
33
 
@@ -218,7 +218,11 @@ export const readHandler = createRouter()
218
218
  }),
219
219
  response: t.Object({
220
220
  content: t.String(), // Base64 encoded binary content
221
- contentType: t.String()
221
+ contentType: t.String(),
222
+ // Disk mtime + size — used by the image editor as an optimistic
223
+ // concurrency token and to report compression savings.
224
+ modified: t.Optional(t.String()),
225
+ size: t.Optional(t.Number())
222
226
  })
223
227
  }, async ({ data, conn }) => {
224
228
  const path = await requireFilePathAccess(conn, data.path);
@@ -239,8 +243,12 @@ export const readHandler = createRouter()
239
243
  // Detect content type
240
244
  const contentType = file.type || 'application/octet-stream';
241
245
 
246
+ const stats = await file.stat();
247
+
242
248
  return {
243
249
  content: base64,
244
- contentType
250
+ contentType,
251
+ modified: stats.mtime.toISOString(),
252
+ size: stats.size
245
253
  };
246
254
  });
@@ -34,4 +34,67 @@ export const commitHandler = createRouter()
34
34
  const project = requireProjectAccess(conn, data.projectId);
35
35
  const hash = await gitService.amendCommit(project.path, data.message);
36
36
  return { hash };
37
+ })
38
+
39
+ .http('git:undo-commit', {
40
+ data: t.Object({
41
+ projectId: t.String(),
42
+ mode: t.Union([t.Literal('soft'), t.Literal('mixed'), t.Literal('hard')])
43
+ }),
44
+ response: t.Object({ ok: t.Boolean() })
45
+ }, async ({ data, conn }) => {
46
+ const project = requireProjectAccess(conn, data.projectId);
47
+ await gitService.undoLastCommit(project.path, data.mode);
48
+ return { ok: true };
49
+ })
50
+
51
+ .http('git:revert', {
52
+ data: t.Object({
53
+ projectId: t.String(),
54
+ ref: t.Optional(t.String())
55
+ }),
56
+ response: t.Object({
57
+ success: t.Boolean(),
58
+ message: t.String()
59
+ })
60
+ }, async ({ data, conn }) => {
61
+ const project = requireProjectAccess(conn, data.projectId);
62
+ return await gitService.revertCommit(project.path, data.ref);
63
+ })
64
+
65
+ .http('git:clean', {
66
+ data: t.Object({
67
+ projectId: t.String()
68
+ }),
69
+ response: t.Object({ message: t.String() })
70
+ }, async ({ data, conn }) => {
71
+ const project = requireProjectAccess(conn, data.projectId);
72
+ const message = await gitService.cleanUntracked(project.path);
73
+ return { message };
74
+ })
75
+
76
+ .http('git:gc', {
77
+ data: t.Object({
78
+ projectId: t.String()
79
+ }),
80
+ response: t.Object({ message: t.String() })
81
+ }, async ({ data, conn }) => {
82
+ const project = requireProjectAccess(conn, data.projectId);
83
+ const message = await gitService.optimize(project.path);
84
+ return { message };
85
+ })
86
+
87
+ .http('git:npm-version', {
88
+ data: t.Object({
89
+ projectId: t.String(),
90
+ bump: t.Union([t.Literal('patch'), t.Literal('minor'), t.Literal('major')])
91
+ }),
92
+ response: t.Object({
93
+ success: t.Boolean(),
94
+ version: t.String(),
95
+ message: t.String()
96
+ })
97
+ }, async ({ data, conn }) => {
98
+ const project = requireProjectAccess(conn, data.projectId);
99
+ return await gitService.npmVersion(project.path, data.bump);
37
100
  });
@@ -40,6 +40,28 @@ export const remoteHandler = createRouter()
40
40
  data: t.Object({
41
41
  projectId: t.String(),
42
42
  remote: t.Optional(t.String()),
43
+ branch: t.Optional(t.String()),
44
+ rebase: t.Optional(t.Boolean())
45
+ }),
46
+ response: t.Object({
47
+ success: t.Boolean(),
48
+ message: t.String()
49
+ })
50
+ }, async ({ data, conn }) => {
51
+ const project = requireProjectAccess(conn, data.projectId);
52
+ return await gitService.pull(project.path, data.remote, data.branch, data.rebase);
53
+ })
54
+
55
+ .http('git:push-advanced', {
56
+ data: t.Object({
57
+ projectId: t.String(),
58
+ mode: t.Union([
59
+ t.Literal('with-tags'),
60
+ t.Literal('all-tags'),
61
+ t.Literal('force-lease'),
62
+ t.Literal('force')
63
+ ]),
64
+ remote: t.Optional(t.String()),
43
65
  branch: t.Optional(t.String())
44
66
  }),
45
67
  response: t.Object({
@@ -48,7 +70,20 @@ export const remoteHandler = createRouter()
48
70
  })
49
71
  }, async ({ data, conn }) => {
50
72
  const project = requireProjectAccess(conn, data.projectId);
51
- return await gitService.pull(project.path, data.remote, data.branch);
73
+ return await gitService.pushAdvanced(project.path, data.mode, data.remote, data.branch);
74
+ })
75
+
76
+ .http('git:fetch-all', {
77
+ data: t.Object({
78
+ projectId: t.String()
79
+ }),
80
+ response: t.Object({
81
+ message: t.String()
82
+ })
83
+ }, async ({ data, conn }) => {
84
+ const project = requireProjectAccess(conn, data.projectId);
85
+ const message = await gitService.fetchAll(project.path);
86
+ return { message };
52
87
  })
53
88
 
54
89
  .http('git:push', {
@@ -24,6 +24,7 @@ import { messagesRouter } from './messages';
24
24
  import { settingsRouter } from './settings';
25
25
  import { userRouter } from './user';
26
26
  import { filesRouter } from './files';
27
+ import { workspaceRouter } from './workspace';
27
28
  import { systemRouter } from './system';
28
29
  import { tunnelRouter } from './tunnel';
29
30
  import { gitRouter } from './git';
@@ -58,6 +59,7 @@ export const wsRouter = createRouter()
58
59
  .merge(settingsRouter)
59
60
  .merge(userRouter)
60
61
  .merge(filesRouter)
62
+ .merge(workspaceRouter)
61
63
  .merge(systemRouter)
62
64
  .merge(tunnelRouter)
63
65
 
@@ -9,7 +9,8 @@
9
9
  */
10
10
 
11
11
  import type { WSConnection } from '$shared/utils/ws-server';
12
- import { requireCurrentProjectAccess } from '../access';
12
+ import { ws } from '$backend/utils/ws';
13
+ import { requireCurrentProjectAccess, requireProjectAccess } from '../access';
13
14
  import { browserPreviewServiceManager } from '../../preview/index';
14
15
 
15
16
  type PreviewService = ReturnType<typeof browserPreviewServiceManager.getService>;
@@ -27,6 +28,24 @@ export function requireBrowserPreviewAccess(conn: WSConnection): BrowserPreviewC
27
28
  return { userId, projectId, previewService };
28
29
  }
29
30
 
31
+ /**
32
+ * Resolve preview access for an explicitly-supplied project, after verifying
33
+ * the caller is a member. Used by session-recovery reads (tab list / switch)
34
+ * that fire during a project switch: the connection's room context may not have
35
+ * caught up yet (the context-sync round-trip can resolve via timeout), so
36
+ * trusting it would recover the *previous* project's tabs. Passing the target
37
+ * projectId explicitly makes recovery deterministic.
38
+ */
39
+ export function requireBrowserPreviewAccessFor(
40
+ conn: WSConnection,
41
+ projectId: string
42
+ ): BrowserPreviewContext {
43
+ requireProjectAccess(conn, projectId); // throws if the caller isn't a member
44
+ const userId = ws.getUserId(conn);
45
+ const previewService = browserPreviewServiceManager.getService(projectId);
46
+ return { userId, projectId, previewService };
47
+ }
48
+
30
49
  /**
31
50
  * Resolve a tab in the caller's project. If `tabId` is omitted the active tab
32
51
  * is returned. Throws if the caller can't access the project, or if no tab
@@ -8,7 +8,7 @@ import { t } from 'elysia';
8
8
  import { createRouter } from '$shared/utils/ws-server';
9
9
  import { browserMcpControl } from '../../../preview/browser/browser-mcp-control';
10
10
  import { debug } from '$shared/utils/logger';
11
- import { requireBrowserPreviewAccess, requireBrowserTabAccess } from '../access';
11
+ import { requireBrowserPreviewAccess, requireBrowserPreviewAccessFor, requireBrowserTabAccess } from '../access';
12
12
 
13
13
  export const tabInfoPreviewHandler = createRouter()
14
14
  // Get single tab info
@@ -43,7 +43,10 @@ export const tabInfoPreviewHandler = createRouter()
43
43
 
44
44
  // Get all active tabs (for session recovery after browser refresh)
45
45
  .http('preview:browser-tabs-list', {
46
- data: t.Object({}),
46
+ data: t.Object({
47
+ // Explicit project target for switch-time recovery (see access helper).
48
+ projectId: t.Optional(t.String())
49
+ }),
47
50
  response: t.Object({
48
51
  tabs: t.Array(t.Object({
49
52
  tabId: t.String(),
@@ -59,8 +62,10 @@ export const tabInfoPreviewHandler = createRouter()
59
62
  activeTabId: t.Union([t.String(), t.Null()]),
60
63
  count: t.Number()
61
64
  })
62
- }, async ({ conn }) => {
63
- const { projectId, previewService } = requireBrowserPreviewAccess(conn);
65
+ }, async ({ data, conn }) => {
66
+ const { projectId, previewService } = data.projectId
67
+ ? requireBrowserPreviewAccessFor(conn, data.projectId)
68
+ : requireBrowserPreviewAccess(conn);
64
69
 
65
70
  const allTabsInfo = previewService.getAllTabsInfo();
66
71
  const activeTab = previewService.getActiveTab();
@@ -87,7 +92,9 @@ export const tabInfoPreviewHandler = createRouter()
87
92
  // Switch to a specific tab (for session recovery)
88
93
  .http('preview:browser-tab-switch', {
89
94
  data: t.Object({
90
- tabId: t.String()
95
+ tabId: t.String(),
96
+ // Explicit project target for switch-time recovery (see access helper).
97
+ projectId: t.Optional(t.String())
91
98
  }),
92
99
  response: t.Object({
93
100
  success: t.Boolean(),
@@ -96,7 +103,9 @@ export const tabInfoPreviewHandler = createRouter()
96
103
  })
97
104
  }, async ({ data, conn }) => {
98
105
  const { tabId } = data;
99
- const { projectId, previewService } = requireBrowserPreviewAccess(conn);
106
+ const { projectId, previewService } = data.projectId
107
+ ? requireBrowserPreviewAccessFor(conn, data.projectId)
108
+ : requireBrowserPreviewAccess(conn);
100
109
 
101
110
  const success = previewService.switchTab(tabId);
102
111
  if (!success) {
@@ -60,6 +60,9 @@ export const previewRouter = createRouter()
60
60
  .merge(mcpPreviewHandler)
61
61
  // Server-emitted events (for type safety)
62
62
  .emit('preview:browser-tab-opened', t.Object({
63
+ // projectId lets the frontend reject events that belong to a project it has
64
+ // since switched away from (prevents cross-project tab leaks).
65
+ projectId: t.String(),
63
66
  tabId: t.String(),
64
67
  url: t.String(),
65
68
  title: t.String(),
@@ -67,16 +70,19 @@ export const previewRouter = createRouter()
67
70
  timestamp: t.Number()
68
71
  }))
69
72
  .emit('preview:browser-tab-closed', t.Object({
73
+ projectId: t.String(),
70
74
  tabId: t.String(),
71
75
  newActiveTabId: t.Union([t.String(), t.Null()]),
72
76
  timestamp: t.Number()
73
77
  }))
74
78
  .emit('preview:browser-tab-switched', t.Object({
79
+ projectId: t.String(),
75
80
  previousTabId: t.String(),
76
81
  newTabId: t.String(),
77
82
  timestamp: t.Number()
78
83
  }))
79
84
  .emit('preview:browser-tab-navigated', t.Object({
85
+ projectId: t.String(),
80
86
  tabId: t.String(),
81
87
  url: t.String(),
82
88
  title: t.String(),
@@ -145,6 +151,7 @@ export const previewRouter = createRouter()
145
151
  source: t.Literal('mcp')
146
152
  }))
147
153
  .emit('preview:browser-viewport-changed', t.Object({
154
+ projectId: t.String(),
148
155
  tabId: t.String(),
149
156
  deviceSize: t.String(),
150
157
  rotation: t.String(),
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Workspace Router
3
+ *
4
+ * Per-project workspace state persistence (dock layout + dock view state).
5
+ *
6
+ * Structure:
7
+ * - state.ts: HTTP endpoints for get/save per-project workspace state
8
+ */
9
+
10
+ import { createRouter } from '$shared/utils/ws-server';
11
+ import { workspaceStateHandler } from './state';
12
+
13
+ export const workspaceRouter = createRouter()
14
+ .merge(workspaceStateHandler);
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Workspace State Handlers
3
+ *
4
+ * Persist per-user-per-project workspace state (dock layout/ratios/preset,
5
+ * git dock UI state, preview prefs, terminal active tab, and other dock view
6
+ * state). Single source of truth in DB so each project's workspace survives
7
+ * browser refresh and follows the user across devices.
8
+ *
9
+ * Mirrors the files:*-panel-state pattern.
10
+ */
11
+
12
+ import { t } from 'elysia';
13
+ import { createRouter } from '$shared/utils/ws-server';
14
+ import { projectQueries } from '../../database/queries/project-queries';
15
+ import { ws as wsServer } from '../../utils/ws';
16
+ import { requireProjectAccess } from '../access';
17
+
18
+ export const workspaceStateHandler = createRouter()
19
+ .http('workspace:get-state', {
20
+ data: t.Object({
21
+ projectId: t.String()
22
+ }),
23
+ response: t.Object({
24
+ state: t.Union([t.String(), t.Null()])
25
+ })
26
+ }, async ({ data, conn }) => {
27
+ requireProjectAccess(conn, data.projectId);
28
+ const userId = wsServer.getUserId(conn);
29
+ const state = projectQueries.getWorkspaceState(userId, data.projectId);
30
+ return { state };
31
+ })
32
+
33
+ .http('workspace:save-state', {
34
+ data: t.Object({
35
+ projectId: t.String(),
36
+ state: t.Union([t.String(), t.Null()])
37
+ }),
38
+ response: t.Object({ ok: t.Boolean() })
39
+ }, async ({ data, conn }) => {
40
+ requireProjectAccess(conn, data.projectId);
41
+ const userId = wsServer.getUserId(conn);
42
+ projectQueries.setWorkspaceState(userId, data.projectId, data.state);
43
+ return { ok: true };
44
+ });