-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsessionFsProvider.ts
More file actions
235 lines (214 loc) · 8.61 KB
/
sessionFsProvider.ts
File metadata and controls
235 lines (214 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
import type {
SessionFsHandler,
SessionFsError,
SessionFsStatResult,
SessionFsReaddirWithTypesEntry,
SessionFsSqliteQueryResult as GeneratedSqliteQueryResult,
SessionFsSqliteQueryType,
} from "./generated/rpc.js";
export type { SessionFsSqliteQueryType };
/**
* File metadata returned by {@link SessionFsProvider.stat}.
* Same shape as the generated {@link SessionFsStatResult} but without the
* `error` field, since providers signal errors by throwing.
*/
export type SessionFsFileInfo = Omit<SessionFsStatResult, "error">;
/**
* Result of a SQLite query execution via {@link SessionFsSqliteProvider.query}.
* Same shape as the generated {@link GeneratedSqliteQueryResult} but without the
* `error` field, since providers signal errors by throwing.
*/
export type SessionFsSqliteQueryResult = Omit<GeneratedSqliteQueryResult, "error">;
/**
* SQLite operations for the per-session database.
* Implementers provide query execution and existence checking.
*/
export interface SessionFsSqliteProvider {
/**
* Execute a SQLite query against the per-session database.
*
* @param queryType - How to execute: `"exec"` for DDL/multi-statement, `"query"` for SELECT, `"run"` for INSERT/UPDATE/DELETE.
* @param query - SQL query to execute.
* @param params - Optional named bind parameters.
*/
query(
queryType: SessionFsSqliteQueryType,
query: string,
params?: Record<string, string | number | null>
): Promise<SessionFsSqliteQueryResult | undefined>;
/**
* Check whether the per-session database already exists, without creating it.
*/
exists(): Promise<boolean>;
}
/**
* Interface for session filesystem providers. Implementers use idiomatic
* TypeScript patterns: throw on error, return values directly. Use
* {@link createSessionFsAdapter} to convert a provider into the
* {@link SessionFsHandler} expected by the SDK.
*
* Errors with a `code` property of `"ENOENT"` are mapped to the ENOENT
* error code; all others map to UNKNOWN.
*/
export interface SessionFsProvider {
/** Reads the full content of a file. Throw if the file does not exist. */
readFile(path: string): Promise<string>;
/** Writes content to a file, creating parent directories if needed. */
writeFile(path: string, content: string, mode?: number): Promise<void>;
/** Appends content to a file, creating parent directories if needed. */
appendFile(path: string, content: string, mode?: number): Promise<void>;
/** Checks whether a path exists. */
exists(path: string): Promise<boolean>;
/** Gets metadata about a file or directory. Throw if it does not exist. */
stat(path: string): Promise<SessionFsFileInfo>;
/** Creates a directory. If recursive is true, creates parents as needed. */
mkdir(path: string, recursive: boolean, mode?: number): Promise<void>;
/** Lists entry names in a directory. Throw if it does not exist. */
readdir(path: string): Promise<string[]>;
/** Lists entries with type info. Throw if the directory does not exist. */
readdirWithTypes(path: string): Promise<SessionFsReaddirWithTypesEntry[]>;
/** Removes a file or directory. If force is true, do not throw on ENOENT. */
rm(path: string, recursive: boolean, force: boolean): Promise<void>;
/** Renames/moves a file or directory. */
rename(src: string, dest: string): Promise<void>;
/** Per-session SQLite database operations. Optional — omit if the provider does not support SQLite. */
sqlite?: SessionFsSqliteProvider;
}
function normalizeSqliteParams(
params?: Record<string, string | number | null | undefined>
): Record<string, string | number | null> | undefined {
if (!params) {
return undefined;
}
const normalized: Record<string, string | number | null> = {};
for (const [key, value] of Object.entries(params)) {
if (value !== undefined) {
normalized[key] = value;
}
}
return normalized;
}
/**
* Wraps a {@link SessionFsProvider} into the {@link SessionFsHandler}
* interface expected by the SDK, converting thrown errors into
* {@link SessionFsError} results.
*/
export function createSessionFsAdapter(provider: SessionFsProvider): SessionFsHandler {
return {
readFile: async ({ path }) => {
try {
const content = await provider.readFile(path);
return { content };
} catch (err) {
return { content: "", error: toSessionFsError(err) };
}
},
writeFile: async ({ path, content, mode }) => {
try {
await provider.writeFile(path, content, mode);
return undefined;
} catch (err) {
return toSessionFsError(err);
}
},
appendFile: async ({ path, content, mode }) => {
try {
await provider.appendFile(path, content, mode);
return undefined;
} catch (err) {
return toSessionFsError(err);
}
},
exists: async ({ path }) => {
try {
return { exists: await provider.exists(path) };
} catch {
return { exists: false };
}
},
stat: async ({ path }) => {
try {
return await provider.stat(path);
} catch (err) {
return {
isFile: false,
isDirectory: false,
size: 0,
mtime: new Date().toISOString(),
birthtime: new Date().toISOString(),
error: toSessionFsError(err),
};
}
},
mkdir: async ({ path, recursive, mode }) => {
try {
await provider.mkdir(path, recursive ?? false, mode);
return undefined;
} catch (err) {
return toSessionFsError(err);
}
},
readdir: async ({ path }) => {
try {
const entries = await provider.readdir(path);
return { entries };
} catch (err) {
return { entries: [], error: toSessionFsError(err) };
}
},
readdirWithTypes: async ({ path }) => {
try {
const entries = await provider.readdirWithTypes(path);
return { entries };
} catch (err) {
return { entries: [], error: toSessionFsError(err) };
}
},
rm: async ({ path, recursive, force }) => {
try {
await provider.rm(path, recursive ?? false, force ?? false);
return undefined;
} catch (err) {
return toSessionFsError(err);
}
},
rename: async ({ src, dest }) => {
try {
await provider.rename(src, dest);
return undefined;
} catch (err) {
return toSessionFsError(err);
}
},
// Unlike the FS methods above, SQLite methods let errors propagate to the JSON-RPC layer
// rather than catching and mapping via toSessionFsError. The FS error mapping is specifically
// for translating Node.js errno codes (e.g., ENOENT) into SessionFsError, which isn't
// meaningful for SQL errors. Letting exceptions propagate preserves the original error
// message in the JSON-RPC error response.
sqliteQuery: async ({ queryType, query, params: bindParams }) => {
if (!provider.sqlite) {
throw new Error("SQLite is not supported by this provider");
}
const result = await provider.sqlite.query(
queryType,
query,
normalizeSqliteParams(bindParams)
);
return result ?? { rows: [], columns: [], rowsAffected: 0 };
},
sqliteExists: async () => {
if (!provider.sqlite) {
throw new Error("SQLite is not supported by this provider");
}
return { exists: await provider.sqlite.exists() };
},
};
}
function toSessionFsError(err: unknown): SessionFsError {
const e = err as NodeJS.ErrnoException;
const code = e.code === "ENOENT" ? "ENOENT" : "UNKNOWN";
return { code, message: e.message ?? String(err) };
}