brain-memory 0.1.0-beta.2 → 0.1.0-beta.4

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,308 @@
1
+ /**
2
+ * Brain Memory — OneDrive Sync Provider
3
+ *
4
+ * Microsoft Graph API integration using AppFolder special folder.
5
+ * Path-based access via approot:/{path}: — simpler than Google Drive.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+ const { SyncProvider } = require('../provider');
10
+
11
+ const GRAPH_BASE = 'https://graph.microsoft.com/v1.0/me/drive/special/approot';
12
+
13
+ class OneDriveProvider extends SyncProvider {
14
+ constructor(config) {
15
+ super(config);
16
+ }
17
+
18
+ /**
19
+ * Compute content hash using SHA-1 (matches OneDrive's sha1Hash).
20
+ *
21
+ * @param {Buffer} buffer - File content
22
+ * @returns {string} Uppercase hex-encoded SHA-1 hash
23
+ */
24
+ computeContentHash(buffer) {
25
+ return crypto.createHash('sha1').update(buffer).digest('hex').toUpperCase();
26
+ }
27
+
28
+ async listFiles(cursor) {
29
+ if (cursor) {
30
+ return this._listDelta(cursor);
31
+ }
32
+ return this._listInitialDelta();
33
+ }
34
+
35
+ async _listInitialDelta() {
36
+ const allFiles = [];
37
+ let url = `${GRAPH_BASE}:/delta?$select=name,size,lastModifiedDateTime,file,parentReference,deleted`;
38
+
39
+ let deltaLink = null;
40
+
41
+ while (url) {
42
+ const response = await fetch(url, {
43
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
44
+ });
45
+
46
+ if (!response.ok) {
47
+ const text = await response.text();
48
+ throw new Error(`OneDrive delta failed (${response.status}): ${text}`);
49
+ }
50
+
51
+ const data = await response.json();
52
+
53
+ for (const item of data.value || []) {
54
+ if (item.deleted || !item.file) continue;
55
+
56
+ const filePath = this._extractPath(item);
57
+ if (!filePath) continue;
58
+
59
+ allFiles.push({
60
+ path: filePath,
61
+ rev: item.eTag || item.id,
62
+ hash: item.file?.hashes?.sha1Hash || '',
63
+ modified: item.lastModifiedDateTime,
64
+ size: item.size || 0,
65
+ });
66
+ }
67
+
68
+ url = data['@odata.nextLink'] || null;
69
+ if (data['@odata.deltaLink']) {
70
+ deltaLink = data['@odata.deltaLink'];
71
+ }
72
+ }
73
+
74
+ return {
75
+ files: allFiles,
76
+ cursor: deltaLink,
77
+ hasMore: false,
78
+ };
79
+ }
80
+
81
+ async _listDelta(deltaLink) {
82
+ const files = [];
83
+ let url = deltaLink;
84
+ let newDeltaLink = null;
85
+
86
+ while (url) {
87
+ const response = await fetch(url, {
88
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
89
+ });
90
+
91
+ if (!response.ok) {
92
+ const text = await response.text();
93
+ throw new Error(`OneDrive delta failed (${response.status}): ${text}`);
94
+ }
95
+
96
+ const data = await response.json();
97
+
98
+ for (const item of data.value || []) {
99
+ const filePath = this._extractPath(item);
100
+ if (!filePath) continue;
101
+
102
+ if (item.deleted) {
103
+ files.push({
104
+ path: filePath,
105
+ rev: '',
106
+ hash: '',
107
+ modified: '',
108
+ size: 0,
109
+ deleted: true,
110
+ });
111
+ } else if (item.file) {
112
+ files.push({
113
+ path: filePath,
114
+ rev: item.eTag || item.id,
115
+ hash: item.file?.hashes?.sha1Hash || '',
116
+ modified: item.lastModifiedDateTime,
117
+ size: item.size || 0,
118
+ });
119
+ }
120
+ }
121
+
122
+ url = data['@odata.nextLink'] || null;
123
+ if (data['@odata.deltaLink']) {
124
+ newDeltaLink = data['@odata.deltaLink'];
125
+ }
126
+ }
127
+
128
+ return {
129
+ files,
130
+ cursor: newDeltaLink || deltaLink,
131
+ hasMore: false,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Extract relative path from a OneDrive item's parentReference.
137
+ *
138
+ * @param {Object} item - OneDrive drive item
139
+ * @returns {string|null} Relative path or null
140
+ */
141
+ _extractPath(item) {
142
+ if (!item.name) return null;
143
+
144
+ const parentPath = item.parentReference?.path || '';
145
+ // parentPath looks like: /drive/special/approot:/subfolder
146
+ // or just /drive/special/approot for root items
147
+ const appRootMarker = '/approot:';
148
+ const markerIdx = parentPath.indexOf(appRootMarker);
149
+
150
+ let relativePart = '';
151
+ if (markerIdx !== -1) {
152
+ relativePart = parentPath.substring(markerIdx + appRootMarker.length);
153
+ if (relativePart.startsWith('/')) relativePart = relativePart.substring(1);
154
+ }
155
+
156
+ return relativePart ? `${relativePart}/${item.name}` : item.name;
157
+ }
158
+
159
+ async downloadFile(remotePath) {
160
+ const response = await fetch(`${GRAPH_BASE}:/${remotePath}:/content`, {
161
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
162
+ redirect: 'follow',
163
+ });
164
+
165
+ if (!response.ok) {
166
+ const text = await response.text();
167
+ throw new Error(`OneDrive download failed (${response.status}): ${text}`);
168
+ }
169
+
170
+ const buffer = Buffer.from(await response.arrayBuffer());
171
+
172
+ // Get metadata for rev/hash
173
+ const meta = await this.getFileMetadata(remotePath);
174
+
175
+ return {
176
+ content: buffer,
177
+ rev: meta?.rev || '',
178
+ hash: meta?.hash || this.computeContentHash(buffer),
179
+ };
180
+ }
181
+
182
+ async uploadFile(remotePath, content, options = {}) {
183
+ const { rev } = options;
184
+
185
+ const headers = {
186
+ 'Authorization': `Bearer ${this.accessToken}`,
187
+ 'Content-Type': 'application/octet-stream',
188
+ };
189
+
190
+ // Use eTag for optimistic concurrency
191
+ if (rev) {
192
+ headers['If-Match'] = rev;
193
+ }
194
+
195
+ const response = await fetch(`${GRAPH_BASE}:/${remotePath}:/content`, {
196
+ method: 'PUT',
197
+ headers,
198
+ body: content,
199
+ });
200
+
201
+ if (response.status === 412) {
202
+ const err = new Error('Conflict: file was modified remotely');
203
+ err.code = 'CONFLICT';
204
+ throw err;
205
+ }
206
+
207
+ if (!response.ok) {
208
+ const text = await response.text();
209
+ throw new Error(`OneDrive upload failed (${response.status}): ${text}`);
210
+ }
211
+
212
+ const data = await response.json();
213
+ return {
214
+ rev: data.eTag || data.id,
215
+ hash: data.file?.hashes?.sha1Hash || '',
216
+ };
217
+ }
218
+
219
+ async deleteFile(remotePath) {
220
+ const response = await fetch(`${GRAPH_BASE}:/${remotePath}:`, {
221
+ method: 'DELETE',
222
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
223
+ });
224
+
225
+ if (!response.ok && response.status !== 404) {
226
+ const text = await response.text();
227
+ throw new Error(`OneDrive delete failed (${response.status}): ${text}`);
228
+ }
229
+
230
+ return { success: true };
231
+ }
232
+
233
+ async getFileMetadata(remotePath) {
234
+ const params = new URLSearchParams({
235
+ $select: 'id,eTag,size,lastModifiedDateTime,file',
236
+ });
237
+
238
+ const response = await fetch(`${GRAPH_BASE}:/${remotePath}:?${params}`, {
239
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
240
+ });
241
+
242
+ if (!response.ok) {
243
+ if (response.status === 404) return null;
244
+ const text = await response.text();
245
+ throw new Error(`OneDrive metadata failed (${response.status}): ${text}`);
246
+ }
247
+
248
+ const data = await response.json();
249
+ return {
250
+ rev: data.eTag || data.id,
251
+ hash: data.file?.hashes?.sha1Hash || '',
252
+ modified: data.lastModifiedDateTime,
253
+ size: data.size || 0,
254
+ };
255
+ }
256
+
257
+ async createFolder(remotePath) {
258
+ const parts = remotePath.split('/');
259
+
260
+ // OneDrive auto-creates intermediate folders on upload,
261
+ // but we create explicitly for completeness
262
+ let currentPath = '';
263
+ for (const part of parts) {
264
+ const parentUrl = currentPath
265
+ ? `${GRAPH_BASE}:/${currentPath}:/children`
266
+ : `${GRAPH_BASE}/children`;
267
+
268
+ const response = await fetch(parentUrl, {
269
+ method: 'POST',
270
+ headers: {
271
+ 'Authorization': `Bearer ${this.accessToken}`,
272
+ 'Content-Type': 'application/json',
273
+ },
274
+ body: JSON.stringify({
275
+ name: part,
276
+ folder: {},
277
+ '@microsoft.graph.conflictBehavior': 'fail',
278
+ }),
279
+ });
280
+
281
+ // 409 = folder already exists, which is fine
282
+ if (!response.ok && response.status !== 409) {
283
+ const text = await response.text();
284
+ throw new Error(`OneDrive folder creation failed (${response.status}): ${text}`);
285
+ }
286
+
287
+ currentPath = currentPath ? `${currentPath}/${part}` : part;
288
+ }
289
+ }
290
+
291
+ async testConnection() {
292
+ const response = await fetch('https://graph.microsoft.com/v1.0/me', {
293
+ headers: { 'Authorization': `Bearer ${this.accessToken}` },
294
+ });
295
+
296
+ if (!response.ok) {
297
+ return { ok: false, account: null };
298
+ }
299
+
300
+ const data = await response.json();
301
+ return {
302
+ ok: true,
303
+ account: data.userPrincipalName || data.displayName || 'Unknown',
304
+ };
305
+ }
306
+ }
307
+
308
+ module.exports = { OneDriveProvider };