@fnndsc/cumin 3.30.6 → 3.31.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.
Files changed (161) hide show
  1. package/dist/cache/checkpointWatch.d.ts +36 -0
  2. package/dist/cache/checkpointWatch.js +83 -0
  3. package/dist/cache/checkpointWatch.js.map +1 -0
  4. package/dist/cache/index.d.ts +1 -1
  5. package/dist/cache/index.js +4 -1
  6. package/dist/cache/index.js.map +1 -1
  7. package/dist/cache/listCache.d.ts +54 -2
  8. package/dist/cache/listCache.js +120 -24
  9. package/dist/cache/listCache.js.map +1 -1
  10. package/dist/cache/listCheckpoint.d.ts +5 -8
  11. package/dist/cache/listCheckpoint.js +17 -28
  12. package/dist/cache/listCheckpoint.js.map +1 -1
  13. package/dist/cache/listingInvalidation.js +11 -6
  14. package/dist/cache/listingInvalidation.js.map +1 -1
  15. package/dist/cache/procCache.d.ts +11 -0
  16. package/dist/cache/procCache.js +26 -1
  17. package/dist/cache/procCache.js.map +1 -1
  18. package/dist/cache/procCheckpoint.d.ts +11 -6
  19. package/dist/cache/procCheckpoint.js +280 -86
  20. package/dist/cache/procCheckpoint.js.map +1 -1
  21. package/dist/cache/queryIndex.d.ts +11 -0
  22. package/dist/cache/queryIndex.js +38 -2
  23. package/dist/cache/queryIndex.js.map +1 -1
  24. package/dist/cache/queryIndexCheckpoint.d.ts +32 -0
  25. package/dist/cache/queryIndexCheckpoint.js +180 -30
  26. package/dist/cache/queryIndexCheckpoint.js.map +1 -1
  27. package/dist/chrisapi/adapter.d.ts +266 -37
  28. package/dist/chrisapi/adapter.js +577 -116
  29. package/dist/chrisapi/adapter.js.map +1 -1
  30. package/dist/chrisapi/contract.d.ts +20 -20
  31. package/dist/chrisapi/contract.js +213 -60
  32. package/dist/chrisapi/contract.js.map +1 -1
  33. package/dist/chrisapi/cubeRequest.d.ts +198 -0
  34. package/dist/chrisapi/cubeRequest.js +345 -0
  35. package/dist/chrisapi/cubeRequest.js.map +1 -0
  36. package/dist/chrisapi/shape.d.ts +186 -0
  37. package/dist/chrisapi/shape.js +274 -0
  38. package/dist/chrisapi/shape.js.map +1 -0
  39. package/dist/cli.js +2 -1
  40. package/dist/cli.js.map +1 -1
  41. package/dist/compute/computeResources.d.ts +3 -0
  42. package/dist/compute/computeResources.js +5 -3
  43. package/dist/compute/computeResources.js.map +1 -1
  44. package/dist/config/config.d.ts +14 -0
  45. package/dist/config/config.js +6 -3
  46. package/dist/config/config.js.map +1 -1
  47. package/dist/connect/chrisConnection.d.ts +116 -6
  48. package/dist/connect/chrisConnection.js +418 -74
  49. package/dist/connect/chrisConnection.js.map +1 -1
  50. package/dist/connect/identityEpoch.d.ts +263 -0
  51. package/dist/connect/identityEpoch.js +414 -0
  52. package/dist/connect/identityEpoch.js.map +1 -0
  53. package/dist/connect/loginFailure.js +39 -22
  54. package/dist/connect/loginFailure.js.map +1 -1
  55. package/dist/context/chrisContext.js +36 -30
  56. package/dist/context/chrisContext.js.map +1 -1
  57. package/dist/error/errorStack.d.ts +1 -1
  58. package/dist/error/errorStack.js +1 -2
  59. package/dist/error/errorStack.js.map +1 -1
  60. package/dist/feeds/chrisAccess.d.ts +7 -2
  61. package/dist/feeds/chrisAccess.js +20 -7
  62. package/dist/feeds/chrisAccess.js.map +1 -1
  63. package/dist/feeds/chrisFeed.d.ts +8 -10
  64. package/dist/feeds/chrisFeed.js +27 -57
  65. package/dist/feeds/chrisFeed.js.map +1 -1
  66. package/dist/feeds/chrisTags.d.ts +1 -1
  67. package/dist/feeds/chrisTags.js +66 -24
  68. package/dist/feeds/chrisTags.js.map +1 -1
  69. package/dist/filebrowser/chrisFileBrowser.d.ts +0 -1
  70. package/dist/filebrowser/chrisFileBrowser.js +3 -5
  71. package/dist/filebrowser/chrisFileBrowser.js.map +1 -1
  72. package/dist/filebrowser/chrisFiles.d.ts +0 -1
  73. package/dist/filebrowser/chrisFiles.js +3 -4
  74. package/dist/filebrowser/chrisFiles.js.map +1 -1
  75. package/dist/filebrowser/chrisPACS.d.ts +4 -4
  76. package/dist/filebrowser/chrisPACS.js +10 -33
  77. package/dist/filebrowser/chrisPACS.js.map +1 -1
  78. package/dist/filebrowser/chrisPipeline.js +10 -45
  79. package/dist/filebrowser/chrisPipeline.js.map +1 -1
  80. package/dist/groups/chrisGroups.d.ts +3 -0
  81. package/dist/groups/chrisGroups.js +20 -8
  82. package/dist/groups/chrisGroups.js.map +1 -1
  83. package/dist/index.d.ts +6 -8
  84. package/dist/index.js +17 -28
  85. package/dist/index.js.map +1 -1
  86. package/dist/io/chrisIO.d.ts +81 -42
  87. package/dist/io/chrisIO.js +176 -325
  88. package/dist/io/chrisIO.js.map +1 -1
  89. package/dist/io/holderClient.d.ts +248 -0
  90. package/dist/io/holderClient.js +289 -0
  91. package/dist/io/holderClient.js.map +1 -0
  92. package/dist/io/holderFolder.d.ts +151 -0
  93. package/dist/io/holderFolder.js +311 -0
  94. package/dist/io/holderFolder.js.map +1 -0
  95. package/dist/io/holderIO.d.ts +258 -0
  96. package/dist/io/holderIO.js +557 -0
  97. package/dist/io/holderIO.js.map +1 -0
  98. package/dist/io/holderRequest.d.ts +299 -0
  99. package/dist/io/holderRequest.js +447 -0
  100. package/dist/io/holderRequest.js.map +1 -0
  101. package/dist/io/holderUpload.d.ts +62 -0
  102. package/dist/io/holderUpload.js +81 -0
  103. package/dist/io/holderUpload.js.map +1 -0
  104. package/dist/io/io.d.ts +12 -0
  105. package/dist/io/io.js.map +1 -1
  106. package/dist/io/localUpload.d.ts +59 -0
  107. package/dist/io/localUpload.js +150 -0
  108. package/dist/io/localUpload.js.map +1 -0
  109. package/dist/io/node_io.d.ts +16 -0
  110. package/dist/io/node_io.js +72 -0
  111. package/dist/io/node_io.js.map +1 -1
  112. package/dist/io/streamWatch.js +2 -2
  113. package/dist/io/streamWatch.js.map +1 -1
  114. package/dist/io/transferPool.d.ts +18 -2
  115. package/dist/io/transferPool.js +32 -7
  116. package/dist/io/transferPool.js.map +1 -1
  117. package/dist/pacs/chrisPACS.d.ts +3 -9
  118. package/dist/pacs/chrisPACS.js +102 -61
  119. package/dist/pacs/chrisPACS.js.map +1 -1
  120. package/dist/pacs/queryIndexSweep.d.ts +0 -9
  121. package/dist/pacs/queryIndexSweep.js +45 -41
  122. package/dist/pacs/queryIndexSweep.js.map +1 -1
  123. package/dist/path/chrisPath.d.ts +8 -3
  124. package/dist/path/chrisPath.js +10 -9
  125. package/dist/path/chrisPath.js.map +1 -1
  126. package/dist/pipelines/chrisPipeline.d.ts +28 -5
  127. package/dist/pipelines/chrisPipeline.js +270 -94
  128. package/dist/pipelines/chrisPipeline.js.map +1 -1
  129. package/dist/pipelines/pipelineMemo.d.ts +0 -16
  130. package/dist/pipelines/pipelineMemo.js +0 -27
  131. package/dist/pipelines/pipelineMemo.js.map +1 -1
  132. package/dist/plugins/chrisPlugins.d.ts +9 -5
  133. package/dist/plugins/chrisPlugins.js +97 -58
  134. package/dist/plugins/chrisPlugins.js.map +1 -1
  135. package/dist/resources/chrisObjContext.d.ts +7 -11
  136. package/dist/resources/chrisObjContext.js +7 -42
  137. package/dist/resources/chrisObjContext.js.map +1 -1
  138. package/dist/resources/chrisResources.d.ts +186 -74
  139. package/dist/resources/chrisResources.js +421 -117
  140. package/dist/resources/chrisResources.js.map +1 -1
  141. package/dist/resources/resourceShapes.d.ts +109 -0
  142. package/dist/resources/resourceShapes.js +22 -0
  143. package/dist/resources/resourceShapes.js.map +1 -0
  144. package/dist/users/chrisUsers.d.ts +4 -1
  145. package/dist/users/chrisUsers.js +6 -2
  146. package/dist/users/chrisUsers.js.map +1 -1
  147. package/dist/utils/keypair.js +21 -10
  148. package/dist/utils/keypair.js.map +1 -1
  149. package/package.json +10 -3
  150. package/dist/activities/chrisActivity.d.ts +0 -19
  151. package/dist/activities/chrisActivity.js +0 -29
  152. package/dist/activities/chrisActivity.js.map +0 -1
  153. package/dist/jobs/chrisJob.d.ts +0 -43
  154. package/dist/jobs/chrisJob.js +0 -174
  155. package/dist/jobs/chrisJob.js.map +0 -1
  156. package/dist/jobs/index.d.ts +0 -7
  157. package/dist/jobs/index.js +0 -24
  158. package/dist/jobs/index.js.map +0 -1
  159. package/dist/jobs/jobMonitor.d.ts +0 -46
  160. package/dist/jobs/jobMonitor.js +0 -102
  161. package/dist/jobs/jobMonitor.js.map +0 -1
