@dreamlake/dreamlake-cli 0.116.0 → 0.118.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 (52) hide show
  1. package/dist/api/file-multipart.d.ts +6 -0
  2. package/dist/api/file-multipart.js +11 -0
  3. package/dist/api/index.d.ts +70 -2
  4. package/dist/api/index.js +2 -0
  5. package/dist/api/native-experiments.d.ts +25 -0
  6. package/dist/api/native-experiments.js +49 -3
  7. package/dist/api/project-access.d.ts +42 -0
  8. package/dist/api/project-access.js +67 -0
  9. package/dist/api/project-audience.d.ts +32 -0
  10. package/dist/api/project-audience.js +23 -0
  11. package/dist/api/workspace.d.ts +14 -1
  12. package/dist/api/workspace.js +5 -0
  13. package/dist/cli/create/index.d.ts +1 -0
  14. package/dist/cli/create/index.js +25 -7
  15. package/dist/cli/experiments/index.js +4 -0
  16. package/dist/cli/experiments/management.d.ts +16 -0
  17. package/dist/cli/experiments/management.js +82 -0
  18. package/dist/cli/experiments/transfer/adapter.d.ts +86 -0
  19. package/dist/cli/experiments/transfer/adapter.js +637 -0
  20. package/dist/cli/experiments/transfer/context.d.ts +13 -0
  21. package/dist/cli/experiments/transfer/context.js +20 -0
  22. package/dist/cli/experiments/transfer/download.d.ts +24 -0
  23. package/dist/cli/experiments/transfer/download.js +516 -0
  24. package/dist/cli/experiments/transfer/index.d.ts +2 -0
  25. package/dist/cli/experiments/transfer/index.js +38 -0
  26. package/dist/cli/experiments/transfer/local/safe-path.d.ts +29 -0
  27. package/dist/cli/experiments/transfer/local/safe-path.js +106 -0
  28. package/dist/cli/experiments/transfer/local/storage.d.ts +125 -0
  29. package/dist/cli/experiments/transfer/local/storage.js +432 -0
  30. package/dist/cli/experiments/transfer/transport.d.ts +7 -0
  31. package/dist/cli/experiments/transfer/transport.js +31 -0
  32. package/dist/cli/experiments/transfer/types.d.ts +48 -0
  33. package/dist/cli/experiments/transfer/types.js +1 -0
  34. package/dist/cli/experiments/transfer/upload.d.ts +58 -0
  35. package/dist/cli/experiments/transfer/upload.js +665 -0
  36. package/dist/cli/experiments/transfer/util/ansi.d.ts +24 -0
  37. package/dist/cli/experiments/transfer/util/ansi.js +70 -0
  38. package/dist/cli/experiments/transfer/util/glob.d.ts +4 -0
  39. package/dist/cli/experiments/transfer/util/glob.js +39 -0
  40. package/dist/cli/experiments/transfer/util/json.d.ts +6 -0
  41. package/dist/cli/experiments/transfer/util/json.js +58 -0
  42. package/dist/cli/experiments/transfer/util/pool.d.ts +5 -0
  43. package/dist/cli/experiments/transfer/util/pool.js +21 -0
  44. package/dist/cli/help-examples.generated.js +16 -0
  45. package/dist/cli/project/access.d.ts +10 -0
  46. package/dist/cli/project/access.js +43 -0
  47. package/dist/cli/project/index.js +19 -0
  48. package/dist/cli/project/permissions.d.ts +10 -0
  49. package/dist/cli/project/permissions.js +202 -0
  50. package/dist/cli/version.d.ts +1 -1
  51. package/dist/cli/version.js +1 -1
  52. package/package.json +9 -9
