@foleo/cli 0.1.45 → 0.1.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ export declare const MEMBERS_HELP = "Usage: foleo members [ls] [--workspace <handle>] [--json]\n foleo members invite <email\u2026> [--role owner|edit|view] [--workspace <handle>] [--json]\n foleo members role <email> <owner|edit|view> [--yes] [--workspace <handle>] [--json]\n foleo members remove <email> [--yes] [--workspace <handle>] [--json]\n foleo members leave [--yes] [--workspace <handle>] [--json]\n foleo invites [ls|resend <id>|revoke <id>] [--yes] [--workspace <handle>] [--json]\nSign in with foleo login --workspace <handle> --allow-workspaces and select the requested permissions.\nInvites are drafts: the Owner must open approvalUrl and confirm in Foleo before mail is sent.\nResend sends email and rotates the link. Role changes revoke the member's bound credentials.\nRemove, leave, role changes, resend and revoke require confirmation; --yes confirms explicitly.\nA login stays bound to one workspace; use foleo login --workspace <handle> to change it.\n";
2
+ type Deps = {
3
+ request<T>(path: string, method: "GET" | "POST" | "PATCH" | "DELETE", body?: unknown): Promise<T>;
4
+ workspace(): Promise<string>;
5
+ stdout(s: string): void;
6
+ confirm?(message: string): Promise<boolean>;
7
+ };
8
+ export declare function membersCommand(command: "members" | "invites", args: string[], deps: Deps): Promise<number>;
9
+ export {};
10
+ //# sourceMappingURL=members.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"members.d.ts","sourceRoot":"","sources":["../src/members.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,YAAY,68BAWxB,CAAC;AAQF,KAAK,IAAI,GAAG;IACV,OAAO,CAAC,CAAC,EACP,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,QAAQ,EAC3C,IAAI,CAAC,EAAE,OAAO,GACb,OAAO,CAAC,CAAC,CAAC,CAAC;IACd,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC7C,CAAC;AAeF,wBAAsB,cAAc,CAClC,OAAO,EAAE,SAAS,GAAG,SAAS,EAC9B,IAAI,EAAE,MAAM,EAAE,EACd,IAAI,EAAE,IAAI,GACT,OAAO,CAAC,MAAM,CAAC,CAiIjB"}
@@ -0,0 +1,129 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { LocalError, UsageError } from "./errors.js";
3
+ export const MEMBERS_HELP = `Usage: foleo members [ls] [--workspace <handle>] [--json]
4
+ foleo members invite <email…> [--role owner|edit|view] [--workspace <handle>] [--json]
5
+ foleo members role <email> <owner|edit|view> [--yes] [--workspace <handle>] [--json]
6
+ foleo members remove <email> [--yes] [--workspace <handle>] [--json]
7
+ foleo members leave [--yes] [--workspace <handle>] [--json]
8
+ foleo invites [ls|resend <id>|revoke <id>] [--yes] [--workspace <handle>] [--json]
9
+ Sign in with foleo login --workspace <handle> --allow-workspaces and select the requested permissions.
10
+ Invites are drafts: the Owner must open approvalUrl and confirm in Foleo before mail is sent.
11
+ Resend sends email and rotates the link. Role changes revoke the member's bound credentials.
12
+ Remove, leave, role changes, resend and revoke require confirmation; --yes confirms explicitly.
13
+ A login stays bound to one workspace; use foleo login --workspace <handle> to change it.
14
+ `;
15
+ const roles = {
16
+ owner: "owner",
17
+ edit: "publisher",
18
+ view: "viewer",
19
+ };
20
+ async function confirm(message) {
21
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
22
+ return false;
23
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
24
+ try {
25
+ return /^y(?:es)?$/iu.test((await rl.question(`${message} [y/N] `)).trim());
26
+ }
27
+ finally {
28
+ rl.close();
29
+ }
30
+ }
31
+ export async function membersCommand(command, args, deps) {
32
+ if (args.includes("--help") || args.includes("-h")) {
33
+ deps.stdout(MEMBERS_HELP);
34
+ return 0;
35
+ }
36
+ const positional = [];
37
+ let role = "view";
38
+ let seenRole = false;
39
+ for (let i = 0; i < args.length; i++) {
40
+ const arg = args[i];
41
+ if (["--json", "--yes"].includes(arg))
42
+ continue;
43
+ if (arg === "--role" && !seenRole) {
44
+ seenRole = true;
45
+ role = args[++i] ?? "";
46
+ }
47
+ else if (arg.startsWith("--"))
48
+ throw new UsageError(MEMBERS_HELP);
49
+ else
50
+ positional.push(arg);
51
+ }
52
+ const [action = "ls", ...values] = positional;
53
+ if (command === "members"
54
+ ? !["ls", "invite", "role", "remove", "leave"].includes(action) ||
55
+ (action === "ls" || action === "leave"
56
+ ? values.length !== 0
57
+ : action === "invite"
58
+ ? values.length < 1 ||
59
+ values.length > 10 ||
60
+ !["owner", "edit", "view"].includes(role)
61
+ : values.length !== (action === "role" ? 2 : 1)) ||
62
+ (action === "role" && !roles[values[1]]) ||
63
+ (seenRole && action !== "invite")
64
+ : !["ls", "resend", "revoke"].includes(action) ||
65
+ values.length !== (action === "ls" ? 0 : 1) ||
66
+ seenRole)
67
+ throw new UsageError(MEMBERS_HELP);
68
+ if (command === "members" &&
69
+ ["invite", "role", "remove"].includes(action) &&
70
+ (action === "invite" ? values : values.slice(0, 1)).some((email) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email)))
71
+ throw new UsageError("Supply a valid member email address.");
72
+ if (command === "invites" &&
73
+ action !== "ls" &&
74
+ !/^[a-f0-9-]{36}$/u.test(values[0]))
75
+ throw new UsageError("Supply an invite ID from foleo invites ls.");
76
+ const handle = await deps.workspace();
77
+ const base = `/me/workspaces/${encodeURIComponent(handle)}`;
78
+ const destructive = ["role", "remove", "leave", "resend", "revoke"].includes(action);
79
+ if (destructive &&
80
+ !args.includes("--yes") &&
81
+ !(await (deps.confirm ?? confirm)(`${action} ${values.join(" ")} in ${handle}?`)))
82
+ throw new LocalError("confirmation_required", "Action not confirmed.", {
83
+ next: "Review the target, then rerun with --yes or confirm at an interactive terminal.",
84
+ });
85
+ const allMembers = async () => {
86
+ const members = [];
87
+ let cursor = null;
88
+ const cursors = new Set();
89
+ do {
90
+ const page = await deps.request(`${base}/members${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`, "GET");
91
+ members.push(...page.members);
92
+ cursor = page.nextCursor;
93
+ if (cursor && cursors.has(cursor))
94
+ throw new LocalError("invalid_cursor", "Server repeated a member cursor.");
95
+ if (cursor)
96
+ cursors.add(cursor);
97
+ } while (cursor);
98
+ return members;
99
+ };
100
+ let result;
101
+ if (action === "ls")
102
+ result =
103
+ command === "members"
104
+ ? { members: await allMembers() }
105
+ : await deps.request(`${base}/invites`, "GET");
106
+ else if (action === "invite")
107
+ result = await deps.request(`${base}/invites`, "POST", {
108
+ emails: [...new Set(values.map((e) => e.toLowerCase()))],
109
+ role: roles[role],
110
+ });
111
+ else if (command === "invites")
112
+ result = await deps.request(`${base}/invites/${encodeURIComponent(values[0])}${action === "resend" ? "/resend" : ""}`, action === "resend" ? "POST" : "DELETE");
113
+ else if (action === "leave")
114
+ result = await deps.request(`${base}/members/me`, "DELETE");
115
+ else {
116
+ const member = (await allMembers()).find((m) => m.email.toLowerCase() === values[0].toLowerCase());
117
+ if (!member)
118
+ throw new LocalError("member_not_found", "No member with that email in this workspace.", { next: "Run foleo members ls to inspect current members." });
119
+ result = await deps.request(`${base}/members/${encodeURIComponent(member.userId)}`, action === "role" ? "PATCH" : "DELETE", action === "role" ? { role: roles[values[1]] } : undefined);
120
+ }
121
+ deps.stdout(JSON.stringify(result, null, 2) + "\n");
122
+ if (!args.includes("--json") &&
123
+ typeof result === "object" &&
124
+ result &&
125
+ "approvalUrl" in result)
126
+ deps.stdout(`Open ${String(result.approvalUrl)} and confirm in Foleo. No email has been sent.\n`);
127
+ return 0;
128
+ }
129
+ //# sourceMappingURL=members.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"members.js","sourceRoot":"","sources":["../src/members.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,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AC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EACtC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAC5D,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;IACpD,IACE,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACxB,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM;QACN,aAAa,IAAI,MAAM;QAEvB,IAAI,CAAC,MAAM,CACT,QAAQ,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,kDAAkD,CACrF,CAAC;IACJ,OAAO,CAAC,CAAC;AACX,CAAC"}
package/dist/move.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export declare const MOVE_HELP = "Usage: foleo mv <path> --to-workspace <handle> [--to <folder>] [--mutation-id <id>] [--yes] [--json]\n foleo mv --resume <move-id> [--source-tree <id>] [--yes] [--json]\n foleo mv --cancel <move-id> [--source-tree <id>] [--yes] [--json]\nCopies a file or folder to another workspace and trashes the source. You must be Owner or Can edit in both.\nCharges destination quota; old links forward except when Restricted. Your login stays bound to the source.\nConfirm with the person before --yes. At most 200 items / 256 MiB; interrupted jobs can be resumed.\nBefore handoff, an Owner/admin of either workspace can cancel. After copying, a destination Owner/admin can resume with the original --source-tree.\n";
2
+ type Deps = {
3
+ request<T>(path: string, method: "GET" | "POST", body?: unknown): Promise<T>;
4
+ stdout(s: string): void;
5
+ stderr?(s: string): void;
6
+ confirm?(message: string): Promise<boolean>;
7
+ sleep?(ms: number): Promise<void>;
8
+ };
9
+ export declare function moveCommand(args: string[], deps: Deps): Promise<number>;
10
+ export {};
11
+ //# sourceMappingURL=move.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"move.d.ts","sourceRoot":"","sources":["../src/move.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,SAAS,ktBAOrB,CAAC;AAUF,KAAK,IAAI,GAAG;IACV,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAC7E,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5C,KAAK,CAAC,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnC,CAAC;AAUF,wBAAsB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,mBAsK3D"}
package/dist/move.js ADDED
@@ -0,0 +1,149 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { checkedCloudPath } from "./path-workspace.js";
4
+ import { FoleoError, LocalError, UsageError } from "./errors.js";
5
+ export const MOVE_HELP = `Usage: foleo mv <path> --to-workspace <handle> [--to <folder>] [--mutation-id <id>] [--yes] [--json]
6
+ foleo mv --resume <move-id> [--source-tree <id>] [--yes] [--json]
7
+ foleo mv --cancel <move-id> [--source-tree <id>] [--yes] [--json]
8
+ Copies a file or folder to another workspace and trashes the source. You must be Owner or Can edit in both.
9
+ Charges destination quota; old links forward except when Restricted. Your login stays bound to the source.
10
+ Confirm with the person before --yes. At most 200 items / 256 MiB; interrupted jobs can be resumed.
11
+ Before handoff, an Owner/admin of either workspace can cancel. After copying, a destination Owner/admin can resume with the original --source-tree.
12
+ `;
13
+ async function confirm(message) {
14
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
15
+ return false;
16
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
17
+ try {
18
+ return /^y(?:es)?$/iu.test((await rl.question(`${message} [y/N] `)).trim());
19
+ }
20
+ finally {
21
+ rl.close();
22
+ }
23
+ }
24
+ export async function moveCommand(args, deps) {
25
+ if (args.includes("--help") || args.includes("-h")) {
26
+ deps.stdout(MOVE_HELP);
27
+ return 0;
28
+ }
29
+ const flags = new Map(), paths = [];
30
+ for (let n = 0; n < args.length; n++) {
31
+ const a = args[n];
32
+ if (["--yes", "--json"].includes(a))
33
+ continue;
34
+ if (a.startsWith("--")) {
35
+ if (![
36
+ "--to-workspace",
37
+ "--to",
38
+ "--mutation-id",
39
+ "--resume",
40
+ "--cancel",
41
+ "--source-tree",
42
+ ].includes(a) ||
43
+ !args[n + 1] ||
44
+ flags.has(a))
45
+ throw new UsageError(MOVE_HELP);
46
+ flags.set(a, args[++n]);
47
+ }
48
+ else
49
+ paths.push(a);
50
+ }
51
+ const cancel = flags.get("--cancel"), resume = flags.get("--resume") ?? cancel, target = flags.get("--to-workspace"), path = paths[0];
52
+ if (resume
53
+ ? paths.length !== 0 ||
54
+ flags.size !== (flags.has("--source-tree") ? 2 : 1) ||
55
+ !/^[a-f0-9-]{36}$/u.test(resume)
56
+ : flags.has("--source-tree") ||
57
+ paths.length !== 1 ||
58
+ !target ||
59
+ !/^[a-z0-9-]{1,63}$/u.test(target))
60
+ throw new UsageError(MOVE_HELP);
61
+ if (flags.has("--source-tree") &&
62
+ !/^[a-f0-9-]{36}$/u.test(flags.get("--source-tree")))
63
+ throw new UsageError(MOVE_HELP);
64
+ if (path)
65
+ checkedCloudPath(path);
66
+ checkedCloudPath(flags.get("--to") ?? "/", true);
67
+ const mutationId = flags.get("--mutation-id") ?? randomUUID();
68
+ if (!/^[a-zA-Z0-9_-]{1,128}$/u.test(mutationId))
69
+ throw new UsageError("Invalid --mutation-id.");
70
+ if (!args.includes("--yes") &&
71
+ !(await (deps.confirm ?? confirm)(cancel
72
+ ? `Cancel move ${cancel} and delete its destination copies?`
73
+ : resume
74
+ ? `Resume move ${resume}?`
75
+ : `Move ${path} to ${target}:${flags.get("--to") ?? "/"} and trash the source?`)))
76
+ throw new LocalError("confirmation_required", "Move not confirmed.", {
77
+ next: "Review both workspaces and rerun with --yes or confirm in a terminal.",
78
+ });
79
+ const trees = await deps.request("/workspaces", "GET");
80
+ const tree = flags.get("--source-tree") ?? trees.workspaces[0]?.id;
81
+ if (!tree)
82
+ throw new LocalError("workspace_missing", "Open the source workspace first.");
83
+ let receipt;
84
+ try {
85
+ const base = `/workspaces/${tree}/moves`;
86
+ if (cancel) {
87
+ let result = await deps.request(`${base}/${cancel}/cancel`, "POST", {});
88
+ for (let n = 0; result.status !== "cancelled" && n < 650; n++) {
89
+ await (deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(result.pollAfterMs || 500, 2000));
90
+ result = await deps.request(`${base}/${cancel}/cancel`, "POST", {});
91
+ }
92
+ if (result.status !== "cancelled")
93
+ throw new LocalError("move_pending", "Cancellation is still running.");
94
+ deps.stdout(args.includes("--json")
95
+ ? JSON.stringify(result) + "\n"
96
+ : `Cancelled move ${result.id}.\n`);
97
+ return 0;
98
+ }
99
+ if (!resume)
100
+ deps.stderr?.(`Move retry key: --mutation-id ${mutationId}\n`);
101
+ receipt = resume
102
+ ? await deps.request(`${base}/${resume}`, "GET")
103
+ : await deps.request(base, "POST", {
104
+ path,
105
+ toWorkspace: target,
106
+ to: flags.get("--to") ?? "/",
107
+ clientMutationId: mutationId,
108
+ });
109
+ if (receipt.status !== "completed" || receipt.cleanupPending)
110
+ deps.stderr?.(`Move started. Resume after interruption: foleo mv --resume ${receipt.id} --yes\n`);
111
+ if (receipt.status === "cancelled" || receipt.status === "cancelling")
112
+ throw new LocalError("move_cancelled", "This move was cancelled.");
113
+ for (let n = 0; (receipt.status !== "completed" || receipt.cleanupPending) && n < 650; n++) {
114
+ await (deps.sleep ??
115
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(Math.min(receipt.pollAfterMs || 500, 2000));
116
+ receipt = await deps.request(`${base}/${receipt.id}/continue`, "POST", {});
117
+ }
118
+ if (receipt.status !== "completed" || receipt.cleanupPending)
119
+ throw new LocalError("move_pending", "The move is still running.");
120
+ deps.stdout(args.includes("--json")
121
+ ? JSON.stringify(receipt) + "\n"
122
+ : `Moved to workspace item ${receipt.destinationItemId}. Old shared links forward while link or public.\n`);
123
+ return 0;
124
+ }
125
+ catch (e) {
126
+ const next = cancel
127
+ ? `Retry with foleo mv --cancel ${cancel}${flags.has("--source-tree") ? " --source-tree " + flags.get("--source-tree") : ""} --yes.`
128
+ : receipt
129
+ ? `Resume with foleo mv --resume ${receipt.id} --yes.`
130
+ : `Retry the same move with --mutation-id ${mutationId}.`;
131
+ throw new FoleoError({
132
+ code: e instanceof FoleoError ? e.code : "move_interrupted",
133
+ message: e instanceof Error ? e.message : "Move interrupted.",
134
+ retryable: e instanceof FoleoError
135
+ ? e.retryable || e.code === "move_pending"
136
+ : true,
137
+ next,
138
+ context: {
139
+ clientMutationId: mutationId,
140
+ ...(cancel
141
+ ? { moveId: cancel }
142
+ : receipt
143
+ ? { moveId: receipt.id }
144
+ : {}),
145
+ },
146
+ });
147
+ }
148
+ }
149
+ //# sourceMappingURL=move.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"move.js","sourceRoot":"","sources":["../src/move.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjE,MAAM,CAAC,MAAM,SAAS,GAAG;;;;;;;CAOxB,CAAC;AAiBF,KAAK,UAAU,OAAO,CAAC,OAAe;IACpC,IAAI,CAAC,OAAO,C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oDAAoD,CAC7G,CAAC;QACF,OAAO,CAAC,CAAC;IACX,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,IAAI,GAAG,MAAM;YACjB,CAAC,CAAC,gCAAgC,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,iBAAiB,GAAG,KAAK,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS;YACpI,CAAC,CAAC,OAAO;gBACP,CAAC,CAAC,iCAAiC,OAAO,CAAC,EAAE,SAAS;gBACtD,CAAC,CAAC,0CAA0C,UAAU,GAAG,CAAC;QAC9D,MAAM,IAAI,UAAU,CAAC;YACnB,IAAI,EAAE,CAAC,YAAY,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB;YAC3D,OAAO,EAAE,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,mBAAmB;YAC7D,SAAS,EACP,CAAC,YAAY,UAAU;gBACrB,CAAC,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,IAAI,KAAK,cAAc;gBAC1C,CAAC,CAAC,IAAI;YACV,IAAI;YACJ,OAAO,EAAE;gBACP,gBAAgB,EAAE,UAAU;gBAC5B,GAAG,CAAC,MAAM;oBACR,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE;oBACpB,CAAC,CAAC,OAAO;wBACP,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,EAAE;wBACxB,CAAC,CAAC,EAAE,CAAC;aACV;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC"}
@@ -0,0 +1,12 @@
1
+ import { CliEditContext } from "./edit-context.js";
2
+ export declare const PATH_WORKSPACE_HELP = "Foleo cloud files:\n foleo save <path> [--file <local-file> | --text-stdin] [--kind folder] [--session <job>] [--workspace <handle|tree-id>] [--json]\n foleo read <path> [--session <job>] [--workspace <handle|tree-id>] [--json]\n foleo share <path> --access restricted|link|public [--password-stdin] [--acknowledge-access-widening] [--workspace <handle|tree-id>] [--json]\n foleo ls [path] [--workspace <handle|tree-id>] [--limit <1-100>] [--cursor <ref>] [--json]\nPaths name cloud files. --file explicitly names a local input; otherwise save reads stdin.\nText is exact UTF-8 up to 64 KiB. Large/binary: foleo workspace put/read (advanced).\nSave creates Private files and parents; preserves sharing. Read before replacing.\nCoalesce intermediate local edits into one save per complete change.\nProcesses sharing --session (default: default) are one serialized editing lane.\nIndependent jobs must choose distinct --session names. Contexts expire after 24h idle.\n";
3
+ export declare function checkedCloudPath(path: string, root?: boolean): void;
4
+ type Deps = {
5
+ request(path: string, init?: RequestInit): Promise<Response>;
6
+ stdout(s: string): void;
7
+ readStdin(): Promise<string>;
8
+ state: CliEditContext;
9
+ };
10
+ export declare function pathWorkspaceCommand(command: string, args: string[], deps: Deps): Promise<0 | 1>;
11
+ export {};
12
+ //# sourceMappingURL=path-workspace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path-workspace.d.ts","sourceRoot":"","sources":["../src/path-workspace.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnD,eAAO,MAAM,mBAAmB,+8BAW/B,CAAC;AACF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,UAAQ,QA0B1D;AACD,KAAK,IAAI,GAAG;IACV,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC7D,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,KAAK,EAAE,cAAc,CAAC;CACvB,CAAC;AACF,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,IAAI,EAAE,IAAI,kBAoRX"}
@@ -0,0 +1,278 @@
1
+ import { createHash, pbkdf2Sync } from "node:crypto";
2
+ import { CliEditContext } from "./edit-context.js";
3
+ import { FoleoError, UsageError } from "./errors.js";
4
+ import { captureFile, secretFileName } from "./workspaces.js";
5
+ export const PATH_WORKSPACE_HELP = `Foleo cloud files:
6
+ foleo save <path> [--file <local-file> | --text-stdin] [--kind folder] [--session <job>] [--workspace <handle|tree-id>] [--json]
7
+ foleo read <path> [--session <job>] [--workspace <handle|tree-id>] [--json]
8
+ foleo share <path> --access restricted|link|public [--password-stdin] [--acknowledge-access-widening] [--workspace <handle|tree-id>] [--json]
9
+ foleo ls [path] [--workspace <handle|tree-id>] [--limit <1-100>] [--cursor <ref>] [--json]
10
+ Paths name cloud files. --file explicitly names a local input; otherwise save reads stdin.
11
+ Text is exact UTF-8 up to 64 KiB. Large/binary: foleo workspace put/read (advanced).
12
+ Save creates Private files and parents; preserves sharing. Read before replacing.
13
+ Coalesce intermediate local edits into one save per complete change.
14
+ Processes sharing --session (default: default) are one serialized editing lane.
15
+ Independent jobs must choose distinct --session names. Contexts expire after 24h idle.
16
+ `;
17
+ export function checkedCloudPath(path, root = false) {
18
+ if ((path === "/" || path === "") && root)
19
+ return;
20
+ const parts = (path.startsWith("/") ? path.slice(1) : path).split("/");
21
+ if (!path ||
22
+ Buffer.byteLength(path) > 4096 ||
23
+ parts.length > 64 ||
24
+ /^(?:[a-z][a-z0-9+.-]*:|~|\/\/)/iu.test(path) ||
25
+ path.includes("\\") ||
26
+ [...path].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) ||
27
+ /%(?:2f|5c|00)/iu.test(path) ||
28
+ parts.some((p) => !p ||
29
+ p === "." ||
30
+ p === ".." ||
31
+ Buffer.byteLength(p) > 255 ||
32
+ /[. ]$/u.test(p)))
33
+ throw new UsageError("Invalid cloud path.", "invalid_path");
34
+ if (parts.some(secretFileName))
35
+ throw new UsageError("Secret filenames cannot be uploaded.", "secret_file_name");
36
+ }
37
+ export async function pathWorkspaceCommand(command, args, deps) {
38
+ const flags = new Map(), positionals = [];
39
+ let password = false, ack = false;
40
+ for (let i = 0; i < args.length; i++) {
41
+ const a = args[i];
42
+ if (["--json", "--text-stdin", "--stdin"].includes(a))
43
+ continue;
44
+ if (a === "--password-stdin") {
45
+ password = true;
46
+ continue;
47
+ }
48
+ if (a === "--acknowledge-access-widening") {
49
+ ack = true;
50
+ continue;
51
+ }
52
+ if (a.startsWith("--")) {
53
+ if (![
54
+ "--file",
55
+ "--from-file",
56
+ "--session",
57
+ "--workspace",
58
+ "--access",
59
+ "--kind",
60
+ "--limit",
61
+ "--cursor",
62
+ ].includes(a) ||
63
+ !args[i + 1])
64
+ throw new UsageError(PATH_WORKSPACE_HELP);
65
+ flags.set(a, args[++i]);
66
+ }
67
+ else
68
+ positionals.push(a);
69
+ }
70
+ if (positionals.length > 1)
71
+ throw new UsageError(PATH_WORKSPACE_HELP);
72
+ const path = positionals[0] ?? (command === "ls" ? "/" : "");
73
+ checkedCloudPath(path, command === "ls");
74
+ if ((flags.has("--file") || flags.has("--from-file")) &&
75
+ (args.includes("--text-stdin") || args.includes("--stdin")))
76
+ throw new UsageError("Choose --file or stdin, not both.");
77
+ if (flags.has("--kind") &&
78
+ flags.get("--kind") !== "folder" &&
79
+ flags.get("--kind") !== "file")
80
+ throw new UsageError("--kind must be file or folder.");
81
+ const isSave = command === "save", isShare = command === "share";
82
+ if (isShare &&
83
+ !["restricted", "link", "public"].includes(flags.get("--access") ?? ""))
84
+ throw new UsageError(PATH_WORKSPACE_HELP);
85
+ const selector = flags.get("--workspace");
86
+ const handle = selector &&
87
+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu.test(selector)
88
+ ? selector
89
+ : undefined;
90
+ if (handle && !/^[a-z0-9-]{1,63}$/u.test(handle))
91
+ throw new UsageError("Invalid workspace handle.");
92
+ if (handle) {
93
+ const original = deps;
94
+ deps = {
95
+ ...original,
96
+ request: (path, init) => original.request(path, {
97
+ ...init,
98
+ headers: {
99
+ ...Object.fromEntries(new Headers(init?.headers)),
100
+ "Foleo-Workspace": handle,
101
+ },
102
+ }),
103
+ };
104
+ }
105
+ let secretPassword;
106
+ const input = {
107
+ path,
108
+ ...(selector && !handle ? { workspace: selector } : {}),
109
+ };
110
+ if (isSave) {
111
+ if (flags.get("--kind") === "folder")
112
+ input.kind = "folder";
113
+ else {
114
+ const file = flags.get("--file") ?? flags.get("--from-file");
115
+ let text;
116
+ if (file) {
117
+ if (file.split(/[\\/]/u).some(secretFileName))
118
+ throw new UsageError("Secret filenames cannot be uploaded.", "secret_file_name");
119
+ const { bytes } = await captureFile(file, 65536);
120
+ try {
121
+ text = new TextDecoder("utf-8", {
122
+ fatal: true,
123
+ ignoreBOM: true,
124
+ }).decode(bytes);
125
+ }
126
+ catch {
127
+ throw new UsageError("Use foleo workspace put for binary files.", "transport_requires_advanced");
128
+ }
129
+ }
130
+ else
131
+ text = await deps.readStdin();
132
+ if (Buffer.byteLength(text) > 65536 ||
133
+ text.includes("\0") ||
134
+ new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(text)) !== text)
135
+ throw new UsageError("Use foleo workspace put for large/binary files.", "transport_requires_advanced");
136
+ input.text = text;
137
+ }
138
+ }
139
+ if (isShare) {
140
+ input.access = flags.get("--access");
141
+ if (ack)
142
+ input.accessWideningAcknowledged = true;
143
+ if (password) {
144
+ if (input.access !== "link")
145
+ throw new UsageError("--password-stdin requires --access link.");
146
+ const value = (await deps.readStdin()).replace(/\r?\n$/u, "");
147
+ if (!value || value.length > 256)
148
+ throw new UsageError("Password must be 1–256 characters.");
149
+ secretPassword = value;
150
+ input.password = true;
151
+ }
152
+ }
153
+ if (command === "ls")
154
+ for (const key of ["limit", "cursor"])
155
+ if (flags.has("--" + key))
156
+ input[key] = flags.get("--" + key);
157
+ const issueContext = async () => {
158
+ const r = await deps.request("/workspace-api/contexts", {
159
+ method: "POST",
160
+ headers: { "content-type": "application/json" },
161
+ body: "{}",
162
+ });
163
+ if (!r.ok) {
164
+ if (command === "read" && [403, 404, 503].includes(r.status))
165
+ return "";
166
+ const failure = (await r.json());
167
+ throw new FoleoError({
168
+ code: failure.error.code,
169
+ message: failure.error.code,
170
+ next: failure.error.next ?? "Resolve workspace access, then read again.",
171
+ source: "api",
172
+ httpStatus: r.status,
173
+ });
174
+ }
175
+ const v = (await r.json());
176
+ return v.editContext;
177
+ };
178
+ const lane = command === "read" || isSave
179
+ ? await deps.state.context(issueContext)
180
+ : undefined;
181
+ const verb = command === "ls" ? "list" : command, mutate = isSave || isShare;
182
+ const hash = createHash("sha256").update(JSON.stringify(input)).digest("hex");
183
+ const key = mutate ? await deps.state.intent(hash) : undefined;
184
+ if (secretPassword !== undefined) {
185
+ const salt = createHash("sha256")
186
+ .update("foleo-share-password-salt:" + key)
187
+ .digest()
188
+ .subarray(0, 16);
189
+ input.passwordKey = {
190
+ version: 1,
191
+ algorithm: "PBKDF2-SHA256",
192
+ iterations: 600000,
193
+ salt: salt.toString("hex"),
194
+ derivedKey: pbkdf2Sync(secretPassword, salt, 600000, 32, "sha256").toString("hex"),
195
+ };
196
+ secretPassword = undefined;
197
+ }
198
+ let url = "/workspace-api/" + verb;
199
+ if (!mutate)
200
+ url +=
201
+ "?" +
202
+ new URLSearchParams(Object.entries(input).map(([k, v]) => [k, String(v)]));
203
+ const response = await deps.request(url, {
204
+ method: mutate ? "POST" : "GET",
205
+ headers: {
206
+ ...(mutate ? { "content-type": "application/json" } : {}),
207
+ ...(lane ? { "X-Foleo-Edit-Context": lane } : {}),
208
+ ...(key ? { "Idempotency-Key": key } : {}),
209
+ },
210
+ ...(mutate ? { body: JSON.stringify(input) } : {}),
211
+ });
212
+ let result = (await response.json());
213
+ if (response.ok &&
214
+ command === "read" &&
215
+ lane &&
216
+ result.editContextStatus === "ticket_required") {
217
+ await deps.state.reset();
218
+ const fresh = await deps.state.context(issueContext);
219
+ if (fresh) {
220
+ const reread = await deps.request(url, {
221
+ method: "GET",
222
+ headers: { "X-Foleo-Edit-Context": fresh },
223
+ });
224
+ if (reread.ok)
225
+ result = (await reread.json());
226
+ else {
227
+ const failure = (await reread.json());
228
+ if (args.includes("--json")) {
229
+ deps.stdout(JSON.stringify({ ok: false, error: failure.error }) + "\n");
230
+ return 1;
231
+ }
232
+ throw new FoleoError({
233
+ code: String(failure.error.code),
234
+ message: String(failure.error.code),
235
+ next: String(failure.error.next ?? "Read again."),
236
+ source: "api",
237
+ httpStatus: reread.status,
238
+ });
239
+ }
240
+ }
241
+ }
242
+ if (!response.ok) {
243
+ const e = result.error;
244
+ if (key &&
245
+ e.retryable === false &&
246
+ [
247
+ "content_conflict",
248
+ "path_changed",
249
+ "item_replaced",
250
+ "mutation_rejected",
251
+ "kind_conflict",
252
+ "busy",
253
+ ].includes(String(e.code)))
254
+ await deps.state.forgetIntent(hash);
255
+ if (args.includes("--json")) {
256
+ deps.stdout(JSON.stringify({ ok: false, error: e }) + "\n");
257
+ return 1;
258
+ }
259
+ throw new FoleoError({
260
+ code: String(e.code),
261
+ message: String(e.code),
262
+ next: String(e.next ?? "Resolve the error and retry."),
263
+ httpStatus: response.status,
264
+ source: "api",
265
+ context: e,
266
+ });
267
+ }
268
+ if (key)
269
+ await deps.state.forgetIntent(hash);
270
+ if (args.includes("--json"))
271
+ deps.stdout(JSON.stringify({ ok: true, result }) + "\n");
272
+ else if (command === "read" && typeof result.text === "string")
273
+ deps.stdout(result.text);
274
+ else
275
+ deps.stdout(JSON.stringify(result, null, 2) + "\n");
276
+ return 0;
277
+ }
278
+ //# sourceMappingURL=path-workspace.js.map