@verentis/cli 0.2.29 → 0.2.31

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 CHANGED
@@ -194,7 +194,7 @@ verentis api POST /v1/things --body @thing.json --workspace <id> --scope some.sc
194
194
  verentis files ls /scripts
195
195
  verentis files cat /data/input.json
196
196
  verentis files upload ./local-dir /scripts # recursive
197
- verentis files upload build.zip /apps --extract # server-side archive extraction
197
+ verentis files upload build.zip /apps --extract # always extract server-side (even without a manifest)
198
198
  verentis files download /data/report.json
199
199
  verentis files mv /a.txt /archive/a.txt
200
200
  verentis files rm /tmp-dir --recursive
@@ -202,6 +202,28 @@ verentis files rm /tmp-dir --recursive
202
202
 
203
203
  All file commands take `--branch` (default `main`) and `--workspace`.
204
204
 
205
+ ### Archives
206
+
207
+ Folders and files with children download as an archive that carries a `.verentis-manifest.json`
208
+ (hierarchy, MIME types, path metadata, SHA-256 hashes). Uploading such an archive recreates the tree:
209
+
210
+ ```bash
211
+ verentis files download /data/x --archive -o x.zip # or --format zip|tgz
212
+ verentis files upload x.zip /data/restore # imports into /data/restore/x, waits, shows progress
213
+ verentis files upload x.zip /data/restore --conflict reject --no-wait # prints the job id
214
+ verentis files import-status <job-id> [--branch main] [--wait] [--json]
215
+ verentis files upload other.zip /data/ # zip without manifest → stored as /data/other.zip
216
+ verentis files upload x.zip /data/ --as-zip # never import; store the zip as a file
217
+ ```
218
+
219
+ - A `.zip` with a root `.verentis-manifest.json` is detected by the server and imported as a
220
+ background job (`202`); the remote path is the destination folder. The CLI polls
221
+ `GET /v1/archive-imports/{id}` (1 s, backing off to 5 s), reports `processed/total` and failures on
222
+ stderr, and exits non-zero (printing the job's errors) when the import ends `Failed` or `Cancelled`.
223
+ - `--as-zip` sends `X-Auto-Extract: false`, `--extract` sends `X-Auto-Extract: true`; without either the
224
+ header is omitted and the server auto-detects. `--conflict merge|reject` sets `X-Archive-Conflict`.
225
+ - Recursive directory uploads always store `.zip` files verbatim.
226
+
205
227
  ## Executions
206
228
 
207
229
  ```bash
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
3
+ import { mkdir, stat, readFile, writeFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
5
  import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
@@ -535,7 +535,9 @@ var files = {
535
535
  workspaceBound: true
536
536
  }),
537
537
  update: e({ method: "PUT", path: "/v1/files/{path}", scopes: [NODE.nodeUpdate, NODE.fileRead, NODE.journalCreate], workspaceBound: true }),
538
- delete: e({ method: "DELETE", path: "/v1/files/{path}", scopes: [NODE.fileDelete], workspaceBound: true })
538
+ delete: e({ method: "DELETE", path: "/v1/files/{path}", scopes: [NODE.fileDelete], workspaceBound: true }),
539
+ /** Status of a background archive import started by an archive upload (202 + Location). */
540
+ archiveImportStatus: e({ method: "GET", path: "/v1/archive-imports/{id}", scopes: [NODE.fileRead], workspaceBound: true })
539
541
  };
540
542
  var execution = {
541
543
  request: e({ method: "POST", path: "/v1/executions", scopes: [EXECUTION.run, ...ENGINE_DEFAULT_PERMISSIONS], workspaceBound: true }),
@@ -2163,21 +2165,116 @@ var normalizeRemote = (path) => {
2163
2165
  const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
2164
2166
  return trimmed;
2165
2167
  };
2168
+ var TERMINAL_IMPORT_STATES = /* @__PURE__ */ new Set(["Succeeded", "Failed", "Cancelled"]);
2169
+ var archiveImportPolling = {
2170
+ initialDelayMs: 1e3,
2171
+ maxDelayMs: 5e3,
2172
+ backoff: 1.5,
2173
+ sleep: (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms))
2174
+ };
2175
+ var isZipName = (name) => name.toLowerCase().endsWith(".zip");
2166
2176
  async function uploadWithHeaders(api, workspaceId, remotePath, localPath, options) {
2167
2177
  const buffer = await readFile(localPath);
2178
+ const contentType = options.contentType ?? (isZipName(localPath) ? "application/zip" : "application/octet-stream");
2168
2179
  const form = new FormData();
2169
- form.append("file", new Blob([buffer], { type: options.contentType ?? "application/octet-stream" }), basename(localPath));
2180
+ form.append("file", new Blob([buffer], { type: contentType }), basename(localPath));
2170
2181
  form.append("metadata", JSON.stringify({ branch: options.branch, contentType: options.contentType }));
2182
+ const headers = {};
2183
+ if (options.autoExtract !== void 0) headers["X-Auto-Extract"] = String(options.autoExtract);
2184
+ if (options.conflict) headers["X-Archive-Conflict"] = options.conflict;
2171
2185
  const res = await api.requestRaw("POST", fillPath(files.upload.path, { path: normalizeRemote(remotePath) }), {
2172
2186
  scopes: [...files.upload.scopes],
2173
2187
  tokenWorkspaceId: workspaceId,
2174
2188
  rawBody: form,
2175
- headers: {
2176
- ...options.autoExtract ? { "X-Auto-Extract": "true" } : {}
2177
- }
2189
+ headers
2178
2190
  });
2179
- return await res.json();
2191
+ const text = await res.text().catch(() => "");
2192
+ let body;
2193
+ try {
2194
+ body = text ? unwrap(JSON.parse(text)) : void 0;
2195
+ } catch {
2196
+ body = text;
2197
+ }
2198
+ return { status: res.status, location: res.headers?.get("Location") ?? void 0, body };
2199
+ }
2200
+ function zipHasRootManifest(buffer) {
2201
+ const EOCD = 101010256;
2202
+ const CDH = 33639248;
2203
+ const minStart = Math.max(0, buffer.length - 22 - 65535);
2204
+ for (let i = buffer.length - 22; i >= minStart; i--) {
2205
+ if (buffer.readUInt32LE(i) !== EOCD) continue;
2206
+ let offset = buffer.readUInt32LE(i + 16);
2207
+ if (offset === 4294967295 || offset >= buffer.length) return void 0;
2208
+ while (offset + 46 <= buffer.length && buffer.readUInt32LE(offset) === CDH) {
2209
+ const nameLength = buffer.readUInt16LE(offset + 28);
2210
+ const extraLength = buffer.readUInt16LE(offset + 30);
2211
+ const commentLength = buffer.readUInt16LE(offset + 32);
2212
+ const name = buffer.subarray(offset + 46, offset + 46 + nameLength).toString("utf8");
2213
+ if (name === ".verentis-manifest.json" || name === "./.verentis-manifest.json") return true;
2214
+ offset += 46 + nameLength + extraLength + commentLength;
2215
+ }
2216
+ return false;
2217
+ }
2218
+ return void 0;
2219
+ }
2220
+ var importJobId = (upload) => {
2221
+ const body = upload.body;
2222
+ if (body && typeof body === "object" && typeof body.id === "string") return body.id;
2223
+ const match = upload.location?.match(/archive-imports\/([^/?#]+)/);
2224
+ return match ? decodeURIComponent(match[1]) : void 0;
2225
+ };
2226
+ async function getImportStatus(api, workspaceId, id, branch) {
2227
+ return call(api, files.archiveImportStatus, { params: { id }, workspaceId, query: { branch } });
2228
+ }
2229
+ var progressLine = (status) => {
2230
+ const total = status.total ?? "?";
2231
+ const parts = [`${status.state}`, `${status.processed ?? 0}/${total}`];
2232
+ if (status.skipped) parts.push(`skipped ${status.skipped}`);
2233
+ if (status.failed) parts.push(`failed ${status.failed}`);
2234
+ return `Archive import ${status.id}: ${parts.join(", ")}`;
2235
+ };
2236
+ async function waitForArchiveImport(api, workspaceId, id, branch, initial) {
2237
+ const tty = Boolean(process.stderr.isTTY);
2238
+ let status = initial;
2239
+ let delay = archiveImportPolling.initialDelayMs;
2240
+ let lastLine = "";
2241
+ for (; ; ) {
2242
+ if (status) {
2243
+ const line = progressLine(status);
2244
+ if (line !== lastLine) {
2245
+ process.stderr.write(tty ? `\r\x1B[2K${line}` : `${line}
2246
+ `);
2247
+ lastLine = line;
2248
+ }
2249
+ if (TERMINAL_IMPORT_STATES.has(status.state)) break;
2250
+ await archiveImportPolling.sleep(delay);
2251
+ delay = Math.min(archiveImportPolling.maxDelayMs, Math.round(delay * archiveImportPolling.backoff));
2252
+ }
2253
+ status = await getImportStatus(api, workspaceId, id, branch);
2254
+ }
2255
+ if (tty && lastLine) process.stderr.write("\n");
2256
+ return status;
2257
+ }
2258
+ function reportImport(status, options) {
2259
+ if (options.json) printJson(status);
2260
+ else {
2261
+ const root = status.rootPath ?? status.targetPath;
2262
+ console.log(`Archive import ${status.id} ${status.state}${root ? ` \u2192 ${root}` : ""}: ${status.processed ?? 0}/${status.total ?? "?"} processed, ${status.skipped ?? 0} skipped, ${status.failed ?? 0} failed.`);
2263
+ }
2264
+ if (status.errors?.length) {
2265
+ console.error("Errors:");
2266
+ for (const err of status.errors) console.error(` ${err.path ? `${err.path}: ` : ""}${err.message}`);
2267
+ }
2268
+ if (status.state === "Failed" || status.state === "Cancelled") process.exitCode = 1;
2180
2269
  }
2270
+ var ARCHIVE_FORMATS = { zip: "Zip", tgz: "Tgz", targz: "Tgz", "tar.gz": "Tgz" };
2271
+ function parseArchiveFormat(value) {
2272
+ if (value === void 0) return void 0;
2273
+ const format = ARCHIVE_FORMATS[value.toLowerCase()];
2274
+ if (!format) throw new Error(`Unknown archive format '${value}'. Use zip or tgz.`);
2275
+ return format;
2276
+ }
2277
+ var CONFLICT_POLICIES = /* @__PURE__ */ new Set(["merge", "reject"]);
2181
2278
  function registerFiles(program2) {
2182
2279
  const filesCmd = program2.command("files").description("Work with workspace files (the VFS)");
2183
2280
  filesCmd.command("ls [path]").description("List a directory in the workspace").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--json", "output JSON").action(async (path, options) => {
@@ -2206,7 +2303,8 @@ function registerFiles(program2) {
2206
2303
  const result = await call(api, files.get, {
2207
2304
  params: { path: normalizeRemote(path) },
2208
2305
  workspaceId,
2209
- query: { branch: options.branch }
2306
+ // The Node files endpoint requires paging for its children listing; stat discards children.
2307
+ query: { branch: options.branch, PageNo: 1, PageSize: 1 }
2210
2308
  });
2211
2309
  const { children, ...rest } = result;
2212
2310
  outputRecord(rest, options);
@@ -2222,39 +2320,92 @@ function registerFiles(program2) {
2222
2320
  if (!res.body) return;
2223
2321
  await pipeline(Readable.fromWeb(res.body), process.stdout, { end: false });
2224
2322
  });
2225
- filesCmd.command("download <remotePath> [localPath]").description("Download a file (or directory as an archive with --format)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--format <format>", "archive format for directories: Zip | TarGz").action(async (remotePath, localPath, options) => {
2323
+ filesCmd.command("download <remotePath> [localPath]").description("Download a file, or a folder / file with children as an archive (--archive or --format)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--archive", "download as an archive (with .verentis-manifest.json); also for files with children").option("--format <format>", "archive format: zip | tgz (implies --archive; default zip)").option("-o, --output <file>", "local output file (same as [localPath])").action(async (remotePath, localPath, options) => {
2324
+ const format = parseArchiveFormat(options.format) ?? (options.archive ? "Zip" : void 0);
2226
2325
  const workspaceId = await resolveWorkspaceId(options);
2227
2326
  const api = await createApiClient();
2228
2327
  const res = await callRaw(api, files.raw, {
2229
2328
  params: { path: normalizeRemote(remotePath) },
2230
2329
  workspaceId,
2231
- query: { branch: options.branch, format: options.format }
2330
+ query: { branch: options.branch, format }
2232
2331
  });
2233
- const suffix = options.format === "Zip" ? ".zip" : options.format === "TarGz" ? ".tar.gz" : "";
2234
- const out = resolve(localPath ?? `${basename(normalizeRemote(remotePath)) || "download"}${suffix}`);
2332
+ const suffix = format === "Zip" ? ".zip" : format === "Tgz" ? ".tar.gz" : "";
2333
+ const out = resolve(options.output ?? localPath ?? `${basename(normalizeRemote(remotePath)) || "download"}${suffix}`);
2235
2334
  if (!res.body) throw new Error("Empty response.");
2236
2335
  await mkdir(dirname(out), { recursive: true });
2237
2336
  await pipeline(Readable.fromWeb(res.body), createWriteStream(out));
2238
2337
  console.log(`Downloaded ${remotePath} \u2192 ${out}`);
2239
2338
  });
2240
- filesCmd.command("upload <localPath> [remotePath]").description("Upload a file or directory (directories upload file-by-file)").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--content-type <type>", "content type for a single-file upload").option("--extract", "archive uploads: extract server-side into the target directory (X-Auto-Extract)").action(async (localPath, remotePath, options) => {
2339
+ filesCmd.command("upload <localPath> [remotePath]").description(
2340
+ "Upload a file or directory (directories upload file-by-file). A .zip with a root .verentis-manifest.json is imported as an archive under [remotePath] (a background job); other zips are stored as-is."
2341
+ ).option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--content-type <type>", "content type for a single-file upload").option("--extract", "always extract archives server-side, even without a manifest (X-Auto-Extract: true)").option("--as-zip", "store the zip as a plain file, never import/extract it (X-Auto-Extract: false)").option("--conflict <policy>", "archive import conflict policy: merge | reject (X-Archive-Conflict)").option("--no-wait", "archive imports: print the job id and return without waiting").option("--json", "output JSON").action(
2342
+ async (localPath, remotePath, options) => {
2343
+ if (options.extract && options.asZip) throw new Error("--extract and --as-zip are mutually exclusive.");
2344
+ const conflict = options.conflict?.toLowerCase();
2345
+ if (conflict && !CONFLICT_POLICIES.has(conflict)) throw new Error(`Unknown conflict policy '${options.conflict}'. Use merge or reject.`);
2346
+ const workspaceId = await resolveWorkspaceId(options);
2347
+ const api = await createApiClient();
2348
+ const local = resolve(localPath);
2349
+ const info = await stat(local);
2350
+ if (info.isDirectory()) {
2351
+ const remoteBase = normalizeRemote(remotePath ?? basename(local));
2352
+ const uploaded = await uploadDirectory(api, workspaceId, local, remoteBase, options.branch);
2353
+ console.log(`Uploaded ${uploaded} file(s) to /${remoteBase}.`);
2354
+ return;
2355
+ }
2356
+ const autoExtract = options.extract ? true : options.asZip ? false : void 0;
2357
+ const asFolder = autoExtract === true || autoExtract === void 0 && isZipName(local) && zipHasRootManifest(await readFile(local)) === true;
2358
+ const remote = asFolder ? normalizeRemote(remotePath ?? "/") : remotePath && remotePath.endsWith("/") ? posix.join(normalizeRemote(remotePath), basename(local)) : normalizeRemote(remotePath ?? basename(local));
2359
+ const result = await uploadWithHeaders(api, workspaceId, remote, local, {
2360
+ branch: options.branch,
2361
+ contentType: options.contentType,
2362
+ autoExtract,
2363
+ conflict
2364
+ });
2365
+ if (result.status === 202) {
2366
+ const id = importJobId(result);
2367
+ if (!id) throw new Error("The server accepted the archive import but returned no job id.");
2368
+ const accepted = result.body && typeof result.body === "object" ? result.body : void 0;
2369
+ if (!options.wait) {
2370
+ if (options.json) printJson(accepted ?? { id });
2371
+ else console.log(`Archive import started: ${id}
2372
+ Check progress with: verentis files import-status ${id} --branch ${options.branch}`);
2373
+ return;
2374
+ }
2375
+ if (!options.json) console.error(`Archive import started: ${id}`);
2376
+ const final = await waitForArchiveImport(api, workspaceId, id, options.branch, accepted?.state ? accepted : void 0);
2377
+ reportImport(final, options);
2378
+ return;
2379
+ }
2380
+ if (options.json) {
2381
+ printJson(result.body);
2382
+ return;
2383
+ }
2384
+ if (Array.isArray(result.body)) {
2385
+ console.log(`Uploaded ${localPath} \u2192 /${remote} (extracted ${result.body.length} file(s))`);
2386
+ return;
2387
+ }
2388
+ console.log(`Uploaded ${localPath} \u2192 /${result.body?.path ?? remote}`);
2389
+ }
2390
+ );
2391
+ filesCmd.command("import-status <id>").description("Show the status of an archive import job").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--wait", "poll until the import finishes").option("--json", "output JSON").action(async (id, options) => {
2241
2392
  const workspaceId = await resolveWorkspaceId(options);
2242
2393
  const api = await createApiClient();
2243
- const local = resolve(localPath);
2244
- const info = await stat(local);
2245
- if (info.isDirectory()) {
2246
- const remoteBase = normalizeRemote(remotePath ?? basename(local));
2247
- const uploaded = await uploadDirectory(api, workspaceId, local, remoteBase, options.branch);
2248
- console.log(`Uploaded ${uploaded} file(s) to /${remoteBase}.`);
2394
+ if (options.wait) {
2395
+ reportImport(await waitForArchiveImport(api, workspaceId, id, options.branch), options);
2249
2396
  return;
2250
2397
  }
2251
- const remote = remotePath && remotePath.endsWith("/") ? posix.join(normalizeRemote(remotePath), basename(local)) : normalizeRemote(remotePath ?? basename(local));
2252
- const result = await uploadWithHeaders(api, workspaceId, remote, local, {
2253
- branch: options.branch,
2254
- contentType: options.contentType,
2255
- autoExtract: options.extract
2256
- });
2257
- console.log(`Uploaded ${localPath} \u2192 /${result.path ?? remote}`);
2398
+ const status = await getImportStatus(api, workspaceId, id, options.branch);
2399
+ const { errors, ...rest } = status;
2400
+ if (options.json) printJson(status);
2401
+ else {
2402
+ outputRecord(rest, options);
2403
+ if (errors?.length) {
2404
+ console.log("errors:");
2405
+ for (const err of errors) console.log(` ${err.path ? `${err.path}: ` : ""}${err.message}`);
2406
+ }
2407
+ }
2408
+ if (status.state === "Failed" || status.state === "Cancelled") process.exitCode = 1;
2258
2409
  });
2259
2410
  filesCmd.command("rm <path>").description("Delete a file or directory").option("--workspace <workspaceId>").option("--branch <branch>", "workspace branch", "main").option("--recursive", "delete directory contents recursively").action(async (path, options) => {
2260
2411
  const workspaceId = await resolveWorkspaceId(options);
@@ -2288,7 +2439,7 @@ async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2288
2439
  if (entry.isDirectory()) {
2289
2440
  count += await uploadDirectory(api, workspaceId, localEntry, remoteEntry, branch);
2290
2441
  } else if (entry.isFile()) {
2291
- await uploadWithHeaders(api, workspaceId, remoteEntry, localEntry, { branch });
2442
+ await uploadWithHeaders(api, workspaceId, remoteEntry, localEntry, { branch, autoExtract: isZipName(entry.name) ? false : void 0 });
2292
2443
  console.log(` /${remoteEntry}`);
2293
2444
  count += 1;
2294
2445
  }