@@ -0,0 +1,70 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ const enabled = () => {
3
+ if (process.env.NO_COLOR !== undefined)
4
+ return false;
5
+ if (process.env.FORCE_COLOR !== undefined)
6
+ return true;
7
+ return process.stdout.isTTY === true;
8
+ };
9
+ const wrap = (code, close) => (s) => enabled() ? `\u001b[${code}m${s}\u001b[${close}m` : s;
10
+ export const bold = wrap(1, 22);
11
+ export const dim = wrap(2, 22);
12
+ export const red = wrap(31, 39);
13
+ export const green = wrap(32, 39);
14
+ export const yellow = wrap(33, 39);
15
+ export const blue = wrap(34, 39);
16
+ export const cyan = wrap(36, 39);
17
+ /** Visible width, ignoring the escape sequences the styles above insert. */
18
+ export const visibleWidth = (s) =>
19
+ // eslint-disable-next-line no-control-regex
20
+ s.replace(/\u001b\[[0-9;]*m/g, "").length;
21
+ const pad = (s, width, align) => {
22
+ const gap = Math.max(0, width - visibleWidth(s));
23
+ if (align === "right")
24
+ return " ".repeat(gap) + s;
25
+ if (align === "center") {
26
+ const l = Math.floor(gap / 2);
27
+ return " ".repeat(l) + s + " ".repeat(gap - l);
28
+ }
29
+ return s + " ".repeat(gap);
30
+ };
31
+ /** Rounded-box table, the same shape `rich.box.ROUNDED` produced. */
32
+ export function renderTable(columns, rows, opts = {}) {
33
+ const widths = columns.map((c, i) => Math.max(visibleWidth(c.header), ...rows.map((r) => visibleWidth(r[i] ?? ""))));
34
+ const line = (l, m, r) => l + widths.map((w) => "─".repeat(w + 2)).join(m) + r;
35
+ const out = [];
36
+ if (opts.title)
37
+ out.push(bold(opts.title));
38
+ out.push(line("╭", "┬", "╮"));
39
+ out.push("│ " + columns.map((c, i) => pad(bold(c.header), widths[i], c.align ?? "left")).join(" │ ") + " │");
40
+ out.push(line("├", "┼", "┤"));
41
+ for (const row of rows) {
42
+ out.push("│ " + columns.map((c, i) => pad(row[i] ?? "", widths[i], c.align ?? "left")).join(" │ ") + " │");
43
+ }
44
+ out.push(line("╰", "┴", "╯"));
45
+ if (opts.caption)
46
+ out.push(dim(opts.caption));
47
+ return out.join("\n");
48
+ }
49
+ /** Bordered panel, the shape `rich.panel.Panel` produced. */
50
+ export function renderPanel(body, opts = {}) {
51
+ const lines = body.split("\n");
52
+ const width = Math.max(...lines.map(visibleWidth), opts.title ? visibleWidth(opts.title) + 2 : 0);
53
+ const top = opts.title
54
+ ? "╭─ " + opts.title + " " + "─".repeat(Math.max(0, width - visibleWidth(opts.title) - 1)) + "╮"
55
+ : "╭" + "─".repeat(width + 2) + "╮";
56
+ const out = [top];
57
+ for (const l of lines)
58
+ out.push("│ " + pad(l, width, "left") + " │");
59
+ out.push("╰" + "─".repeat(width + 2) + "╯");
60
+ return out.join("\n");
61
+ }
62
+ export function formatBytes(n) {
63
+ let v = n;
64
+ for (const unit of ["B", "KB", "MB", "GB"]) {
65
+ if (v < 1024)
66
+ return `${v.toFixed(2)} ${unit}`;
67
+ v /= 1024;
68
+ }
69
+ return `${v.toFixed(2)} TB`;
70
+ }
@@ -0,0 +1,4 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ export declare function fnmatch(name: string, pattern: string): boolean;
3
+ export declare function fnmatchToRegExp(pattern: string): RegExp;
4
+ export declare const hasWildcard: (s: string) => boolean;
@@ -0,0 +1,39 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ export function fnmatch(name, pattern) {
3
+ return fnmatchToRegExp(pattern).test(name);
4
+ }
5
+ export function fnmatchToRegExp(pattern) {
6
+ let out = "";
7
+ let i = 0;
8
+ while (i < pattern.length) {
9
+ const c = pattern[i++];
10
+ if (c === "*")
11
+ out += ".*";
12
+ else if (c === "?")
13
+ out += ".";
14
+ else if (c === "[") {
15
+ let j = i;
16
+ if (j < pattern.length && (pattern[j] === "!" || pattern[j] === "^"))
17
+ j++;
18
+ if (j < pattern.length && pattern[j] === "]")
19
+ j++;
20
+ while (j < pattern.length && pattern[j] !== "]")
21
+ j++;
22
+ if (j >= pattern.length) {
23
+ out += "\\[";
24
+ }
25
+ else {
26
+ let body = pattern.slice(i, j);
27
+ if (body.startsWith("!") || body.startsWith("^"))
28
+ body = "^" + body.slice(1);
29
+ out += "[" + body.replace(/\\/g, "\\\\") + "]";
30
+ i = j + 1;
31
+ }
32
+ }
33
+ else {
34
+ out += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
35
+ }
36
+ }
37
+ return new RegExp(`^${out}$`, "s");
38
+ }
39
+ export const hasWildcard = (s) => /[*?[]/.test(s);
@@ -0,0 +1,6 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ /** Rewrite unsafe integer literals as strings, leaving strings and floats alone. */
3
+ export declare function preserveBigIntegers(text: string): string;
4
+ export declare function parseJson<T = any>(text: string): T;
5
+ /** Coerce whatever the server sent for an ID into a string, losslessly. */
6
+ export declare function asId(v: unknown): string | undefined;
@@ -0,0 +1,58 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ /** Rewrite unsafe integer literals as strings, leaving strings and floats alone. */
3
+ export function preserveBigIntegers(text) {
4
+ let out = "";
5
+ let i = 0;
6
+ const n = text.length;
7
+ while (i < n) {
8
+ const c = text[i];
9
+ if (c === '"') {
10
+ // Copy the string literal verbatim — digits inside it are not numbers.
11
+ const start = i++;
12
+ while (i < n) {
13
+ if (text[i] === "\\")
14
+ i += 2;
15
+ else if (text[i] === '"') {
16
+ i++;
17
+ break;
18
+ }
19
+ else
20
+ i++;
21
+ }
22
+ out += text.slice(start, i);
23
+ continue;
24
+ }
25
+ if (c === "-" || (c >= "0" && c <= "9")) {
26
+ const start = i;
27
+ if (text[i] === "-")
28
+ i++;
29
+ while (i < n && text[i] >= "0" && text[i] <= "9")
30
+ i++;
31
+ const isInteger = !(i < n && (text[i] === "." || text[i] === "e" || text[i] === "E"));
32
+ while (i < n && /[0-9.eE+-]/.test(text[i]))
33
+ i++;
34
+ const literal = text.slice(start, i);
35
+ // Only integers, and only those outside the exactly-representable range.
36
+ out += isInteger && !Number.isSafeInteger(Number(literal)) ? `"${literal}"` : literal;
37
+ continue;
38
+ }
39
+ out += c;
40
+ i++;
41
+ }
42
+ return out;
43
+ }
44
+ export function parseJson(text) {
45
+ return JSON.parse(preserveBigIntegers(text));
46
+ }
47
+ /** Coerce whatever the server sent for an ID into a string, losslessly. */
48
+ export function asId(v) {
49
+ if (v === null || v === undefined)
50
+ return undefined;
51
+ if (typeof v === "string")
52
+ return v;
53
+ if (typeof v === "number")
54
+ return String(v);
55
+ if (typeof v === "bigint")
56
+ return v.toString();
57
+ return String(v);
58
+ }
@@ -0,0 +1,5 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ export declare function runPool<T, R>(items: T[], limit: number, worker: (item: T, index: number) => Promise<R>): Promise<{
3
+ value?: R;
4
+ error?: Error;
5
+ }[]>;
@@ -0,0 +1,21 @@
1
+ /** .dash format compatibility, ported from the MIT-licensed ml-dash-cli. */
2
+ export async function runPool(items, limit, worker) {
3
+ const results = new Array(items.length);
4
+ const width = Math.max(1, Math.min(limit, items.length));
5
+ let cursor = 0;
6
+ const runners = Array.from({ length: width }, async () => {
7
+ for (;;) {
8
+ const index = cursor++;
9
+ if (index >= items.length)
10
+ return;
11
+ try {
12
+ results[index] = { value: await worker(items[index], index) };
13
+ }
14
+ catch (e) {
15
+ results[index] = { error: e instanceof Error ? e : new Error(String(e)) };
16
+ }
17
+ }
18
+ });
19
+ await Promise.all(runners);
20
+ return results;
21
+ }
@@ -57,6 +57,18 @@ export const helpExamples = {
57
57
  "experiments binding": "dl experiments binding --namespace fortyfive --json",
58
58
  "experiments connect": "dl experiments connect research --namespace fortyfive --json\n# Apply only after reviewing the preview. Use its actual revision, not this example's 0.\ndl experiments connect \"$DASH_NAMESPACE_ID\" --namespace fortyfive --instance-id \"$DASH_INSTANCE_ID\" --apply --expected-revision 0 --json",
59
59
  "experiments disconnect": "dl experiments disconnect --namespace fortyfive --json\n# Replace 1 with the revision returned by this preview.\ndl experiments disconnect --namespace fortyfive --apply --expected-revision 1 --json",
60
+ "experiments upload": "dl experiments upload ./.dash --project 'fortyfive/research/*' --strict",
61
+ "experiments download": "dl experiments download ./experiment-copy --project fortyfive/research --experiment trial_1",
62
+ "experiments writers list": "dl experiments writers list --namespace fortyfive --project research",
63
+ "experiments writers create": "dl experiments writers create --namespace fortyfive --project research --idempotency-key \"$INTENT_UUID\" --run-id \"$RUN_ID\"",
64
+ "experiments writers inspect": "dl experiments writers inspect \"$WRITER_ID\" --namespace fortyfive --project research",
65
+ "experiments writers rotate": "dl experiments writers rotate \"$WRITER_ID\" --expected-generation 1 --namespace fortyfive --project research",
66
+ "experiments writers retire": "dl experiments writers retire \"$WRITER_ID\" --expected-generation 2 --namespace fortyfive --project research",
67
+ "experiments jobs submit": "dl experiments jobs submit --spec job.json --namespace fortyfive --project research",
68
+ "experiments jobs list": "dl experiments jobs list --namespace fortyfive --project research",
69
+ "experiments jobs show": "dl experiments jobs show \"$JOB_ID\" --namespace fortyfive --project research",
70
+ "experiments jobs logs": "dl experiments jobs logs \"$JOB_ID\" --namespace fortyfive --project research",
71
+ "experiments jobs cancel": "dl experiments jobs cancel \"$JOB_ID\" --namespace fortyfive --project research",
60
72
  "hosts list": "dl hosts list\ndl hosts list --namespace geyang --group workstations\ndl hosts list --json\ndl hosts list --all\ndl hosts list --wide\ndl hosts --fields\ndl hosts --format '{name} {user} {ips} {network_freshness}'\ndl hosts --probe --format '{name} {ip} {public_ip} {macs} {uptime}'",
61
73
  "hosts status": "dl hosts status geyang/workstations/worker\ndl hosts status HOST_ID --namespace geyang --json\ndl hosts status 'geyang/workstations/*' --page 2 --page-size 100 --json",
62
74
  "hosts lifecycle": "dl hosts lifecycle HOST_ID --namespace geyang --json",
@@ -169,10 +181,14 @@ export const helpExamples = {
169
181
  "create bindr": "# Seed a Bindr with matching episodes without an interactive prompt.\ndl create bindr front-cam --project my-robots --episode \"camera/front/*\" --yes",
170
182
  "project inspect": "dl project inspect research --namespace acme",
171
183
  "project grants": "dl project grants research --namespace acme",
184
+ "project access": "# Inspect current baseline, visibility and your effective authority.\ndl project access research --ns acme --json\n# Remove the workspace-member Read baseline; explicit grants remain.\ndl project access research --ns acme --mode restricted\n# A public Project must become private atomically when restricted.\ndl project access research --ns acme --mode restricted --visibility private\n# Restore the workspace-member baseline; this does not make the Project public.\ndl project access research --ns acme --mode workspace",
185
+ "create project": "dl create project \"Private review\" --namespace acme --access-mode restricted",
172
186
  "project grant": "dl project grant research --namespace acme --user teammate --role WRITE\ndl project grant research --namespace acme --team TEAM_ID --role READ",
173
187
  "project revoke": "dl project grants research --namespace acme\ndl project revoke research GRANT_ID --namespace acme",
174
188
  "project attach": "dl project attach research --namespace acme --type note --resource \"$MEMO_ID\"",
175
189
  "project detach": "dl project detach research --namespace acme --type note --resource \"$MEMO_ID\"",
190
+ "project permissions": "# Choose organization and Project with the keyboard.\ndl project permissions\n# Or select the owning namespace and exact Project up front.\ndl project permissions research --namespace acme",
191
+ "project audience": "dl project audience research --namespace acme --json",
176
192
  "provider create": "dl provider create -n aws-demo --provider aws-jump-worker --json\n# Read the generated AGENT.md and terraform/ENROLLMENT.md.\n# Fill terraform/terraform.tfvars.json and terraform/backend.json explicitly.\ndl provider create -n aws-demo --continue --json",
177
193
  "provider plan": "# Requires the selected backend and authorized AWS read access.\ndl provider plan -n aws-demo --json",
178
194
  "provider machine": "dl provider machine status -n aws-dev --account 123456789012 --json\ndl provider machine start -n aws-dev --account 123456789012 --yes\ndl provider machine terminal -n aws-dev --account 123456789012\ndl provider machine stop -n aws-dev --account 123456789012 --yes",
@@ -0,0 +1,10 @@
1
+ import { type DreamlakeOpts } from '../compat/ctx.js';
2
+ export type ProjectAccessOptions = DreamlakeOpts & {
3
+ namespace?: string;
4
+ ns?: string;
5
+ mode?: string;
6
+ visibility?: string;
7
+ json?: boolean;
8
+ };
9
+ /** Inspect or change only this Project's workspace baseline. No grant/membership changes. */
10
+ export declare function runProjectAccess(project: string, options: ProjectAccessOptions): Promise<number>;
@@ -0,0 +1,43 @@
1
+ import { createClient } from '../../api/index.js';
2
+ import { resolveCtx } from '../compat/ctx.js';
3
+ import { fail } from '../helpers.js';
4
+ import { emitProjectResult } from './output.js';
5
+ /** Inspect or change only this Project's workspace baseline. No grant/membership changes. */
6
+ export async function runProjectAccess(project, options) {
7
+ try {
8
+ const namespace = options.namespace ?? options.ns;
9
+ if (options.namespace && options.ns && options.namespace !== options.ns)
10
+ throw new Error('--namespace and --ns must match');
11
+ if (!namespace?.trim() || !project.trim())
12
+ throw new Error('Explicit namespace and project ID or slug are required');
13
+ if (options.mode !== undefined && !['workspace', 'restricted'].includes(options.mode))
14
+ throw new Error('--mode must be workspace or restricted');
15
+ if (options.visibility !== undefined && !['private', 'public'].includes(options.visibility))
16
+ throw new Error('--visibility must be private or public');
17
+ if (options.visibility !== undefined && options.mode === undefined)
18
+ throw new Error('--visibility requires --mode');
19
+ const ctx = resolveCtx(options);
20
+ if (!ctx.token)
21
+ throw new Error("Not authenticated — run 'dl login' first");
22
+ const api = createClient({ remote: ctx.remote, token: ctx.token }).projects(namespace);
23
+ const result = options.mode === undefined
24
+ ? await api.access({ project })
25
+ : await api.setAccess({ project, accessMode: options.mode,
26
+ ...(options.visibility !== undefined ? { visibility: options.visibility } : {}) });
27
+ emitProjectResult(result, () => [
28
+ `Project: ${result.namespace.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')}/${result.projectSlug.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')} (${result.projectId})`,
29
+ `Access mode: ${result.accessMode}`,
30
+ `Visibility: ${result.visibility}`,
31
+ `Workspace members: ${result.baseline.orgMembers ?? 'no baseline'}`,
32
+ `Namespace owners: ${result.baseline.namespaceOwners}`,
33
+ `Public: ${result.baseline.public ?? 'no baseline'}`,
34
+ `Your role: ${result.viewerRole}; manage access: ${result.manageGrants ? 'yes' : 'no'}`,
35
+ 'Direct user/team grants and independent resource access are unchanged.',
36
+ ].join('\n'), options.json);
37
+ return 0;
38
+ }
39
+ catch (error) {
40
+ fail(error.message);
41
+ return 1;
42
+ }
43
+ }
@@ -1,3 +1,5 @@
1
+ import { runProjectPermissions, runProjectAudience } from './permissions.js';
2
+ import { runProjectAccess } from './access.js';
1
3
  import { runProjectAttachment } from './attachments.js';
2
4
  import { runProjectMove } from './move.js';
3
5
  import { runProjectTransferPreview } from './transfer-preview.js';
@@ -32,6 +34,23 @@ export async function runProjectRead(action, project, opts) {
32
34
  }
33
35
  export function registerProjectCommand(program) {
34
36
  const group = program.command('project').description('Inspect or share a Project, or request whole ownership transfer');
37
+ withConnFlags(group.command('permissions [project]'))
38
+ .description('interactive keyboard management of Project audience, grants and access mode')
39
+ .option('--namespace <slug>', 'owning namespace; omit to choose')
40
+ .action(async (project, options) => { process.exitCode = await runProjectPermissions(project, options); });
41
+ withConnFlags(group.command('audience <project>'))
42
+ .description('inspect effective human audience and access sources; requires current ADMIN')
43
+ .requiredOption('--namespace <slug>', 'owning namespace')
44
+ .option('--json', 'emit complete audience snapshot as JSON')
45
+ .action(async (project, options) => { process.exitCode = await runProjectAudience(project, options); });
46
+ withConnFlags(group.command('access <project>'))
47
+ .description('inspect workspace/restricted access, or set it with --mode; requires current project ADMIN for changes')
48
+ .option('--namespace <slug>', 'owning namespace (source context)')
49
+ .option('--ns <slug>', 'alias of --namespace; must match when both are supplied')
50
+ .option('--mode <mode>', 'workspace or restricted; omit to inspect')
51
+ .option('--visibility <visibility>', 'private or public with --mode; use private to restrict a public Project atomically')
52
+ .option('--json', 'print the complete JSON response (automatic when piped)')
53
+ .action(async (project, options) => { process.exitCode = await runProjectAccess(project, options); });
35
54
  withConnFlags(group.command('move <project>'))
36
55
  .description('move a whole Project and its owned Memos, Artifacts and Envs; review and owner acceptance required')
37
56
  .requiredOption('--namespace <slug>', 'current owning namespace')
@@ -0,0 +1,10 @@
1
+ import { type ProjectAudience } from '../../api/index.js';
2
+ import { type DreamlakeOpts } from '../compat/ctx.js';
3
+ type Options = DreamlakeOpts & {
4
+ namespace?: string;
5
+ json?: boolean;
6
+ };
7
+ export declare function audienceText(a: ProjectAudience): string;
8
+ export declare function runProjectAudience(project: string, opts: Options): Promise<number>;
9
+ export declare function runProjectPermissions(project: string | undefined, opts: Options): Promise<number>;
10
+ export {};
@@ -0,0 +1,202 @@
1
+ import { select, input, confirm, search } from '@inquirer/prompts';
2
+ import { createClient, remainingRole } from '../../api/index.js';
3
+ import { resolveCtx } from '../compat/ctx.js';
4
+ import { fail } from '../helpers.js';
5
+ import { emitProjectResult } from './output.js';
6
+ const safe = (s) => String(s ?? '').replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, ' ');
7
+ const out = (s) => process.stderr.write(s + '\n');
8
+ const cancel = '__cancel__';
9
+ const prompts = { input: process.stdin, output: process.stderr };
10
+ const choose = async (message, choices) => select({ message, choices: [...choices, { name: 'Back / cancel', value: cancel }], pageSize: 12 }, prompts);
11
+ const personName = (p) => `${p.username ? '@' + safe(p.username) : safe(p.name)} (${p.userId})`;
12
+ const sourceName = (s) => `${s.kind === 'owner' ? 'namespace owner recovery' : s.kind === 'team' ? `team ${safe(s.label)} (${s.teamId})` : s.kind === 'user' ? 'direct user grant' : s.kind === 'workspace' ? 'organization membership' : 'public'} ${s.role}${s.grantId ? ` [${s.grantId}]` : ''}`;
13
+ export function audienceText(a) {
14
+ const lines = [`Project: ${safe(a.namespace)}/${safe(a.projectSlug)} (${a.projectId})`,
15
+ `Mode: ${a.accessMode} | Visibility: ${a.visibility} | Your role: ${a.viewerRole}`,
16
+ `Organization members: ${a.baseline.orgMembers ?? 'no baseline'} | Owners: ADMIN recovery | Public: ${a.baseline.public ?? 'no baseline'}`,
17
+ 'Effective human audience — current snapshot; memberships can change.'];
18
+ for (const p of a.people)
19
+ lines.push(` ${personName(p)}: ${p.effectiveRole ?? 'no Project access'}\n ${p.sources.map(sourceName).join('; ') || 'No applicable source'}`);
20
+ if (!a.people.length)
21
+ lines.push(' No named active users in this snapshot.');
22
+ if (a.baseline.public)
23
+ lines.push(' Anyone, including anonymous visitors, also has READ. Named users are not the whole public audience.');
24
+ lines.push('Independent resource shares and access through other Projects remain separate.');
25
+ return lines.join('\n');
26
+ }
27
+ function clientFor(opts) {
28
+ const ctx = resolveCtx(opts);
29
+ if (!ctx.token)
30
+ throw new Error("Not authenticated — run 'dl login' first");
31
+ return createClient({ remote: ctx.remote, token: ctx.token });
32
+ }
33
+ export async function runProjectAudience(project, opts) {
34
+ try {
35
+ if (!opts.namespace?.trim())
36
+ throw new Error('Explicit --namespace is required');
37
+ const a = await clientFor(opts).projects(opts.namespace).audience({ project });
38
+ emitProjectResult(a, () => audienceText(a), opts.json);
39
+ return 0;
40
+ }
41
+ catch (e) {
42
+ fail(e.message);
43
+ return 1;
44
+ }
45
+ }
46
+ export async function runProjectPermissions(project, opts) {
47
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
48
+ fail('Interactive terminal required. Use project audience/grants --json and grant/revoke/access for scripts.');
49
+ return 1;
50
+ }
51
+ let submitted = false;
52
+ try {
53
+ const client = clientFor(opts);
54
+ let namespace = opts.namespace;
55
+ if (!namespace) {
56
+ out('Loading your organizations…');
57
+ const data = await client.organizations.list();
58
+ if (!Array.isArray(data?.myOrganizations))
59
+ throw new Error('Organization list is unconfirmed');
60
+ const choices = data.myOrganizations.map(n => ({ name: `${safe(n.name)} (${safe(n.slug)})`, value: n.slug }));
61
+ const picked = await choose('Choose organization or enter an explicit namespace', [...choices, { name: 'Enter namespace', value: '__enter__' }]);
62
+ if (picked === cancel)
63
+ return 0;
64
+ namespace = picked === '__enter__' ? (await input({ message: 'Exact owning namespace:', validate: s => !!s.trim() || 'Enter a namespace' }, prompts)).trim() : picked;
65
+ }
66
+ const api = client.projects(namespace);
67
+ if (!project) {
68
+ let page = 1;
69
+ while (!project) {
70
+ out(`Loading Projects in ${safe(namespace)}…`);
71
+ const data = await api.list({ page, pageSize: 50 });
72
+ if (!Array.isArray(data.projects))
73
+ throw new Error('Project listing is unconfirmed');
74
+ if (!data.projects.length)
75
+ out('No Projects on this page. Enter a known ID/slug or cancel.');
76
+ const choices = data.projects.map(p => ({ name: `${safe(p.name)} — ${safe(namespace)}/${safe(p.slug)} (${p.id})`, value: p.id }));
77
+ if (data.totalPages && page < data.totalPages)
78
+ choices.push({ name: 'Next page', value: '__next__' });
79
+ if (page > 1)
80
+ choices.push({ name: 'Previous page', value: '__prev__' });
81
+ choices.push({ name: 'Enter exact Project ID or slug', value: '__enter__' });
82
+ const picked = await choose('Choose Project', choices);
83
+ if (picked === cancel)
84
+ return 0;
85
+ if (picked === '__next__') {
86
+ page++;
87
+ continue;
88
+ }
89
+ if (picked === '__prev__') {
90
+ page--;
91
+ continue;
92
+ }
93
+ project = picked === '__enter__' ? (await input({ message: 'Project ID or slug:', validate: s => !!s.trim() || 'Enter a Project' }, prompts)).trim() : picked;
94
+ }
95
+ }
96
+ let projectId = project;
97
+ const load = async () => {
98
+ out('Loading current audience and direct grants…');
99
+ const audience = await api.audience({ project: projectId });
100
+ projectId = audience.projectId; // Subsequent reads/writes bind to the resolved ID, never a reused slug.
101
+ const grants = await api.grants(projectId);
102
+ if (grants?.viewerRole !== 'ADMIN' || !Array.isArray(grants.grants) || !Array.isArray(grants.teams))
103
+ throw new Error('Current grant management contract is unconfirmed');
104
+ return { audience, grants };
105
+ };
106
+ for (;;) {
107
+ const state = await load();
108
+ const { audience: a, grants: g } = state;
109
+ out('\n' + audienceText(a));
110
+ out(`Direct grants: ${g.grants.length}. These alone are not the full audience.`);
111
+ const action = await choose('Project permissions', [
112
+ { name: 'Grant or change a user role', value: 'user' }, { name: 'Grant or change a team role', value: 'team' },
113
+ { name: 'Revoke one direct grant', value: 'revoke' }, { name: 'Set Workspace / Restricted', value: 'mode' },
114
+ { name: 'Refresh audience', value: 'refresh' },
115
+ ]);
116
+ if (action === cancel)
117
+ return 0;
118
+ if (action === 'refresh')
119
+ continue;
120
+ let mutate;
121
+ let verify;
122
+ let preview = '';
123
+ if (action === 'user' || action === 'team') {
124
+ let target;
125
+ if (action === 'user') {
126
+ const choices = a.people.filter(p => p.username).map(p => ({ name: personName(p), value: p.username }));
127
+ target = await search({ message: 'Select a person (type to filter)', pageSize: 10,
128
+ source: term => [...choices.filter(c => c.name.toLowerCase().includes((term ?? '').toLowerCase())),
129
+ { name: 'Enter another exact username', value: '__enter__' }, { name: 'Back / cancel', value: cancel }] }, prompts);
130
+ if (target === '__enter__')
131
+ target = (await input({ message: 'Exact recipient username (without @):', validate: s => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(s.trim()) || 'Enter a username, not a name/email' }, prompts)).trim();
132
+ }
133
+ else {
134
+ if (!g.teams.length) {
135
+ out('No active teams are available in this organization. Use a user grant or manage teams separately.');
136
+ continue;
137
+ }
138
+ target = await choose('Select team in this organization', g.teams.map(t => ({ name: `${safe(t.name)} (${safe(t.slug)}; ${t.id})`, value: t.id })));
139
+ }
140
+ if (target === cancel)
141
+ continue;
142
+ const chosenRole = await choose('Role', [{ name: 'READ — read Project content', value: 'READ' }, { name: 'WRITE — read, create and delete content', value: 'WRITE' }, { name: 'ADMIN — also edit Project and manage grants', value: 'ADMIN' }]);
143
+ if (chosenRole === cancel)
144
+ continue;
145
+ const role = chosenRole;
146
+ const body = action === 'user' ? { granteeSlug: target, role } : { teamId: target, role };
147
+ preview = `Set direct ${action} grant: ${safe(target)} → ${role}.\nExisting grant for this recipient is replaced. Other grants and baselines still apply.`;
148
+ mutate = () => api.grant(projectId, body);
149
+ verify = s => s.grants.grants.some(gr => (action === 'user' ? gr.grantee?.slug === target : gr.teamId === target) && gr.role === role);
150
+ }
151
+ else if (action === 'revoke') {
152
+ if (!g.grants.length) {
153
+ out('No direct grants to revoke. Owner recovery and membership/public baselines are controlled separately.');
154
+ continue;
155
+ }
156
+ const id = await choose('Choose exactly one grant to remove', g.grants.map(gr => ({ name: `${safe(gr.grantee?.slug ?? gr.team?.name ?? gr.granteeId ?? gr.teamId)} — ${gr.role} [${gr.id}]`, value: gr.id })));
157
+ if (id === cancel)
158
+ continue;
159
+ const affected = a.people.filter(p => p.sources.some(s => s.grantId === id));
160
+ preview = `Remove direct grant ${id}.\n` + (affected.length ? affected.map(p => `${personName(p)}: ${p.effectiveRole} → ${remainingRole(p.sources, id) ?? 'no Project access'}\n Survives: ${p.sources.filter(s => s.grantId !== id).map(sourceName).join('; ') || 'none'}`).join('\n') : 'No active named users currently receive access through this grant.');
161
+ preview += '\nIndependent resource shares remain. Team membership can change after this snapshot.';
162
+ mutate = () => api.revoke(projectId, id);
163
+ verify = s => !s.grants.grants.some(gr => gr.id === id);
164
+ }
165
+ else {
166
+ const mode = await choose('Access mode', [{ name: 'Restricted — selected user/team grants and namespace owners', value: 'restricted' }, { name: 'Workspace — organization members inherit READ', value: 'workspace' }]);
167
+ if (mode === cancel)
168
+ continue;
169
+ preview = mode === 'restricted'
170
+ ? `Set Restricted and private. Remove organization/public baselines. Explicit user/team grants and owner recovery survive.${a.visibility === 'public' ? '\nThis explicitly makes the public Project private in the SAME request.' : ''}`
171
+ : 'Set Workspace. Organization members inherit READ; existing visibility and grants remain.';
172
+ mutate = () => api.setAccess({ project: projectId, accessMode: mode, ...(mode === 'restricted' ? { visibility: 'private' } : {}) });
173
+ verify = s => s.audience.accessMode === mode && (mode !== 'restricted' || s.audience.visibility === 'private');
174
+ }
175
+ out(`\nReview change to ${safe(namespace)}/${safe(a.projectSlug)} (${projectId})\n${preview}`);
176
+ if (!await confirm({ message: 'Apply this change?', default: false }, prompts)) {
177
+ out('Cancelled. No mutation submitted.');
178
+ continue;
179
+ }
180
+ const fresh = await load();
181
+ if (JSON.stringify(fresh) !== JSON.stringify(state)) {
182
+ out('Access changed during review. No mutation submitted; review the refreshed state.');
183
+ continue;
184
+ }
185
+ submitted = true;
186
+ await mutate();
187
+ const after = await load();
188
+ if (!verify(after))
189
+ throw new Error('Mutation receipt did not match the requested change');
190
+ submitted = false;
191
+ out('Change saved and read back.');
192
+ }
193
+ }
194
+ catch (e) {
195
+ if (!submitted && ['ExitPromptError', 'AbortPromptError'].includes(e.name)) {
196
+ out('Cancelled. No pending mutation submitted.');
197
+ return 0;
198
+ }
199
+ fail(`${safe(e.message)}${submitted ? '\nChange outcome is unconfirmed. It may have applied. Inspect current access before retrying; no automatic retry was made.' : '\nNo pending mutation submitted. Compatible audience/access endpoints and current ADMIN are required.'}`);
200
+ return 1;
201
+ }
202
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.116.0";
1
+ export declare const VERSION = "0.118.0";
@@ -6,4 +6,4 @@
6
6
  // value means a binary that re-installs the same version forever.
7
7
  //
8
8
  // Editing this by hand does nothing for a release; bump package.json.
9
- export const VERSION = "0.116.0";
9
+ export const VERSION = "0.118.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamlake/dreamlake-cli",
3
- "version": "0.116.0",
3
+ "version": "0.118.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dreamlake-ai/dreamlake-cli.git"
@@ -37,13 +37,13 @@
37
37
  "node": ">=18"
38
38
  },
39
39
  "optionalDependencies": {
40
- "@dreamlake/dreamlake-cli-darwin-arm64": "0.116.0",
41
- "@dreamlake/dreamlake-cli-darwin-x64": "0.116.0",
42
- "@dreamlake/dreamlake-cli-linux-x64": "0.116.0",
43
- "@dreamlake/dreamlake-cli-linux-arm64": "0.116.0",
44
- "@dreamlake/dreamlake-cli-linux-x64-musl": "0.116.0",
45
- "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.116.0",
46
- "@dreamlake/dreamlake-cli-win32-x64": "0.116.0",
47
- "@dreamlake/dreamlake-cli-win32-arm64": "0.116.0"
40
+ "@dreamlake/dreamlake-cli-darwin-arm64": "0.118.0",
41
+ "@dreamlake/dreamlake-cli-darwin-x64": "0.118.0",
42
+ "@dreamlake/dreamlake-cli-linux-x64": "0.118.0",
43
+ "@dreamlake/dreamlake-cli-linux-arm64": "0.118.0",
44
+ "@dreamlake/dreamlake-cli-linux-x64-musl": "0.118.0",
45
+ "@dreamlake/dreamlake-cli-linux-arm64-musl": "0.118.0",
46
+ "@dreamlake/dreamlake-cli-win32-x64": "0.118.0",
47
+ "@dreamlake/dreamlake-cli-win32-arm64": "0.118.0"
48
48
  }
49
49
  }