@arke-institute/sdk 2.0.0 → 2.2.0
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/README.md +108 -4
- package/dist/{index-BrXke2kI.d.ts → crypto-7c990p-j.d.ts} +200 -19
- package/dist/{index-FHcLPBSV.d.cts → crypto-El5Z3bNI.d.cts} +200 -19
- package/dist/generated/index.d.cts +680 -76
- package/dist/generated/index.d.ts +680 -76
- package/dist/index.cjs +638 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +636 -11
- package/dist/index.js.map +1 -1
- package/dist/operations/index.cjs +774 -10
- package/dist/operations/index.cjs.map +1 -1
- package/dist/operations/index.d.cts +171 -1
- package/dist/operations/index.d.ts +171 -1
- package/dist/operations/index.js +755 -9
- package/dist/operations/index.js.map +1 -1
- package/openapi/spec.json +9031 -0
- package/openapi/version.json +7 -0
- package/package.json +12 -4
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/operations/index.ts
|
|
@@ -22,10 +32,739 @@ var operations_exports = {};
|
|
|
22
32
|
__export(operations_exports, {
|
|
23
33
|
BatchOperations: () => BatchOperations,
|
|
24
34
|
CryptoOperations: () => CryptoOperations,
|
|
25
|
-
FolderOperations: () => FolderOperations
|
|
35
|
+
FolderOperations: () => FolderOperations,
|
|
36
|
+
buildUploadTree: () => buildUploadTree,
|
|
37
|
+
computeCid: () => computeCid,
|
|
38
|
+
getMimeType: () => getMimeType,
|
|
39
|
+
scanDirectory: () => scanDirectory,
|
|
40
|
+
scanFileList: () => scanFileList,
|
|
41
|
+
scanFileSystemEntries: () => scanFileSystemEntries,
|
|
42
|
+
uploadTree: () => uploadTree,
|
|
43
|
+
verifyCid: () => verifyCid
|
|
26
44
|
});
|
|
27
45
|
module.exports = __toCommonJS(operations_exports);
|
|
28
46
|
|
|
47
|
+
// src/operations/upload/cid.ts
|
|
48
|
+
var import_cid = require("multiformats/cid");
|
|
49
|
+
var import_sha2 = require("multiformats/hashes/sha2");
|
|
50
|
+
var raw = __toESM(require("multiformats/codecs/raw"), 1);
|
|
51
|
+
async function computeCid(data) {
|
|
52
|
+
let bytes;
|
|
53
|
+
if (data instanceof Blob) {
|
|
54
|
+
const buffer = await data.arrayBuffer();
|
|
55
|
+
bytes = new Uint8Array(buffer);
|
|
56
|
+
} else if (data instanceof ArrayBuffer) {
|
|
57
|
+
bytes = new Uint8Array(data);
|
|
58
|
+
} else {
|
|
59
|
+
bytes = data;
|
|
60
|
+
}
|
|
61
|
+
const hash = await import_sha2.sha256.digest(bytes);
|
|
62
|
+
const cid = import_cid.CID.create(1, raw.code, hash);
|
|
63
|
+
return cid.toString();
|
|
64
|
+
}
|
|
65
|
+
async function verifyCid(data, expectedCid) {
|
|
66
|
+
const computed = await computeCid(data);
|
|
67
|
+
return computed === expectedCid;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/operations/upload/engine.ts
|
|
71
|
+
var PHASE_COUNT = 4;
|
|
72
|
+
var PHASE_INDEX = {
|
|
73
|
+
"computing-cids": 0,
|
|
74
|
+
"creating": 1,
|
|
75
|
+
"backlinking": 2,
|
|
76
|
+
"uploading": 3,
|
|
77
|
+
"complete": 4,
|
|
78
|
+
"error": -1
|
|
79
|
+
};
|
|
80
|
+
async function parallelLimit(items, concurrency, fn) {
|
|
81
|
+
const results = [];
|
|
82
|
+
let index = 0;
|
|
83
|
+
async function worker() {
|
|
84
|
+
while (index < items.length) {
|
|
85
|
+
const currentIndex = index++;
|
|
86
|
+
const item = items[currentIndex];
|
|
87
|
+
results[currentIndex] = await fn(item, currentIndex);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
|
|
91
|
+
await Promise.all(workers);
|
|
92
|
+
return results;
|
|
93
|
+
}
|
|
94
|
+
var TARGET_BYTES_IN_FLIGHT = 200 * 1024 * 1024;
|
|
95
|
+
var BytePool = class {
|
|
96
|
+
constructor(targetBytes = TARGET_BYTES_IN_FLIGHT) {
|
|
97
|
+
this.targetBytes = targetBytes;
|
|
98
|
+
this.bytesInFlight = 0;
|
|
99
|
+
this.waitQueue = [];
|
|
100
|
+
}
|
|
101
|
+
async run(size, fn) {
|
|
102
|
+
while (this.bytesInFlight > 0 && this.bytesInFlight + size > this.targetBytes) {
|
|
103
|
+
await new Promise((resolve) => this.waitQueue.push(resolve));
|
|
104
|
+
}
|
|
105
|
+
this.bytesInFlight += size;
|
|
106
|
+
try {
|
|
107
|
+
return await fn();
|
|
108
|
+
} finally {
|
|
109
|
+
this.bytesInFlight -= size;
|
|
110
|
+
const next = this.waitQueue.shift();
|
|
111
|
+
if (next) next();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
function getParentPath(relativePath) {
|
|
116
|
+
const lastSlash = relativePath.lastIndexOf("/");
|
|
117
|
+
if (lastSlash === -1) return null;
|
|
118
|
+
return relativePath.slice(0, lastSlash);
|
|
119
|
+
}
|
|
120
|
+
function groupFoldersByDepth(folders) {
|
|
121
|
+
const byDepth = /* @__PURE__ */ new Map();
|
|
122
|
+
for (const folder of folders) {
|
|
123
|
+
const depth = folder.relativePath.split("/").length - 1;
|
|
124
|
+
if (!byDepth.has(depth)) byDepth.set(depth, []);
|
|
125
|
+
byDepth.get(depth).push(folder);
|
|
126
|
+
}
|
|
127
|
+
return byDepth;
|
|
128
|
+
}
|
|
129
|
+
async function uploadTree(client, tree, options) {
|
|
130
|
+
const { target, onProgress, concurrency = 10, continueOnError = false, note } = options;
|
|
131
|
+
const errors = [];
|
|
132
|
+
const createdFolders = [];
|
|
133
|
+
const createdFiles = [];
|
|
134
|
+
const foldersByPath = /* @__PURE__ */ new Map();
|
|
135
|
+
const totalEntities = tree.files.length + tree.folders.length;
|
|
136
|
+
const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);
|
|
137
|
+
let completedEntities = 0;
|
|
138
|
+
let bytesUploaded = 0;
|
|
139
|
+
const reportProgress = (progress) => {
|
|
140
|
+
if (onProgress) {
|
|
141
|
+
const phase = progress.phase || "computing-cids";
|
|
142
|
+
const phaseIndex = PHASE_INDEX[phase] ?? -1;
|
|
143
|
+
let phasePercent = 0;
|
|
144
|
+
if (phase === "computing-cids") {
|
|
145
|
+
const done = progress.completedEntities ?? completedEntities;
|
|
146
|
+
phasePercent = tree.files.length > 0 ? Math.round(done / tree.files.length * 100) : 100;
|
|
147
|
+
} else if (phase === "creating") {
|
|
148
|
+
const done = progress.completedEntities ?? completedEntities;
|
|
149
|
+
phasePercent = totalEntities > 0 ? Math.round(done / totalEntities * 100) : 100;
|
|
150
|
+
} else if (phase === "backlinking") {
|
|
151
|
+
const done = progress.completedParents ?? 0;
|
|
152
|
+
const total = progress.totalParents ?? 0;
|
|
153
|
+
phasePercent = total > 0 ? Math.round(done / total * 100) : 100;
|
|
154
|
+
} else if (phase === "uploading") {
|
|
155
|
+
const done = progress.bytesUploaded ?? bytesUploaded;
|
|
156
|
+
phasePercent = totalBytes > 0 ? Math.round(done / totalBytes * 100) : 100;
|
|
157
|
+
} else if (phase === "complete") {
|
|
158
|
+
phasePercent = 100;
|
|
159
|
+
}
|
|
160
|
+
onProgress({
|
|
161
|
+
phase,
|
|
162
|
+
phaseIndex,
|
|
163
|
+
phaseCount: PHASE_COUNT,
|
|
164
|
+
phasePercent,
|
|
165
|
+
totalEntities,
|
|
166
|
+
completedEntities,
|
|
167
|
+
totalParents: 0,
|
|
168
|
+
completedParents: 0,
|
|
169
|
+
totalBytes,
|
|
170
|
+
bytesUploaded,
|
|
171
|
+
...progress
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
try {
|
|
176
|
+
let collectionId;
|
|
177
|
+
let collectionCid;
|
|
178
|
+
let collectionCreated = false;
|
|
179
|
+
if (target.createCollection) {
|
|
180
|
+
const collectionBody = {
|
|
181
|
+
label: target.createCollection.label,
|
|
182
|
+
description: target.createCollection.description,
|
|
183
|
+
roles: target.createCollection.roles,
|
|
184
|
+
note
|
|
185
|
+
};
|
|
186
|
+
const { data, error } = await client.api.POST("/collections", {
|
|
187
|
+
body: collectionBody
|
|
188
|
+
});
|
|
189
|
+
if (error || !data) {
|
|
190
|
+
throw new Error(`Failed to create collection: ${JSON.stringify(error)}`);
|
|
191
|
+
}
|
|
192
|
+
collectionId = data.id;
|
|
193
|
+
collectionCid = data.cid;
|
|
194
|
+
collectionCreated = true;
|
|
195
|
+
} else if (target.collectionId) {
|
|
196
|
+
collectionId = target.collectionId;
|
|
197
|
+
const { data, error } = await client.api.GET("/collections/{id}", {
|
|
198
|
+
params: { path: { id: collectionId } }
|
|
199
|
+
});
|
|
200
|
+
if (error || !data) {
|
|
201
|
+
throw new Error(`Failed to fetch collection: ${JSON.stringify(error)}`);
|
|
202
|
+
}
|
|
203
|
+
collectionCid = data.cid;
|
|
204
|
+
} else {
|
|
205
|
+
throw new Error("Must provide either collectionId or createCollection in target");
|
|
206
|
+
}
|
|
207
|
+
const rootParentId = target.parentId ?? collectionId;
|
|
208
|
+
reportProgress({ phase: "computing-cids", completedEntities: 0 });
|
|
209
|
+
const preparedFiles = [];
|
|
210
|
+
let cidProgress = 0;
|
|
211
|
+
await parallelLimit(tree.files, Math.max(concurrency, 20), async (file) => {
|
|
212
|
+
try {
|
|
213
|
+
const data = await file.getData();
|
|
214
|
+
const cid = await computeCid(data);
|
|
215
|
+
preparedFiles.push({ ...file, cid });
|
|
216
|
+
cidProgress++;
|
|
217
|
+
reportProgress({
|
|
218
|
+
phase: "computing-cids",
|
|
219
|
+
completedEntities: cidProgress,
|
|
220
|
+
currentItem: file.relativePath
|
|
221
|
+
});
|
|
222
|
+
} catch (err) {
|
|
223
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
224
|
+
if (continueOnError) {
|
|
225
|
+
errors.push({ path: file.relativePath, error: `CID computation failed: ${errorMsg}` });
|
|
226
|
+
} else {
|
|
227
|
+
throw new Error(`Failed to compute CID for ${file.relativePath}: ${errorMsg}`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
reportProgress({ phase: "creating", completedEntities: 0 });
|
|
232
|
+
const foldersByDepth = groupFoldersByDepth(tree.folders);
|
|
233
|
+
const sortedDepths = [...foldersByDepth.keys()].sort((a, b) => a - b);
|
|
234
|
+
for (const depth of sortedDepths) {
|
|
235
|
+
const foldersAtDepth = foldersByDepth.get(depth);
|
|
236
|
+
await Promise.all(
|
|
237
|
+
foldersAtDepth.map(async (folder) => {
|
|
238
|
+
try {
|
|
239
|
+
const parentPath = getParentPath(folder.relativePath);
|
|
240
|
+
const parentId = parentPath ? foldersByPath.get(parentPath).id : rootParentId;
|
|
241
|
+
const parentType = parentPath ? "folder" : parentId === collectionId ? "collection" : "folder";
|
|
242
|
+
const folderBody = {
|
|
243
|
+
label: folder.name,
|
|
244
|
+
collection: collectionId,
|
|
245
|
+
note,
|
|
246
|
+
relationships: [{ predicate: "in", peer: parentId, peer_type: parentType }]
|
|
247
|
+
};
|
|
248
|
+
const { data, error } = await client.api.POST("/folders", {
|
|
249
|
+
body: folderBody
|
|
250
|
+
});
|
|
251
|
+
if (error || !data) {
|
|
252
|
+
throw new Error(JSON.stringify(error));
|
|
253
|
+
}
|
|
254
|
+
foldersByPath.set(folder.relativePath, { id: data.id, cid: data.cid });
|
|
255
|
+
createdFolders.push({
|
|
256
|
+
name: folder.name,
|
|
257
|
+
relativePath: folder.relativePath,
|
|
258
|
+
id: data.id,
|
|
259
|
+
entityCid: data.cid
|
|
260
|
+
});
|
|
261
|
+
completedEntities++;
|
|
262
|
+
reportProgress({
|
|
263
|
+
phase: "creating",
|
|
264
|
+
completedEntities,
|
|
265
|
+
currentItem: folder.relativePath
|
|
266
|
+
});
|
|
267
|
+
} catch (err) {
|
|
268
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
269
|
+
if (continueOnError) {
|
|
270
|
+
errors.push({ path: folder.relativePath, error: `Folder creation failed: ${errorMsg}` });
|
|
271
|
+
completedEntities++;
|
|
272
|
+
} else {
|
|
273
|
+
throw new Error(`Failed to create folder ${folder.relativePath}: ${errorMsg}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
})
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
const FILE_CREATION_CONCURRENCY = 50;
|
|
280
|
+
await parallelLimit(preparedFiles, FILE_CREATION_CONCURRENCY, async (file) => {
|
|
281
|
+
try {
|
|
282
|
+
const parentPath = getParentPath(file.relativePath);
|
|
283
|
+
const parentId = parentPath ? foldersByPath.get(parentPath).id : rootParentId;
|
|
284
|
+
const parentType = parentPath ? "folder" : parentId === collectionId ? "collection" : "folder";
|
|
285
|
+
const fileBody = {
|
|
286
|
+
key: file.cid,
|
|
287
|
+
filename: file.name,
|
|
288
|
+
content_type: file.mimeType,
|
|
289
|
+
size: file.size,
|
|
290
|
+
cid: file.cid,
|
|
291
|
+
collection: collectionId,
|
|
292
|
+
relationships: [{ predicate: "in", peer: parentId, peer_type: parentType }]
|
|
293
|
+
};
|
|
294
|
+
const { data, error } = await client.api.POST("/files", {
|
|
295
|
+
body: fileBody
|
|
296
|
+
});
|
|
297
|
+
if (error || !data) {
|
|
298
|
+
throw new Error(`Entity creation failed: ${JSON.stringify(error)}`);
|
|
299
|
+
}
|
|
300
|
+
createdFiles.push({
|
|
301
|
+
...file,
|
|
302
|
+
id: data.id,
|
|
303
|
+
entityCid: data.cid,
|
|
304
|
+
uploadUrl: data.upload_url,
|
|
305
|
+
uploadExpiresAt: data.upload_expires_at
|
|
306
|
+
});
|
|
307
|
+
completedEntities++;
|
|
308
|
+
reportProgress({
|
|
309
|
+
phase: "creating",
|
|
310
|
+
completedEntities,
|
|
311
|
+
currentItem: file.relativePath
|
|
312
|
+
});
|
|
313
|
+
} catch (err) {
|
|
314
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
315
|
+
if (continueOnError) {
|
|
316
|
+
errors.push({ path: file.relativePath, error: errorMsg });
|
|
317
|
+
completedEntities++;
|
|
318
|
+
} else {
|
|
319
|
+
throw new Error(`Failed to create file ${file.relativePath}: ${errorMsg}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
const childrenByParent = /* @__PURE__ */ new Map();
|
|
324
|
+
for (const folder of createdFolders) {
|
|
325
|
+
const parentPath = getParentPath(folder.relativePath);
|
|
326
|
+
const parentId = parentPath ? foldersByPath.get(parentPath).id : rootParentId;
|
|
327
|
+
if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);
|
|
328
|
+
childrenByParent.get(parentId).push({ id: folder.id, type: "folder" });
|
|
329
|
+
}
|
|
330
|
+
for (const file of createdFiles) {
|
|
331
|
+
const parentPath = getParentPath(file.relativePath);
|
|
332
|
+
const parentId = parentPath ? foldersByPath.get(parentPath).id : rootParentId;
|
|
333
|
+
if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []);
|
|
334
|
+
childrenByParent.get(parentId).push({ id: file.id, type: "file" });
|
|
335
|
+
}
|
|
336
|
+
const totalParents = childrenByParent.size;
|
|
337
|
+
let completedParents = 0;
|
|
338
|
+
reportProgress({ phase: "backlinking", totalParents, completedParents: 0 });
|
|
339
|
+
const parentEntries = [...childrenByParent.entries()];
|
|
340
|
+
await parallelLimit(parentEntries, concurrency, async ([parentId, children]) => {
|
|
341
|
+
try {
|
|
342
|
+
const isCollection = parentId === collectionId;
|
|
343
|
+
const relationshipsAdd = children.map((child) => ({
|
|
344
|
+
predicate: "contains",
|
|
345
|
+
peer: child.id,
|
|
346
|
+
peer_type: child.type
|
|
347
|
+
}));
|
|
348
|
+
if (isCollection) {
|
|
349
|
+
const { data: collData, error: getError } = await client.api.GET("/collections/{id}", {
|
|
350
|
+
params: { path: { id: parentId } }
|
|
351
|
+
});
|
|
352
|
+
if (getError || !collData) {
|
|
353
|
+
throw new Error(`Failed to fetch collection: ${JSON.stringify(getError)}`);
|
|
354
|
+
}
|
|
355
|
+
const updateBody = {
|
|
356
|
+
expect_tip: collData.cid,
|
|
357
|
+
relationships_add: relationshipsAdd,
|
|
358
|
+
note: note ? `${note} (backlink)` : "Upload backlink"
|
|
359
|
+
};
|
|
360
|
+
const { error } = await client.api.PUT("/collections/{id}", {
|
|
361
|
+
params: { path: { id: parentId } },
|
|
362
|
+
body: updateBody
|
|
363
|
+
});
|
|
364
|
+
if (error) {
|
|
365
|
+
throw new Error(JSON.stringify(error));
|
|
366
|
+
}
|
|
367
|
+
} else {
|
|
368
|
+
const { data: folderData, error: getError } = await client.api.GET("/folders/{id}", {
|
|
369
|
+
params: { path: { id: parentId } }
|
|
370
|
+
});
|
|
371
|
+
if (getError || !folderData) {
|
|
372
|
+
throw new Error(`Failed to fetch folder: ${JSON.stringify(getError)}`);
|
|
373
|
+
}
|
|
374
|
+
const updateBody = {
|
|
375
|
+
expect_tip: folderData.cid,
|
|
376
|
+
relationships_add: relationshipsAdd,
|
|
377
|
+
note: note ? `${note} (backlink)` : "Upload backlink"
|
|
378
|
+
};
|
|
379
|
+
const { error } = await client.api.PUT("/folders/{id}", {
|
|
380
|
+
params: { path: { id: parentId } },
|
|
381
|
+
body: updateBody
|
|
382
|
+
});
|
|
383
|
+
if (error) {
|
|
384
|
+
throw new Error(JSON.stringify(error));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
completedParents++;
|
|
388
|
+
reportProgress({
|
|
389
|
+
phase: "backlinking",
|
|
390
|
+
totalParents,
|
|
391
|
+
completedParents,
|
|
392
|
+
currentItem: `parent:${parentId}`
|
|
393
|
+
});
|
|
394
|
+
} catch (err) {
|
|
395
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
396
|
+
if (continueOnError) {
|
|
397
|
+
errors.push({ path: `parent:${parentId}`, error: `Backlink failed: ${errorMsg}` });
|
|
398
|
+
completedParents++;
|
|
399
|
+
} else {
|
|
400
|
+
throw new Error(`Failed to backlink parent ${parentId}: ${errorMsg}`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
reportProgress({ phase: "uploading", bytesUploaded: 0 });
|
|
405
|
+
const pool = new BytePool();
|
|
406
|
+
await Promise.all(
|
|
407
|
+
createdFiles.map(async (file) => {
|
|
408
|
+
await pool.run(file.size, async () => {
|
|
409
|
+
try {
|
|
410
|
+
const fileData = await file.getData();
|
|
411
|
+
let body;
|
|
412
|
+
if (fileData instanceof Blob) {
|
|
413
|
+
body = fileData;
|
|
414
|
+
} else if (fileData instanceof Uint8Array) {
|
|
415
|
+
const arrayBuffer = new ArrayBuffer(fileData.byteLength);
|
|
416
|
+
new Uint8Array(arrayBuffer).set(fileData);
|
|
417
|
+
body = new Blob([arrayBuffer], { type: file.mimeType });
|
|
418
|
+
} else {
|
|
419
|
+
body = new Blob([fileData], { type: file.mimeType });
|
|
420
|
+
}
|
|
421
|
+
const uploadResponse = await fetch(file.uploadUrl, {
|
|
422
|
+
method: "PUT",
|
|
423
|
+
body,
|
|
424
|
+
headers: { "Content-Type": file.mimeType }
|
|
425
|
+
});
|
|
426
|
+
if (!uploadResponse.ok) {
|
|
427
|
+
throw new Error(`S3 upload failed with status ${uploadResponse.status}`);
|
|
428
|
+
}
|
|
429
|
+
let confirmTip = file.entityCid;
|
|
430
|
+
let confirmAttempts = 0;
|
|
431
|
+
const MAX_CONFIRM_ATTEMPTS = 3;
|
|
432
|
+
while (confirmAttempts < MAX_CONFIRM_ATTEMPTS) {
|
|
433
|
+
confirmAttempts++;
|
|
434
|
+
const { error: confirmError } = await client.api.POST("/files/{id}/confirm-upload", {
|
|
435
|
+
params: { path: { id: file.id } },
|
|
436
|
+
body: {
|
|
437
|
+
expect_tip: confirmTip,
|
|
438
|
+
note: note ? `${note} (confirmed)` : "Upload confirmed"
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
if (!confirmError) {
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
const errorStr = JSON.stringify(confirmError);
|
|
445
|
+
if (errorStr.includes("409") || errorStr.includes("CAS") || errorStr.includes("conflict")) {
|
|
446
|
+
const { data: currentFile, error: fetchError } = await client.api.GET("/files/{id}", {
|
|
447
|
+
params: { path: { id: file.id } }
|
|
448
|
+
});
|
|
449
|
+
if (fetchError || !currentFile) {
|
|
450
|
+
throw new Error(`Failed to fetch file for confirm retry: ${JSON.stringify(fetchError)}`);
|
|
451
|
+
}
|
|
452
|
+
confirmTip = currentFile.cid;
|
|
453
|
+
} else {
|
|
454
|
+
throw new Error(`Confirm upload failed: ${errorStr}`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (confirmAttempts >= MAX_CONFIRM_ATTEMPTS) {
|
|
458
|
+
throw new Error(`Confirm upload failed after ${MAX_CONFIRM_ATTEMPTS} CAS retries`);
|
|
459
|
+
}
|
|
460
|
+
bytesUploaded += file.size;
|
|
461
|
+
reportProgress({
|
|
462
|
+
phase: "uploading",
|
|
463
|
+
bytesUploaded,
|
|
464
|
+
currentItem: file.relativePath
|
|
465
|
+
});
|
|
466
|
+
} catch (err) {
|
|
467
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
468
|
+
if (continueOnError) {
|
|
469
|
+
errors.push({ path: file.relativePath, error: `Upload failed: ${errorMsg}` });
|
|
470
|
+
} else {
|
|
471
|
+
throw new Error(`Failed to upload ${file.relativePath}: ${errorMsg}`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
})
|
|
476
|
+
);
|
|
477
|
+
reportProgress({ phase: "complete", totalParents, completedParents, bytesUploaded });
|
|
478
|
+
const resultFolders = createdFolders.map((f) => ({
|
|
479
|
+
id: f.id,
|
|
480
|
+
cid: f.entityCid,
|
|
481
|
+
type: "folder",
|
|
482
|
+
relativePath: f.relativePath
|
|
483
|
+
}));
|
|
484
|
+
const resultFiles = createdFiles.map((f) => ({
|
|
485
|
+
id: f.id,
|
|
486
|
+
cid: f.entityCid,
|
|
487
|
+
type: "file",
|
|
488
|
+
relativePath: f.relativePath
|
|
489
|
+
}));
|
|
490
|
+
return {
|
|
491
|
+
success: errors.length === 0,
|
|
492
|
+
collection: {
|
|
493
|
+
id: collectionId,
|
|
494
|
+
cid: collectionCid,
|
|
495
|
+
created: collectionCreated
|
|
496
|
+
},
|
|
497
|
+
folders: resultFolders,
|
|
498
|
+
files: resultFiles,
|
|
499
|
+
errors
|
|
500
|
+
};
|
|
501
|
+
} catch (err) {
|
|
502
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
503
|
+
reportProgress({
|
|
504
|
+
phase: "error",
|
|
505
|
+
error: errorMsg
|
|
506
|
+
});
|
|
507
|
+
return {
|
|
508
|
+
success: false,
|
|
509
|
+
collection: {
|
|
510
|
+
id: target.collectionId ?? "",
|
|
511
|
+
cid: "",
|
|
512
|
+
created: false
|
|
513
|
+
},
|
|
514
|
+
folders: createdFolders.map((f) => ({
|
|
515
|
+
id: f.id,
|
|
516
|
+
cid: f.entityCid,
|
|
517
|
+
type: "folder",
|
|
518
|
+
relativePath: f.relativePath
|
|
519
|
+
})),
|
|
520
|
+
files: createdFiles.map((f) => ({
|
|
521
|
+
id: f.id,
|
|
522
|
+
cid: f.entityCid,
|
|
523
|
+
type: "file",
|
|
524
|
+
relativePath: f.relativePath
|
|
525
|
+
})),
|
|
526
|
+
errors: [...errors, { path: "", error: errorMsg }]
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/operations/upload/scanners.ts
|
|
532
|
+
function getMimeType(filename) {
|
|
533
|
+
const ext = filename.toLowerCase().split(".").pop() || "";
|
|
534
|
+
const mimeTypes = {
|
|
535
|
+
// Images
|
|
536
|
+
jpg: "image/jpeg",
|
|
537
|
+
jpeg: "image/jpeg",
|
|
538
|
+
png: "image/png",
|
|
539
|
+
gif: "image/gif",
|
|
540
|
+
webp: "image/webp",
|
|
541
|
+
svg: "image/svg+xml",
|
|
542
|
+
ico: "image/x-icon",
|
|
543
|
+
bmp: "image/bmp",
|
|
544
|
+
tiff: "image/tiff",
|
|
545
|
+
tif: "image/tiff",
|
|
546
|
+
// Documents
|
|
547
|
+
pdf: "application/pdf",
|
|
548
|
+
doc: "application/msword",
|
|
549
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
550
|
+
xls: "application/vnd.ms-excel",
|
|
551
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
552
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
553
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
554
|
+
odt: "application/vnd.oasis.opendocument.text",
|
|
555
|
+
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
556
|
+
odp: "application/vnd.oasis.opendocument.presentation",
|
|
557
|
+
// Text
|
|
558
|
+
txt: "text/plain",
|
|
559
|
+
md: "text/markdown",
|
|
560
|
+
csv: "text/csv",
|
|
561
|
+
html: "text/html",
|
|
562
|
+
htm: "text/html",
|
|
563
|
+
css: "text/css",
|
|
564
|
+
xml: "text/xml",
|
|
565
|
+
rtf: "application/rtf",
|
|
566
|
+
// Code
|
|
567
|
+
js: "text/javascript",
|
|
568
|
+
mjs: "text/javascript",
|
|
569
|
+
ts: "text/typescript",
|
|
570
|
+
jsx: "text/javascript",
|
|
571
|
+
tsx: "text/typescript",
|
|
572
|
+
json: "application/json",
|
|
573
|
+
yaml: "text/yaml",
|
|
574
|
+
yml: "text/yaml",
|
|
575
|
+
// Archives
|
|
576
|
+
zip: "application/zip",
|
|
577
|
+
tar: "application/x-tar",
|
|
578
|
+
gz: "application/gzip",
|
|
579
|
+
rar: "application/vnd.rar",
|
|
580
|
+
"7z": "application/x-7z-compressed",
|
|
581
|
+
// Audio
|
|
582
|
+
mp3: "audio/mpeg",
|
|
583
|
+
wav: "audio/wav",
|
|
584
|
+
ogg: "audio/ogg",
|
|
585
|
+
m4a: "audio/mp4",
|
|
586
|
+
flac: "audio/flac",
|
|
587
|
+
// Video
|
|
588
|
+
mp4: "video/mp4",
|
|
589
|
+
webm: "video/webm",
|
|
590
|
+
avi: "video/x-msvideo",
|
|
591
|
+
mov: "video/quicktime",
|
|
592
|
+
mkv: "video/x-matroska",
|
|
593
|
+
// Fonts
|
|
594
|
+
woff: "font/woff",
|
|
595
|
+
woff2: "font/woff2",
|
|
596
|
+
ttf: "font/ttf",
|
|
597
|
+
otf: "font/otf",
|
|
598
|
+
// Other
|
|
599
|
+
wasm: "application/wasm"
|
|
600
|
+
};
|
|
601
|
+
return mimeTypes[ext] || "application/octet-stream";
|
|
602
|
+
}
|
|
603
|
+
async function scanDirectory(directoryPath, options = {}) {
|
|
604
|
+
const fs = await import("fs/promises");
|
|
605
|
+
const path = await import("path");
|
|
606
|
+
const { ignore = ["node_modules", ".git", ".DS_Store"], includeHidden = false } = options;
|
|
607
|
+
const files = [];
|
|
608
|
+
const folders = [];
|
|
609
|
+
const rootName = path.basename(directoryPath);
|
|
610
|
+
async function scanDir(dirPath, relativePath) {
|
|
611
|
+
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
612
|
+
for (const entry of entries) {
|
|
613
|
+
const name = entry.name;
|
|
614
|
+
if (!includeHidden && name.startsWith(".")) {
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (ignore.some((pattern) => name === pattern || name.match(pattern))) {
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
const fullPath = path.join(dirPath, name);
|
|
621
|
+
const entryRelativePath = relativePath ? `${relativePath}/${name}` : name;
|
|
622
|
+
if (entry.isDirectory()) {
|
|
623
|
+
folders.push({
|
|
624
|
+
name,
|
|
625
|
+
relativePath: entryRelativePath
|
|
626
|
+
});
|
|
627
|
+
await scanDir(fullPath, entryRelativePath);
|
|
628
|
+
} else if (entry.isFile()) {
|
|
629
|
+
const stat = await fs.stat(fullPath);
|
|
630
|
+
files.push({
|
|
631
|
+
name,
|
|
632
|
+
relativePath: entryRelativePath,
|
|
633
|
+
size: stat.size,
|
|
634
|
+
mimeType: getMimeType(name),
|
|
635
|
+
getData: async () => {
|
|
636
|
+
const buffer = await fs.readFile(fullPath);
|
|
637
|
+
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
await scanDir(directoryPath, "");
|
|
644
|
+
folders.sort((a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length);
|
|
645
|
+
return { files, folders };
|
|
646
|
+
}
|
|
647
|
+
async function scanFileSystemEntries(entries, options = {}) {
|
|
648
|
+
const { ignore = ["node_modules", ".git", ".DS_Store"] } = options;
|
|
649
|
+
const files = [];
|
|
650
|
+
const folders = [];
|
|
651
|
+
async function processEntry(entry, parentPath) {
|
|
652
|
+
const name = entry.name;
|
|
653
|
+
if (ignore.some((pattern) => name === pattern)) {
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
const relativePath = parentPath ? `${parentPath}/${name}` : name;
|
|
657
|
+
if (entry.isFile) {
|
|
658
|
+
const fileEntry = entry;
|
|
659
|
+
const file = await new Promise((resolve, reject) => {
|
|
660
|
+
fileEntry.file(resolve, reject);
|
|
661
|
+
});
|
|
662
|
+
files.push({
|
|
663
|
+
name,
|
|
664
|
+
relativePath,
|
|
665
|
+
size: file.size,
|
|
666
|
+
mimeType: file.type || getMimeType(name),
|
|
667
|
+
getData: async () => file.arrayBuffer()
|
|
668
|
+
});
|
|
669
|
+
} else if (entry.isDirectory) {
|
|
670
|
+
const dirEntry = entry;
|
|
671
|
+
folders.push({
|
|
672
|
+
name,
|
|
673
|
+
relativePath
|
|
674
|
+
});
|
|
675
|
+
const reader = dirEntry.createReader();
|
|
676
|
+
const childEntries = await new Promise((resolve, reject) => {
|
|
677
|
+
const allEntries = [];
|
|
678
|
+
function readEntries() {
|
|
679
|
+
reader.readEntries((entries2) => {
|
|
680
|
+
if (entries2.length === 0) {
|
|
681
|
+
resolve(allEntries);
|
|
682
|
+
} else {
|
|
683
|
+
allEntries.push(...entries2);
|
|
684
|
+
readEntries();
|
|
685
|
+
}
|
|
686
|
+
}, reject);
|
|
687
|
+
}
|
|
688
|
+
readEntries();
|
|
689
|
+
});
|
|
690
|
+
for (const childEntry of childEntries) {
|
|
691
|
+
await processEntry(childEntry, relativePath);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
for (const entry of entries) {
|
|
696
|
+
if (entry) {
|
|
697
|
+
await processEntry(entry, "");
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
folders.sort((a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length);
|
|
701
|
+
return { files, folders };
|
|
702
|
+
}
|
|
703
|
+
async function scanFileList(fileList, options = {}) {
|
|
704
|
+
const { ignore = ["node_modules", ".git", ".DS_Store"] } = options;
|
|
705
|
+
const files = [];
|
|
706
|
+
const folderPaths = /* @__PURE__ */ new Set();
|
|
707
|
+
for (let i = 0; i < fileList.length; i++) {
|
|
708
|
+
const file = fileList[i];
|
|
709
|
+
if (!file) continue;
|
|
710
|
+
const relativePath = file.webkitRelativePath || file.name;
|
|
711
|
+
const name = file.name;
|
|
712
|
+
const pathSegments = relativePath.split("/");
|
|
713
|
+
if (pathSegments.some((segment) => ignore.includes(segment))) {
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
const pathParts = relativePath.split("/");
|
|
717
|
+
for (let j = 1; j < pathParts.length; j++) {
|
|
718
|
+
const folderPath = pathParts.slice(0, j).join("/");
|
|
719
|
+
folderPaths.add(folderPath);
|
|
720
|
+
}
|
|
721
|
+
const fileRef = file;
|
|
722
|
+
files.push({
|
|
723
|
+
name,
|
|
724
|
+
relativePath,
|
|
725
|
+
size: fileRef.size,
|
|
726
|
+
mimeType: fileRef.type || getMimeType(name),
|
|
727
|
+
getData: async () => fileRef.arrayBuffer()
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
const folders = Array.from(folderPaths).map((path) => ({
|
|
731
|
+
name: path.split("/").pop(),
|
|
732
|
+
relativePath: path
|
|
733
|
+
})).sort((a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length);
|
|
734
|
+
return { files, folders };
|
|
735
|
+
}
|
|
736
|
+
function buildUploadTree(items) {
|
|
737
|
+
const files = [];
|
|
738
|
+
const folderPaths = /* @__PURE__ */ new Set();
|
|
739
|
+
for (const item of items) {
|
|
740
|
+
const pathParts = item.path.split("/");
|
|
741
|
+
const name = pathParts.pop();
|
|
742
|
+
for (let i = 1; i <= pathParts.length; i++) {
|
|
743
|
+
folderPaths.add(pathParts.slice(0, i).join("/"));
|
|
744
|
+
}
|
|
745
|
+
let size;
|
|
746
|
+
if (item.data instanceof Blob) {
|
|
747
|
+
size = item.data.size;
|
|
748
|
+
} else if (item.data instanceof ArrayBuffer) {
|
|
749
|
+
size = item.data.byteLength;
|
|
750
|
+
} else {
|
|
751
|
+
size = item.data.length;
|
|
752
|
+
}
|
|
753
|
+
files.push({
|
|
754
|
+
name,
|
|
755
|
+
relativePath: item.path,
|
|
756
|
+
size,
|
|
757
|
+
mimeType: item.mimeType || getMimeType(name),
|
|
758
|
+
getData: async () => item.data
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
const folders = Array.from(folderPaths).map((path) => ({
|
|
762
|
+
name: path.split("/").pop(),
|
|
763
|
+
relativePath: path
|
|
764
|
+
})).sort((a, b) => a.relativePath.split("/").length - b.relativePath.split("/").length);
|
|
765
|
+
return { files, folders };
|
|
766
|
+
}
|
|
767
|
+
|
|
29
768
|
// src/operations/folders.ts
|
|
30
769
|
var FolderOperations = class {
|
|
31
770
|
constructor(client) {
|
|
@@ -34,15 +773,32 @@ var FolderOperations = class {
|
|
|
34
773
|
/**
|
|
35
774
|
* Upload a local directory to Arke
|
|
36
775
|
*
|
|
37
|
-
*
|
|
38
|
-
* Steps:
|
|
39
|
-
* 1. Scan directory structure
|
|
40
|
-
* 2. Create folder hierarchy (depth-first)
|
|
41
|
-
* 3. Upload files in parallel (with concurrency limit)
|
|
42
|
-
* 4. Create bidirectional relationships (folder contains file)
|
|
776
|
+
* @deprecated Use uploadTree and scanDirectory instead
|
|
43
777
|
*/
|
|
44
|
-
async uploadDirectory(
|
|
45
|
-
|
|
778
|
+
async uploadDirectory(localPath, options) {
|
|
779
|
+
const tree = await scanDirectory(localPath);
|
|
780
|
+
const result = await uploadTree(this.client, tree, {
|
|
781
|
+
target: {
|
|
782
|
+
collectionId: options.collectionId,
|
|
783
|
+
parentId: options.parentFolderId
|
|
784
|
+
},
|
|
785
|
+
concurrency: options.concurrency,
|
|
786
|
+
onProgress: options.onProgress ? (p) => {
|
|
787
|
+
options.onProgress({
|
|
788
|
+
phase: p.phase === "computing-cids" ? "creating-folders" : p.phase === "creating" ? "uploading-files" : p.phase === "backlinking" ? "linking" : p.phase === "complete" ? "complete" : "scanning",
|
|
789
|
+
totalFiles: p.totalEntities,
|
|
790
|
+
completedFiles: p.completedEntities,
|
|
791
|
+
totalFolders: p.totalParents,
|
|
792
|
+
completedFolders: p.completedParents,
|
|
793
|
+
currentFile: p.currentItem
|
|
794
|
+
});
|
|
795
|
+
} : void 0
|
|
796
|
+
});
|
|
797
|
+
return {
|
|
798
|
+
rootFolder: result.folders[0] || null,
|
|
799
|
+
folders: result.folders,
|
|
800
|
+
files: result.files
|
|
801
|
+
};
|
|
46
802
|
}
|
|
47
803
|
};
|
|
48
804
|
|
|
@@ -108,6 +864,14 @@ var CryptoOperations = class {
|
|
|
108
864
|
0 && (module.exports = {
|
|
109
865
|
BatchOperations,
|
|
110
866
|
CryptoOperations,
|
|
111
|
-
FolderOperations
|
|
867
|
+
FolderOperations,
|
|
868
|
+
buildUploadTree,
|
|
869
|
+
computeCid,
|
|
870
|
+
getMimeType,
|
|
871
|
+
scanDirectory,
|
|
872
|
+
scanFileList,
|
|
873
|
+
scanFileSystemEntries,
|
|
874
|
+
uploadTree,
|
|
875
|
+
verifyCid
|
|
112
876
|
});
|
|
113
877
|
//# sourceMappingURL=index.cjs.map
|