@@ -9,6 +9,12 @@
9
9
  */
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.chrisIO = exports.ChrisIO = void 0;
12
+ const holderClient_js_1 = require("./holderClient.js");
13
+ const holderFolder_js_1 = require("./holderFolder.js");
14
+ const holderIO_js_1 = require("./holderIO.js");
15
+ const holderUpload_js_1 = require("./holderUpload.js");
16
+ const localUpload_js_1 = require("./localUpload.js");
17
+ const listCache_js_1 = require("../cache/listCache.js");
12
18
  const chrisConnection_js_1 = require("../connect/chrisConnection.js");
13
19
  const adapter_js_1 = require("../chrisapi/adapter.js");
14
20
  const errorStack_js_1 = require("../error/errorStack.js");
@@ -34,13 +40,22 @@ function httpStatus_extract(error) {
34
40
  const status = candidate.response?.status ?? candidate.status;
35
41
  return typeof status === "number" ? status : null;
36
42
  }
43
+ /**
44
+ * The size a file stream's response declares: its Content-Length header,
45
+ * lower case first, read as a decimal number.
46
+ *
47
+ * @param response - The stream's response.
48
+ * @returns The declared size (NaN for a header that is not a number), or undefined when no text header is given.
49
+ */
50
+ function streamSize_read(response) {
51
+ const lengthHeader = response.headers?.["content-length"] ||
52
+ response.headers?.["Content-Length"];
53
+ return typeof lengthHeader === "string" ? parseInt(lengthHeader, 10) : undefined;
54
+ }
37
55
  class ChrisIO {
38
56
  constructor() {
39
57
  this._chrisFolder = "";
40
- this._client = null;
41
58
  this.storageProvider = null;
42
- /** HTTP status of the most recent failed file lookup, when CUBE gave one. */
43
- this.lastFileRefusal = null;
44
59
  // Client initialization is deferred or handled via async accessor
45
60
  }
46
61
  /**
@@ -55,10 +70,9 @@ class ChrisIO {
55
70
  * @returns A Promise resolving to the Client instance or null.
56
71
  */
57
72
  async client_get() {
58
- if (!this._client) {
59
- this._client = await chrisConnection_js_1.chrisConnection.client_get();
60
- }
61
- return this._client;
73
+ // Asked of the connection each time, never kept: the connection knows who is connected now, and whose
74
+ // client a `sudo` scope is running under.
75
+ return chrisConnection_js_1.chrisConnection.client_get();
62
76
  }
63
77
  get chrisFolder() {
64
78
  return this._chrisFolder;
@@ -107,87 +121,92 @@ class ChrisIO {
107
121
  *
108
122
  * @param client - The connected ChRIS client.
109
123
  * @param fileId - The file id from a folder listing.
110
- * @returns The file resource, or null when neither collection knows the id.
124
+ * @returns The file resource, or none with the status CUBE refused the lookup with.
111
125
  */
112
126
  async downloadableFile_get(client, fileId) {
113
- this.lastFileRefusal = null;
127
+ // What CUBE refused with, for this lookup alone: held here and handed back with the answer, so that two
128
+ // lookups under way at once each say their own reason.
129
+ let refusal = null;
114
130
  try {
115
- const userFile = await client.getUserFile(fileId);
131
+ // Asked through cumin's guarded request at CUBE's own address, never chrisapi's lookup, which asks
132
+ // whatever collection CUBE's root advertises and follows its links anywhere.
133
+ const userFile = await (0, adapter_js_1.fileById_read)(client, 'userfiles', fileId);
116
134
  if (userFile)
117
- return userFile;
135
+ return { file: userFile, refusal: null };
118
136
  }
119
137
  catch (error) {
120
138
  // A refusal is not an absence. CUBE answers 403 for a file this
121
139
  // identity may see listed but not read — the shape a shared feed
122
140
  // takes — and reporting that as "not found" sends an operator
123
141
  // looking for a missing file that is in fact right there.
124
- this.lastFileRefusal = httpStatus_extract(error);
142
+ refusal = httpStatus_extract(error);
125
143
  }
126
144
  try {
127
- const pacsFile = await (0, adapter_js_1.resource_call)(client, 'getPACSFile', fileId);
145
+ const pacsFile = await (0, adapter_js_1.fileById_read)(client, 'pacs/files', fileId);
128
146
  if (pacsFile)
129
- return pacsFile;
147
+ return { file: pacsFile, refusal: null };
130
148
  }
131
149
  catch (error) {
132
- this.lastFileRefusal ?? (this.lastFileRefusal = httpStatus_extract(error));
150
+ refusal ?? (refusal = httpStatus_extract(error));
133
151
  }
134
152
  // A file in a feed shared with this identity: CUBE serves it through
135
153
  // the file browser while `/userfiles/` answers 403.
154
+ let reason;
136
155
  try {
137
156
  const shared = await (0, adapter_js_1.filebrowserFile_get)(client, fileId);
138
- if (shared) {
139
- this.lastFileRefusal = null;
140
- return shared;
141
- }
157
+ if (shared)
158
+ return { file: shared, refusal: null };
142
159
  }
143
160
  catch (error) {
144
- this.lastFileRefusal ?? (this.lastFileRefusal = httpStatus_extract(error));
161
+ // A status CUBE gave earlier (the 403 of `/userfiles/`) stays the reason: a fallback refused for its own
162
+ // cause does not replace it.
163
+ const status = httpStatus_extract(error);
164
+ refusal ?? (refusal = status);
165
+ if (status === null && error instanceof Error)
166
+ reason = error.message;
145
167
  }
146
168
  // The client answers a refusal with null as readily as it does an
147
169
  // absence, so neither branch above necessarily carries a status. Ask
148
170
  // CUBE plainly what it thinks of this file, once, on the failure path
149
171
  // only: an operator told "not found" about a file they can see listed
150
172
  // will go looking for the wrong problem.
151
- this.lastFileRefusal ?? (this.lastFileRefusal = await this.fileStatus_probe(fileId));
152
- return null;
173
+ refusal ?? (refusal = await this.fileStatus_probe(client, fileId));
174
+ return refusal === null && reason !== undefined ? { file: null, refusal, reason } : { file: null, refusal };
153
175
  }
154
176
  /**
155
- * Asks CUBE directly what it answers for a file id.
177
+ * Asks CUBE directly what it answers for a file id, as the same user the
178
+ * lookup was made as: with that lookup's own client's address and token,
179
+ * never the connection's current ones (which are another user's inside a
180
+ * `sudo`, and after someone else has connected), at CUBE's own address
181
+ * for the file, following no redirect.
156
182
  *
183
+ * @param client - The client the lookup was made with.
157
184
  * @param fileId - The file the lookup could not resolve.
158
185
  * @returns The HTTP status, or null when it could not be asked.
159
186
  */
160
- async fileStatus_probe(fileId) {
161
- try {
162
- const url = await chrisConnection_js_1.chrisConnection.chrisURL_get();
163
- const token = await chrisConnection_js_1.chrisConnection.authToken_get();
164
- if (!url || !token)
165
- return null;
166
- const response = await fetch(`${url.replace(/\/$/, "")}/userfiles/${fileId}/`, {
167
- headers: { Authorization: `Token ${token}` },
168
- });
169
- return response.status;
170
- }
171
- catch {
172
- return null;
173
- }
187
+ async fileStatus_probe(client, fileId) {
188
+ return (0, holderIO_js_1.itemStatus_probe)(client, "file", fileId);
174
189
  }
175
190
  /**
176
191
  * Explains why a file lookup came back empty, in CUBE's own terms.
177
192
  *
178
193
  * @param fileId - The file the operator asked for.
194
+ * @param refusal - The status CUBE refused that lookup with, when it gave one.
195
+ * @param reason - Why the lookup was refused when CUBE gave no status.
179
196
  * @returns A sentence naming what CUBE actually answered.
180
197
  */
181
- fileRefusal_describe(fileId) {
182
- if (this.lastFileRefusal === 403) {
198
+ fileRefusal_describe(fileId, refusal, reason) {
199
+ if (refusal === 403) {
183
200
  return `File ID ${fileId}: CUBE refused access (403). It is listed but not readable by this identity — a feed shared with you grants the listing, not the contents.`;
184
201
  }
185
- if (this.lastFileRefusal === 404) {
202
+ if (refusal === 404) {
186
203
  return `File ID ${fileId} does not exist (404).`;
187
204
  }
188
- if (this.lastFileRefusal !== null) {
189
- return `File ID ${fileId} could not be read: CUBE answered ${this.lastFileRefusal}.`;
205
+ if (refusal !== null) {
206
+ return `File ID ${fileId} could not be read: CUBE answered ${refusal}.`;
190
207
  }
208
+ if (reason !== undefined)
209
+ return `File ID ${fileId} could not be read: ${reason}.`;
191
210
  return `File ID ${fileId} is not in the file collections this client can read.`;
192
211
  }
193
212
  async file_downloadStream(fileId) {
@@ -197,9 +216,10 @@ class ChrisIO {
197
216
  return (0, result_js_1.Err)();
198
217
  }
199
218
  try {
200
- const userFile = await this.downloadableFile_get(client, fileId);
219
+ const looked = await this.downloadableFile_get(client, fileId);
220
+ const userFile = looked.file;
201
221
  if (!userFile) {
202
- errorStack_js_1.errorStack.stack_push("error", this.fileRefusal_describe(fileId));
222
+ errorStack_js_1.errorStack.stack_push("error", this.fileRefusal_describe(fileId, looked.refusal, looked.reason));
203
223
  return (0, result_js_1.Err)();
204
224
  }
205
225
  // No deadline on the transfer (chrisapi's default is 30 s, which a
@@ -210,9 +230,7 @@ class ChrisIO {
210
230
  errorStack_js_1.errorStack.stack_push("error", `File ID ${fileId} returned no data.`);
211
231
  return (0, result_js_1.Err)();
212
232
  }
213
- const lengthHeader = response.headers?.["content-length"] ||
214
- response.headers?.["Content-Length"];
215
- const size = typeof lengthHeader === "string" ? parseInt(lengthHeader, 10) : undefined;
233
+ const size = streamSize_read(response);
216
234
  const body = response.data;
217
235
  const watched = body !== null && typeof body === "object" && typeof body.pipe === "function"
218
236
  ? (0, streamWatch_js_1.stream_watchStalls)(body, streamWatch_js_1.STREAM_STALL_MS, `file ${fileId}`)
@@ -220,7 +238,7 @@ class ChrisIO {
220
238
  return (0, result_js_1.Ok)({
221
239
  stream: watched,
222
240
  size: Number.isFinite(size) ? size : undefined,
223
- filename: userFile.data?.fname,
241
+ filename: ((name) => (typeof name === 'string' ? name : undefined))(userFile.data.fname),
224
242
  });
225
243
  }
226
244
  catch (error) {
@@ -240,8 +258,9 @@ class ChrisIO {
240
258
  if (!client)
241
259
  return null;
242
260
  try {
243
- const userFile = await this.downloadableFile_get(client, fileId);
244
- const fsize = userFile?.data?.fsize;
261
+ const looked = await this.downloadableFile_get(client, fileId);
262
+ const userFile = looked.file;
263
+ const fsize = userFile?.data.fsize;
245
264
  return typeof fsize === "number" ? fsize : null;
246
265
  }
247
266
  catch {
@@ -251,44 +270,25 @@ class ChrisIO {
251
270
  /**
252
271
  * Downloads a file from ChRIS by its ID.
253
272
  * @param fileId - The ID of the file to download.
273
+ * @param bound - The client an act was bound to, read on instead of the session's now.
254
274
  * @returns A Promise resolving to a Buffer of the file content, or null on failure.
255
275
  */
256
- async file_download(fileId) {
257
- const client = await this.client_get();
276
+ async file_download(fileId, bound) {
277
+ const client = bound ?? await this.client_get();
258
278
  if (!client) {
259
279
  errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
260
280
  return null;
261
281
  }
262
282
  try {
263
- const userFile = await this.downloadableFile_get(client, fileId);
283
+ const looked = await this.downloadableFile_get(client, fileId);
284
+ const userFile = looked.file;
264
285
  if (!userFile) {
265
286
  // This is a common case: the file ID was scraped from a listing, but
266
287
  // the file itself is not retrievable (e.g. 404, or permissions)
267
- errorStack_js_1.errorStack.stack_push("error", this.fileRefusal_describe(fileId));
288
+ errorStack_js_1.errorStack.stack_push("error", this.fileRefusal_describe(fileId, looked.refusal, looked.reason));
268
289
  return null;
269
290
  }
270
- const blob = await userFile.getFileBlob();
271
- if (!blob) {
272
- errorStack_js_1.errorStack.stack_push("error", `File ID ${fileId} exists but returned no content/blob.`);
273
- return null;
274
- }
275
- if (typeof blob === "string") {
276
- return Buffer.from(blob);
277
- }
278
- else if (Buffer.isBuffer(blob)) {
279
- // Already a Node.js Buffer
280
- return blob;
281
- }
282
- else if (blob instanceof ArrayBuffer) {
283
- return Buffer.from(blob);
284
- }
285
- else if (blob instanceof Blob) {
286
- const arrayBuffer = await blob.arrayBuffer();
287
- return Buffer.from(arrayBuffer);
288
- }
289
- else {
290
- throw new Error(`Unexpected blob type: ${typeof blob}`);
291
- }
291
+ return Buffer.from(await userFile.getFileBlob());
292
292
  }
293
293
  catch (error) {
294
294
  // Catch network errors, timeouts, or specific API error messages
@@ -298,79 +298,45 @@ class ChrisIO {
298
298
  }
299
299
  }
300
300
  /**
301
- * Uploads a file to ChRIS.
301
+ * Uploads a file and answers what CUBE stored, without touching it after.
302
302
  *
303
- * The upload has no deadline as a whole; it fails when it has made no
304
- * progress for `STREAM_STALL_MS`, with a sentence saying how far it got.
303
+ * A caller that goes on to act on the file (to move it, or to delete it)
304
+ * needs to know which file it is: its id, and the path it actually landed
305
+ * at, which is not always the one asked (CUBE may suffix the name). The
306
+ * name is never changed back here.
305
307
  *
306
- * @param fileBlob - The file content as a Blob.
307
- * @param uploadDir - The directory path in ChRIS to upload to.
308
- * @param filename - The name of the file to create.
309
- * @returns A Promise resolving to true on success, false on failure.
308
+ * @param fileBlob - The file content.
309
+ * @param uploadDir - The ChRIS folder to upload into.
310
+ * @param filename - The name asked for.
311
+ * @returns The stored file's id and path, or Err with the reason stacked
312
+ * when the upload failed or CUBE's answer names no usable id or path.
310
313
  */
311
- async file_upload(fileBlob, uploadDir, filename) {
314
+ async file_uploadReceipted(fileBlob, uploadDir, filename) {
312
315
  const client = await this.client_get();
313
316
  if (!client) {
314
- console.error("ChRIS client is not initialized");
315
- return false;
316
- }
317
- try {
318
- // ChRIS API expects paths WITHOUT leading slash
319
- // upload_path should be the FULL PATH including filename
320
- const normalizedUploadDir = uploadDir.startsWith('/') ? uploadDir.substring(1) : uploadDir;
321
- const fullPath = normalizedUploadDir.endsWith('/')
322
- ? normalizedUploadDir + filename
323
- : normalizedUploadDir + '/' + filename;
324
- // No deadline on the whole upload (CUBE takes bytes at about 0.4 MB/s,
325
- // so any fixed one fails a healthy large file): the watch fails it when
326
- // it stops moving, abandons the request, and says how far it got.
327
- const watch = (0, streamWatch_js_1.upload_watchStalls)(fileBlob, filename, streamWatch_js_1.STREAM_STALL_MS);
328
- const abandon = new AbortController();
329
- watch.stalled.catch((stall) => { abandon.abort(stall); });
330
- let uploaded;
331
- try {
332
- uploaded = await (0, adapter_js_1.client_userFileUpload)(client, fullPath, watch.file, abandon.signal);
333
- }
334
- finally {
335
- watch.stop();
336
- }
337
- // ChRIS may rename the file to avoid collisions (e.g. world.txt → world_XXXXXXX.txt)
338
- // when the path was recently deleted and not yet committed. Renaming
339
- // it back is right THEN and catastrophic when the path is genuinely
340
- // occupied: a write onto a path the store already holds leaves a row
341
- // CUBE's own API cannot serve, and one such row makes every listing
342
- // of that folder fail (docs/CUBE-gaps.adoc). So the rename happens
343
- // only when the wanted path is free, and a check that cannot answer
344
- // counts as occupied — the safe reading, since the cost of guessing
345
- // wrong is the operator's folder.
346
- const actualFname = typeof uploaded.fname === 'string' ? uploaded.fname : '';
347
- const normalizedActual = actualFname.startsWith('/') ? actualFname.substring(1) : actualFname;
348
- if (normalizedActual && normalizedActual !== fullPath) {
349
- const free = await this.path_isFree(client, fullPath, normalizedActual);
350
- if (!free) {
351
- errorStack_js_1.errorStack.stack_push('warning', `'${fullPath}' already exists — the upload landed as '${actualFname}' rather than overwriting it`);
352
- }
353
- else {
354
- try {
355
- const userFile = typeof uploaded.id === 'number' ? await client.getUserFile(uploaded.id) : null;
356
- if (userFile === null)
357
- throw new Error('CUBE did not name the uploaded file');
358
- await userFile.put({ upload_path: fullPath });
359
- }
360
- catch (renameErr) {
361
- const renameMsg = renameErr instanceof Error ? renameErr.message : String(renameErr);
362
- errorStack_js_1.errorStack.stack_push('warning', `Uploaded as '${actualFname}' — rename to '${fullPath}' failed: ${renameMsg}`);
363
- // Don't fail the upload — file was uploaded, just at wrong name
364
- }
365
- }
366
- }
367
- return true;
317
+ errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
318
+ return (0, result_js_1.Err)();
368
319
  }
369
- catch (error) {
370
- const errorMsg = error instanceof Error ? error.message : String(error);
371
- errorStack_js_1.errorStack.stack_push("error", `Failed to upload file ${filename} to ${uploadDir}: ${errorMsg}`);
372
- return false;
320
+ return (0, holderUpload_js_1.file_uploadReceipted)(client, fileBlob, uploadDir, filename);
321
+ }
322
+ /**
323
+ * Where a file is now, asked of CUBE by the file's id.
324
+ *
325
+ * After a move whose reply was lost, the move may or may not have
326
+ * happened; this is how a caller finds out before it undoes anything.
327
+ *
328
+ * @param fileId - The file's id.
329
+ * @returns The file's path with a leading slash; null when CUBE says the
330
+ * file is not there (404); Err when CUBE could not be asked or would
331
+ * not say, which is neither.
332
+ */
333
+ async file_locate(fileId) {
334
+ const client = await this.client_get();
335
+ if (!client) {
336
+ errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
337
+ return (0, result_js_1.Err)();
373
338
  }
339
+ return (0, holderIO_js_1.file_locate)(client, fileId);
374
340
  }
375
341
  /**
376
342
  * Deletes one file by its id, without listing anything.
@@ -389,57 +355,21 @@ class ChrisIO {
389
355
  errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
390
356
  return (0, result_js_1.Err)();
391
357
  }
392
- try {
393
- const userFile = await client.getUserFile(fileId);
394
- if (!userFile) {
395
- errorStack_js_1.errorStack.stack_push("error", `File not found with ID ${fileId}`);
396
- return (0, result_js_1.Err)();
397
- }
398
- await (0, adapter_js_1.resource_call)(userFile, '_delete');
399
- return (0, result_js_1.Ok)(true);
400
- }
401
- catch (error) {
402
- const message = error instanceof Error ? error.message : String(error);
403
- errorStack_js_1.errorStack.stack_push("error", `Failed to delete file ID ${fileId}: ${message}`);
358
+ const asked = await (0, holderIO_js_1.file_deleteById)(client, fileId);
359
+ if (!asked.ok)
404
360
  return (0, result_js_1.Err)();
405
- }
406
- }
407
- /**
408
- * Whether a path is free to be written to.
409
- *
410
- * Asked by exact name rather than by listing the folder: one request, and
411
- * it still answers when the folder's own listing is broken. Anything the
412
- * server will not answer counts as occupied.
413
- *
414
- * @param client - The connected client.
415
- * @param wanted - The path a write wants, without a leading slash.
416
- * @param mine - The path the just-uploaded file currently occupies, which
417
- * is not a collision with itself.
418
- * @returns True when nothing else holds the path.
419
- */
420
- async path_isFree(client, wanted, mine) {
421
- try {
422
- // listing-bound: one exact path can only be held by one file; five is
423
- // room for a server that answers loosely, not a page of a collection.
424
- const held = await client.getUserFiles({ limit: 5, fname_exact: wanted });
425
- const items = held.getItems() ?? [];
426
- for (const item of items) {
427
- const fname = (0, adapter_js_1.itemData_get)(item)?.fname ?? '';
428
- const normalized = fname.startsWith('/') ? fname.substring(1) : fname;
429
- if (normalized !== mine)
430
- return false;
431
- }
432
- return true;
433
- }
434
- catch {
435
- return false;
436
- }
361
+ if (asked.value === "accepted")
362
+ return (0, result_js_1.Ok)(true);
363
+ errorStack_js_1.errorStack.stack_push("error", `The delete of file ID ${String(fileId)} was asked and CUBE gave no reply: it may or may not be gone`);
364
+ return (0, result_js_1.Err)();
437
365
  }
438
366
  /**
439
367
  * Creates a new folder in ChRIS at the specified path.
440
368
  *
441
369
  * @param folderPath - The path where the folder should be created.
442
- * @returns A Result containing true if created, false if already exists, or Err on error.
370
+ * @returns Ok(true) when CUBE's answer names the folder made, Ok(false)
371
+ * when CUBE said it was there already; Err on error, and when a folder
372
+ * is there after a post CUBE did not answer (who made it is not known).
443
373
  *
444
374
  * @example
445
375
  * ```typescript
@@ -455,42 +385,13 @@ class ChrisIO {
455
385
  errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
456
386
  return (0, result_js_1.Err)();
457
387
  }
458
- try {
459
- const folderList = await client.getFileBrowserFolders();
460
- const response = await folderList.post({ path: folderPath });
461
- if (response && response.data) {
462
- return (0, result_js_1.Ok)(true); // Folder created successfully
463
- }
464
- else {
465
- errorStack_js_1.errorStack.stack_push("error", `Failed to create folder: ${folderPath}. No data in response.`);
466
- return (0, result_js_1.Err)();
467
- }
468
- }
469
- catch (error) {
470
- // Check if this is an "already exists" error (400 status with specific message)
471
- if (error &&
472
- typeof error === 'object' &&
473
- 'response' in error &&
474
- error.response &&
475
- typeof error.response === 'object' &&
476
- 'status' in error.response &&
477
- error.response.status === 400 &&
478
- 'data' in error.response &&
479
- error.response.data &&
480
- typeof error.response.data === 'object' &&
481
- 'path' in error.response.data &&
482
- Array.isArray(error.response.data.path) &&
483
- error.response.data.path[0] &&
484
- typeof error.response.data.path[0] === 'string' &&
485
- error.response.data.path[0].includes('already exists')) {
486
- errorStack_js_1.errorStack.stack_push("warning", `Folder '${folderPath}' already exists.`);
487
- return (0, result_js_1.Ok)(false); // Return false to indicate folder already existed
488
- }
489
- // Other errors
490
- const errorMessage = error instanceof Error ? error.message : String(error);
491
- errorStack_js_1.errorStack.stack_push("error", `Error creating folder '${folderPath}': ${errorMessage}`);
388
+ const posted = await (0, holderFolder_js_1.folder_post)(client, folderPath);
389
+ if (!posted.ok)
492
390
  return (0, result_js_1.Err)();
493
- }
391
+ if (posted.value !== "present")
392
+ return (0, result_js_1.Ok)(posted.value === "made");
393
+ errorStack_js_1.errorStack.stack_push("error", `The folder ${folderPath} is there, but CUBE did not answer the request to make it: who made it is not known`);
394
+ return (0, result_js_1.Err)();
494
395
  }
495
396
  /**
496
397
  * Moves (renames) a folder in ChRIS by updating its path.
@@ -511,7 +412,7 @@ class ChrisIO {
511
412
  return (0, result_js_1.Err)();
512
413
  }
513
414
  // chrisapi typings omit the path field, but API supports it for renames
514
- await (0, adapter_js_1.resource_call)(folder, 'put', { path: destPath });
415
+ await (0, adapter_js_1.resource_invoke)(folder, 'put', { path: destPath });
515
416
  return (0, result_js_1.Ok)(true);
516
417
  }
517
418
  catch (error) {
@@ -544,9 +445,12 @@ class ChrisIO {
544
445
  if (!folder) {
545
446
  return (0, result_js_1.Ok)(true);
546
447
  }
547
- await (0, adapter_js_1.resource_call)(folder, 'delete');
448
+ await (0, adapter_js_1.resource_invoke)(folder, 'delete');
548
449
  const deadline = Date.now() + (options.timeoutMs ?? 10000);
549
450
  while (Date.now() < deadline) {
451
+ // What is remembered of this folder is from before the delete: it is dropped before each look, so
452
+ // that the look asks CUBE and is not answered with the folder that was just deleted.
453
+ (0, listCache_js_1.listCache_get)().cache_invalidateTree((0, listCache_js_1.folderKey_spell)(cleanPath));
550
454
  if (!(await client.getFileBrowserFolderByPath(cleanPath))) {
551
455
  return (0, result_js_1.Ok)(true);
552
456
  }
@@ -562,123 +466,70 @@ class ChrisIO {
562
466
  }
563
467
  }
564
468
  /**
565
- * Moves (renames) a file in ChRIS by updating its path.
469
+ * The session's client now, bound for acting on what a proof named
470
+ * ({@link HolderClient}): every act and every question after it goes to
471
+ * that one client, and the binding says whether it is still the
472
+ * session's, which a caller asks before it changes anything.
473
+ *
474
+ * @returns The binding, or Err with the reason stacked when no client is connected.
475
+ *
476
+ * @example
477
+ * ```ts
478
+ * const acts: Result<HolderClient> = await chrisIO.holderClient_bind();
479
+ * if (acts.ok && await acts.value.current_is()) await acts.value.folder_deleteById(7);
480
+ * ```
481
+ */
482
+ async holderClient_bind() {
483
+ const client = await this.client_get();
484
+ if (client === null) {
485
+ errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
486
+ return (0, result_js_1.Err)();
487
+ }
488
+ return (0, result_js_1.Ok)(new holderClient_js_1.HolderClient(client, async () => this.client_get()));
489
+ }
490
+ /**
491
+ * Moves (renames) a file in ChRIS by updating its path, on the
492
+ * session's client ({@link fileById_move}: the current rename field
493
+ * first, the older one only when CUBE says it does not read the first).
494
+ *
566
495
  * @param fileId - The file ID.
567
496
  * @param destPath - The target path including filename.
568
- * @returns Promise resolving to true on success, false on failure.
497
+ * @param recheck - Asked before the second spelling is tried, when given:
498
+ * whether the move may still be made (the file where it was, the
499
+ * destination free). False stops the move.
500
+ * @returns Ok(true) when CUBE accepted the move; Err otherwise, which
501
+ * does not say the file stayed where it was.
502
+ *
503
+ * @example
504
+ * ```ts
505
+ * const moved: Result<boolean> = await chrisIO.file_moveById(41, '/home/ada/b.txt');
506
+ * ```
569
507
  */
570
- async file_moveById(fileId, destPath) {
508
+ async file_moveById(fileId, destPath, recheck) {
571
509
  const client = await this.client_get();
572
510
  if (!client) {
573
511
  errorStack_js_1.errorStack.stack_push("error", "ChRIS client is not initialized");
574
512
  return (0, result_js_1.Err)();
575
513
  }
576
- try {
577
- const userFile = await client.getUserFile(fileId);
578
- if (!userFile) {
579
- errorStack_js_1.errorStack.stack_push("error", `File not found with ID ${fileId}`);
580
- return (0, result_js_1.Err)();
581
- }
582
- // The rename field drifted across CUBE versions: newer servers take
583
- // `upload_path`, older ones `path` (chrisapi types neither). Try the
584
- // current name first and fall back for older CUBEs.
585
- try {
586
- await (0, adapter_js_1.resource_call)(userFile, 'put', { upload_path: destPath });
587
- }
588
- catch {
589
- await (0, adapter_js_1.resource_call)(userFile, 'put', { path: destPath });
590
- }
591
- return (0, result_js_1.Ok)(true);
592
- }
593
- catch (error) {
594
- const errorMsg = error instanceof Error ? error.message : String(error);
595
- errorStack_js_1.errorStack.stack_push("error", `Failed to move file ID ${fileId} to ${destPath}: ${errorMsg}`);
596
- return (0, result_js_1.Err)();
597
- }
514
+ return (0, holderIO_js_1.file_moveById)(client, fileId, destPath, recheck);
598
515
  }
599
516
  /**
600
- * Uploads a local directory or file to ChRIS recursively.
517
+ * Walks a local directory or file for an upload, each file handed to the
518
+ * caller's store (never posted here): {@link localPath_upload}, on the
519
+ * storage provider this IO was given.
520
+ *
601
521
  * @param localPath - The path on the local filesystem.
602
- * @param remotePath - The destination path on ChRIS. For directories, follows Unix cp semantics:
603
- * the source directory name is appended to remotePath.
604
- * @returns Promise<boolean> success status.
522
+ * @param remotePath - The destination path on ChRIS: a directory lands under it by its own name (`cp -r`).
523
+ * @param store - Stores one file's content at its ChRIS path; false (its reason stacked) when it did not.
524
+ * @param folderName - The name a directory lands under; null for its contents in the destination itself.
525
+ * @returns True when every file was stored; false otherwise (stacked).
605
526
  */
606
- async uploadLocalPath(localPath, remotePath) {
527
+ async uploadLocalPath(localPath, remotePath, store, folderName) {
607
528
  if (!this.storageProvider) {
608
529
  errorStack_js_1.errorStack.stack_push("error", "Storage provider not configured in ChrisIO.");
609
530
  return false;
610
531
  }
611
- try {
612
- const isDir = await this.storageProvider.isDirectory(localPath);
613
- if (isDir) {
614
- // For directories, follow Unix cp semantics: append source dir basename to target
615
- // e.g., upload ~/test-upload /home/user -> /home/user/test-upload/
616
- const dirBasename = this.storageProvider.basename(localPath);
617
- const targetDir = remotePath.endsWith('/')
618
- ? remotePath + dirBasename
619
- : remotePath + '/' + dirBasename;
620
- const entries = await this.storageProvider.readdir(localPath);
621
- let success = true;
622
- for (const entry of entries) {
623
- const childLocal = this.storageProvider.join(localPath, entry);
624
- const childRemote = targetDir.endsWith('/')
625
- ? targetDir + entry
626
- : targetDir + '/' + entry;
627
- const result = await this.uploadLocalPath(childLocal, childRemote);
628
- if (!result)
629
- success = false;
630
- }
631
- return success;
632
- }
633
- else {
634
- // It's a file
635
- const content = await this.storageProvider.readBinary(localPath);
636
- if (!content) {
637
- errorStack_js_1.errorStack.stack_push("error", `Failed to read local file: ${localPath}`);
638
- return false;
639
- }
640
- const blob = new Blob([content]);
641
- // Split remotePath into dir and filename
642
- // Since remote path is ChRIS path (Unix-like), we split by last '/'
643
- const lastSlashIndex = remotePath.lastIndexOf('/');
644
- let dir = "";
645
- let name = remotePath;
646
- if (lastSlashIndex !== -1) {
647
- dir = remotePath.substring(0, lastSlashIndex);
648
- name = remotePath.substring(lastSlashIndex + 1);
649
- }
650
- // If dir is empty, use root
651
- if (!dir)
652
- dir = "/";
653
- return await this.file_upload(blob, dir, name);
654
- }
655
- }
656
- catch (error) {
657
- const msg = error instanceof Error ? error.message : String(error);
658
- errorStack_js_1.errorStack.stack_push("error", `Recursive upload failed for ${localPath}: ${msg}`);
659
- return false;
660
- }
661
- }
662
- /**
663
- * Performs a dummy upload for testing purposes.
664
- * @returns A Promise resolving to true on success, or null if client is missing.
665
- */
666
- async dummy_upload() {
667
- const client = await this.client_get();
668
- if (!client) {
669
- return null;
670
- }
671
- // dummy_upload is deprecated/test logic, fixing for compilation
672
- const data = {
673
- upload_path: this.chrisFolder,
674
- };
675
- const fileContent = "This is a test file";
676
- const fileData = JSON.stringify(fileContent);
677
- const uploadFileBlob = new Blob([fileData], {
678
- type: "application/json",
679
- });
680
- const filename = "dummy.json";
681
- return await this.file_upload(uploadFileBlob, this.chrisFolder, filename);
532
+ return (0, localUpload_js_1.localPath_upload)(this.storageProvider, localPath, remotePath, store, folderName);
682
533
  }
683
534
  }
684
535
  exports.ChrisIO = ChrisIO;