@lbdudc/linea-cli 0.3.1 → 0.3.2

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.
@@ -1,41 +1,4 @@
1
1
  // @bun
2
- import {
3
- createGitProvider,
4
- registerLocation,
5
- createPackageSource,
6
- publishFolder,
7
- git,
8
- gitAsync,
9
- isAuthFailure,
10
- checkGitAccess,
11
- isRepo,
12
- cloneUrlOf,
13
- credentialOptions,
14
- repoState,
15
- changedCount,
16
- checkoutsAt,
17
- cloneLine,
18
- cloneProduct,
19
- pullCheckout,
20
- fetchCheckout,
21
- pushCheckout,
22
- hasUnsent,
23
- adoptFolder,
24
- clonePackage,
25
- config,
26
- serverOf,
27
- loadState,
28
- saveState,
29
- clearAuth,
30
- hostLabel,
31
- gitConfigOf,
32
- gitSettings,
33
- gitProviderOf,
34
- catalogOf,
35
- remotePackages,
36
- packageSourceOf,
37
- whyNoAccess2
38
- } from "./chunk-byt4gzdm.js";
39
2
  import {
40
3
  __toESM,
41
4
  __commonJS,
@@ -82,6 +45,45 @@ import {
82
45
  splsUsing,
83
46
  changeProductFeatures
84
47
  } from "./chunk-6y69424k.js";
48
+ import {
49
+ createGitProvider,
50
+ registerLocation,
51
+ createPackageSource,
52
+ publishFolder,
53
+ git,
54
+ gitAsync,
55
+ isAuthFailure,
56
+ checkGitAccess,
57
+ isRepo,
58
+ cloneUrlOf,
59
+ credentialOptions,
60
+ repoState,
61
+ changedCount,
62
+ checkoutsAt,
63
+ cloneLine,
64
+ cloneProduct,
65
+ pullCheckout,
66
+ fetchCheckout,
67
+ pushCheckout,
68
+ hasUnsent,
69
+ adoptFolder,
70
+ clonePackage,
71
+ config,
72
+ serverOf,
73
+ storedGit,
74
+ loadState,
75
+ saveState,
76
+ resolveMode,
77
+ clearAuth,
78
+ hostLabel,
79
+ gitConfigOf,
80
+ gitSettings,
81
+ gitProviderOf,
82
+ catalogOf,
83
+ remotePackages,
84
+ packageSourceOf,
85
+ whyNoAccess2
86
+ } from "./chunk-7fb64a6k.js";
85
87
 
86
88
  // ../../node_modules/vscode-jsonrpc/lib/common/is.js
87
89
  var require_is = __commonJS(function(exports) {
@@ -15133,6 +15135,13 @@ function onTokenRefreshed(fn) {
15133
15135
  persistToken = fn;
15134
15136
  }
15135
15137
 
15138
+ class SessionExpiredError extends Error {
15139
+ constructor() {
15140
+ super("Your session on the LINEA server expired.");
15141
+ this.name = "SessionExpiredError";
15142
+ }
15143
+ }
15144
+
15136
15145
  class SplalmError extends Error {
15137
15146
  status;
15138
15147
  code;
@@ -15152,10 +15161,23 @@ var CODE_MESSAGES = {
15152
15161
  "error_messages.basicData_name_validation": "The product name is missing or invalid.",
15153
15162
  "error_messages.basicData_version_format": "The product version must be in x.y.z form.",
15154
15163
  "error_messages.line_platform_not_found": "The SPL has no platform code in GitLab yet.",
15164
+ "error_messages.no_linea_account": "That account has never signed in to this LINEA: sign in once with the browser (login <remote>) or a code (login <remote> --device) first; after that a token works.",
15165
+ "error_messages.device_flow_unavailable": "This LINEA has no sign-in with a code for that remote: use the browser (login <remote>) or a token (login <remote> --token <token or file>).",
15166
+ "error_messages.device_flow_disabled": "The OAuth application of that remote does not allow the sign-in with a code (an administrator has to enable the device flow in it).",
15167
+ "error_messages.device_code_expired": "The code expired before it was approved: run the command again.",
15168
+ "error_messages.device_access_denied": "The sign-in was refused on the other screen.",
15169
+ "error_messages.git_host_not_linked": "You have no account on that remote yet: remote link <remote>.",
15170
+ "error_messages.git_host_is_own": "That is the account you sign in with here: it cannot be unlinked.",
15171
+ "error_messages.git_host_account_taken": "That account already belongs to someone else on this LINEA.",
15172
+ "error_messages.git_host_validation": "This LINEA does not have that remote on: remote shows the ones it has.",
15173
+ "error_messages.incorrect_credentials": "Those credentials were not accepted.",
15174
+ "error_messages.too_many_attempts": "Too many attempts: wait a little and try again.",
15155
15175
  "error_messages.code_validation": "GitLab did not send a valid authorization code \u2014 try /login again.",
15156
15176
  "error_messages.redirect_uri_validation": "The CLI's loopback redirect_uri was rejected by the server (must be a canonical http://127.0.0.1:<port>/callback or [::1] URI). Try /login again; if this persists, set LINEA_OAUTH_PORT to a different free port."
15157
15177
  };
15158
15178
  function handleApiError(error) {
15179
+ if (error instanceof SessionExpiredError)
15180
+ return "\u2717 Your session on the LINEA server expired. Run: login (or add --offline to work on this machine).";
15159
15181
  if (error instanceof SplalmError) {
15160
15182
  const known = CODE_MESSAGES[error.code];
15161
15183
  if (known)
@@ -15165,7 +15187,7 @@ function handleApiError(error) {
15165
15187
  case 400:
15166
15188
  return `Bad request \u2014 ${detail}. Check your input.`;
15167
15189
  case 401:
15168
- return "Unauthorized \u2014 your session has expired. Run /login to sign in again.";
15190
+ return "Unauthorized \u2014 your session has expired. Run: login (or add --offline to work on this machine).";
15169
15191
  case 403:
15170
15192
  return "Permission denied \u2014 you need a higher GitLab access level (maintainer=40, owner=50) for this.";
15171
15193
  case 404:
@@ -15183,7 +15205,7 @@ function handleApiError(error) {
15183
15205
  const causeCode = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
15184
15206
  const blob = `${error.message} ${causeCode}`;
15185
15207
  if (error.message === "fetch failed" || blob.includes("ECONNREFUSED") || blob.includes("ENOTFOUND")) {
15186
- return `Cannot reach SPLALM at ${baseUrl}. Check the server is running and LINEA_BASE_URL is correct.`;
15208
+ return `Cannot reach LINEA at ${baseUrl}. Check the address (server <url>). To work on this machine meanwhile: mode offline, or --offline for one command.`;
15187
15209
  }
15188
15210
  if (blob.includes("ETIMEDOUT") || blob.includes("timeout")) {
15189
15211
  return "Request timed out. Generation can take several minutes.";
@@ -15203,10 +15225,12 @@ async function apiRequest(method, urlPath, body, isRetry = false) {
15203
15225
  if (body !== undefined)
15204
15226
  init.body = JSON.stringify(body);
15205
15227
  const res = await fetch(`${baseUrl}${urlPath}`, init);
15206
- if (res.status === 401 && !isRetry) {
15228
+ if (res.status === 401 && !isRetry && currentJwt) {
15207
15229
  const refreshed = await doRefresh();
15208
15230
  if (refreshed)
15209
15231
  return apiRequest(method, urlPath, body, true);
15232
+ if (urlPath !== "/api/users/loginFromServiceToken")
15233
+ throw new SessionExpiredError;
15210
15234
  }
15211
15235
  if (!res.ok) {
15212
15236
  const err = await res.json().catch(() => ({ message: res.statusText }));
@@ -15251,7 +15275,8 @@ function startAutoRefresh() {
15251
15275
  var splalm = {
15252
15276
  get: (p) => apiRequest("GET", p),
15253
15277
  post: (p, b) => apiRequest("POST", p, b),
15254
- put: (p, b) => apiRequest("PUT", p, b)
15278
+ put: (p, b) => apiRequest("PUT", p, b),
15279
+ del: (p) => apiRequest("DELETE", p)
15255
15280
  };
15256
15281
 
15257
15282
  // src/core/session.ts
@@ -15367,6 +15392,7 @@ function buildSession(opts = {}) {
15367
15392
  session: {
15368
15393
  baseUrl,
15369
15394
  authed: Boolean(token),
15395
+ mode: resolveMode(stored),
15370
15396
  user: stored.user,
15371
15397
  workdir,
15372
15398
  cwd,
@@ -15376,6 +15402,30 @@ function buildSession(opts = {}) {
15376
15402
  };
15377
15403
  }
15378
15404
 
15405
+ // src/core/mode.ts
15406
+ var modeOf = (session) => session.mode ?? (session.authed ? "server" : "offline");
15407
+ var online = (session) => modeOf(session) === "server" && session.authed;
15408
+ var shortServer = (url) => url.replace(/^https?:\/\//, "").replace(/\/+$/, "");
15409
+ var remoteOf = (session) => session.user?.activeHost ? hostLabel(session.user.activeHost) : undefined;
15410
+ function contextLine(session, { short = false } = {}) {
15411
+ if (modeOf(session) === "offline") {
15412
+ return session.modeOverride ? "\u25CB offline (this command) \xB7 this machine only" : short ? "\u25CB offline" : "\u25CB offline \xB7 this machine only";
15413
+ }
15414
+ const server = shortServer(session.baseUrl);
15415
+ if (!session.authed)
15416
+ return short ? "\u25D0 not signed in" : `\u25D0 server ${server} \xB7 not signed in (login)`;
15417
+ if (session.expired)
15418
+ return short ? "\u25D0 session expired" : `\u25D0 server ${server} \xB7 session expired (login)`;
15419
+ const who = session.user?.username;
15420
+ const remote = remoteOf(session);
15421
+ if (short)
15422
+ return `\u25CF ${[remote, who].filter(Boolean).join(" \xB7 ") || "server"}`;
15423
+ return `\u25CF server ${server} \xB7 ${remote ? `${remote} as ` : "signed in as "}${who ?? "?"}`;
15424
+ }
15425
+ function needsServerText(what, session) {
15426
+ return modeOf(session) === "offline" ? `\u2717 ${what} needs the LINEA server, and linea is offline (this machine only). Switch: mode server` : `\u2717 ${what} needs you signed in to ${shortServer(session.baseUrl)}: login [remote] (or --offline to work on this machine)`;
15427
+ }
15428
+
15379
15429
  // src/core/guide.ts
15380
15430
  import fs4 from "fs";
15381
15431
  import path5 from "path";
@@ -15444,7 +15494,8 @@ function guideState(session, folder = findContext(session.cwd ?? process.cwd()),
15444
15494
  spls = fs4.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && findContext(path5.join(root, e.name)).line?.dir === path5.join(root, e.name)).length;
15445
15495
  } catch {}
15446
15496
  return {
15447
- signedIn: session.authed,
15497
+ signedIn: online(session),
15498
+ mode: modeOf(session),
15448
15499
  ...session.user?.username ? { user: session.user.username } : {},
15449
15500
  spls,
15450
15501
  ...folder.line ? { line: checkouts ? checkouts.line ?? { name: folder.line.name, linked: false, changes: 0, ahead: 0, behind: 0 } : checkoutOf(folder.line.name, folder.line.dir) } : {},
@@ -15467,7 +15518,7 @@ function tipsFor(state) {
15467
15518
  const here = state.product ?? state.line;
15468
15519
  if (here) {
15469
15520
  if (state.line && !state.line.linked && !state.product) {
15470
- tips.push(state.signedIn ? { command: "push", why: `put ${state.line.name} on LINEA (it is only on this machine)` } : { command: "login", why: `sign in, and push will put ${state.line.name} on LINEA` });
15521
+ tips.push(state.signedIn ? { command: "push", why: `put ${state.line.name} on LINEA (it is only on this machine)` } : state.mode === "offline" ? { command: "mode server", why: `connect to LINEA, and push will put ${state.line.name} there` } : { command: "login", why: `sign in, and push will put ${state.line.name} on LINEA` });
15471
15522
  }
15472
15523
  if (here.changes > 0 || here.ahead > 0)
15473
15524
  tips.push({ command: 'push -m "\u2026"', why: `send ${plural(here.changes || here.ahead, here.changes ? "change" : "commit")} to LINEA` });
@@ -15488,8 +15539,13 @@ function tipsFor(state) {
15488
15539
  return dedupe(tips).slice(0, 5);
15489
15540
  }
15490
15541
  if (!state.signedIn) {
15491
- tips.push({ command: "login", why: "sign in: your SPLs on LINEA, and git access" });
15492
- tips.push({ command: "spl new <name> --local", why: "start an SPL on this machine" });
15542
+ if (state.mode === "offline") {
15543
+ tips.push({ command: "spl new <name>", why: "start an SPL on this machine" });
15544
+ tips.push({ command: "mode server", why: "connect to LINEA: your SPLs there, and git access" });
15545
+ } else {
15546
+ tips.push({ command: "login", why: "sign in to LINEA: your SPLs there, and git access" });
15547
+ tips.push({ command: "mode offline", why: "or work on this machine only" });
15548
+ }
15493
15549
  if (state.spls)
15494
15550
  tips.push({ command: "status", why: whereStand(state.spls) });
15495
15551
  tips.push({ command: "doctor", why: "check that git and an editor are in place" });
@@ -15648,6 +15704,9 @@ var GLYPHS = {
15648
15704
  "!": { glyph: "warn", rest: "plain" },
15649
15705
  "\u26A0": { glyph: "warn", rest: "plain" },
15650
15706
  "\xB7": { glyph: "dim", rest: "dim" },
15707
+ "\u25CF": { glyph: "ok", rest: "dim" },
15708
+ "\u25D0": { glyph: "warn", rest: "dim" },
15709
+ "\u25CB": { glyph: "faint", rest: "dim" },
15651
15710
  "\u2026": { glyph: "faint", rest: "dim" }
15652
15711
  };
15653
15712
  var WHERE = { "here + LINEA": "ok", "here only": "warn", "LINEA only": "info" };
@@ -15718,7 +15777,7 @@ var KEYS_HELP = [
15718
15777
 
15719
15778
  // src/commands/help.ts
15720
15779
  var GROUPS = [
15721
- { title: "Account and setup", names: ["login", "logout", "whoami", "config", "init", "doctor"] },
15780
+ { title: "Account, server and mode", names: ["whoami", "login", "logout", "remote", "mode", "server", "config", "init", "doctor"] },
15722
15781
  { title: "LINEA \u21C4 your machine", names: ["get", "status", "push"] },
15723
15782
  { title: "Open", names: ["open"] },
15724
15783
  { title: "SPLs", names: ["cd", "spl", "check"] },
@@ -15737,8 +15796,11 @@ var detail = (c) => {
15737
15796
  lines.push(` flags: ${c.flags.join(" ")}`);
15738
15797
  if (c.aliases?.length)
15739
15798
  lines.push(` aliases: ${c.aliases.join(", ")}`);
15740
- if (c.requiresAuth)
15741
- lines.push(" needs you signed in (login)");
15799
+ const where = c.where ?? (c.requiresAuth ? "server" : "machine");
15800
+ if (where === "server")
15801
+ lines.push(" needs the LINEA server: server mode, signed in (mode server, login)");
15802
+ else if (where === "both")
15803
+ lines.push(" works on the LINEA server (server mode) or on this machine (offline), by the mode you are in");
15742
15804
  return lines;
15743
15805
  };
15744
15806
  function commandReference() {
@@ -15926,10 +15988,6 @@ var flagString = (f, name) => {
15926
15988
  return typeof v === "string" ? v : undefined;
15927
15989
  };
15928
15990
 
15929
- // src/oauth/loopback.ts
15930
- import http from "http";
15931
- import crypto from "crypto";
15932
-
15933
15991
  // node_modules/open/index.js
15934
15992
  import process8 from "process";
15935
15993
  import { Buffer } from "buffer";
@@ -16441,6 +16499,8 @@ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
16441
16499
  var open_default = open;
16442
16500
 
16443
16501
  // src/oauth/loopback.ts
16502
+ import http from "http";
16503
+ import crypto from "crypto";
16444
16504
  var PAGE = (ok, detail) => `<!doctype html><html><head>
16445
16505
  <meta charset="utf-8"><title>linea</title>
16446
16506
  <style>body{font-family:system-ui,sans-serif;background:#0f172a;color:#f1f5f9;display:flex;
@@ -16505,6 +16565,20 @@ async function runLoopbackOAuth(opts) {
16505
16565
  });
16506
16566
  }
16507
16567
 
16568
+ // src/commands/lookup.ts
16569
+ var find = () => {
16570
+ return;
16571
+ };
16572
+ function setLookup(fn) {
16573
+ find = fn;
16574
+ }
16575
+ function commandNamed(name) {
16576
+ const cmd = find(name);
16577
+ if (!cmd)
16578
+ throw new Error(`Internal: no command "${name}".`);
16579
+ return cmd;
16580
+ }
16581
+
16508
16582
  // src/commands/auth.ts
16509
16583
  function hostToSignIn(cfg, asked) {
16510
16584
  const on = cfg.hosts?.map((host) => host.id) ?? [cfg.provider ?? "gitlab"];
@@ -16514,14 +16588,14 @@ function hostToSignIn(cfg, asked) {
16514
16588
  return wanted;
16515
16589
  }
16516
16590
  var configOf = (cfg, host) => ({ ...cfg, ...cfg.hosts?.find((entry) => entry.id === host) ?? {}, provider: host });
16517
- async function signIn(ctx, all, host) {
16591
+ async function browserCode(ctx, all, host) {
16518
16592
  const cfg = configOf(all, host);
16519
16593
  if (!cfg.clientId || !cfg.url) {
16520
16594
  throw new Error(`The backend's /api/users/config didn't return a ${hostLabel(host)} clientId/url (internal_error).`);
16521
16595
  }
16522
16596
  const name = hostLabel(host);
16523
16597
  ctx.setStatus(`waiting for ${name} authorization (${cfg.url}) in your browser\u2026`);
16524
- const { code, redirectUri } = await runLoopbackOAuth({
16598
+ return runLoopbackOAuth({
16525
16599
  authorizeBase: cfg.url,
16526
16600
  ...cfg.authorizeUrl ? { authorizeUrl: cfg.authorizeUrl } : {},
16527
16601
  ...cfg.scope ? { scope: cfg.scope } : {},
@@ -16529,8 +16603,12 @@ async function signIn(ctx, all, host) {
16529
16603
  port: config.LOOPBACK_PORT,
16530
16604
  onUrl: (url) => ctx.print(`Opening your browser to authorize with ${name}.
16531
16605
  If it didn't open, visit:
16532
- ${url}`, "info")
16606
+ ${url}
16607
+ (no browser here? run it again with --device)`, "info")
16533
16608
  });
16609
+ }
16610
+ async function signIn(ctx, all, host) {
16611
+ const { code, redirectUri } = await browserCode(ctx, all, host);
16534
16612
  ctx.setStatus("exchanging authorization code\u2026");
16535
16613
  const primary = all.primary ?? all.provider ?? "gitlab";
16536
16614
  const res = await splalm.post(host === primary ? "/api/users/loginFromGitLabNative" : `/api/users/login/${host}/native`, { code, redirect_uri: redirectUri });
@@ -16539,8 +16617,8 @@ async function signIn(ctx, all, host) {
16539
16617
  function keepSession(ctx, res) {
16540
16618
  configureClient({ token: res.token });
16541
16619
  startAutoRefresh();
16542
- saveState({ token: res.token, user: res.user });
16543
- ctx.updateSession({ authed: true, user: res.user });
16620
+ saveState({ token: res.token, user: res.user, mode: "server", baseUrl: ctx.session.baseUrl });
16621
+ ctx.updateSession({ authed: true, expired: false, user: res.user, mode: "server" });
16544
16622
  return res;
16545
16623
  }
16546
16624
  async function signInLocal(ctx, username, password) {
@@ -16585,13 +16663,13 @@ async function usePersonalToken(ctx, cfg, token, username) {
16585
16663
  }
16586
16664
  }
16587
16665
  const previous = loadState();
16588
- saveState({ git: stored, baseUrl: ctx.session.baseUrl });
16666
+ saveState({ git: stored, baseUrl: ctx.session.baseUrl, personal: { ...previous.personal, [provider]: stored } });
16589
16667
  if (repos[0]) {
16590
16668
  const url = cloneUrlOf(repos[0].webUrl);
16591
16669
  ctx.setStatus(`trying git on ${repos[0].path} the way get does\u2026`);
16592
16670
  const viaHelper = await gitAsync(undefined, [...credentialOptions2(url), "ls-remote", "--heads", url]);
16593
16671
  if (viaHelper.status !== 0) {
16594
- saveState({ git: previous.git, baseUrl: previous.baseUrl });
16672
+ saveState({ git: previous.git, baseUrl: previous.baseUrl, personal: previous.personal });
16595
16673
  throw new Error(`${name} accepts the token when git is sent it directly, but not through linea's credential helper, which is what get and push use ` + `(${repos[0].path}): ${(viaHelper.stderr || viaHelper.stdout).trim().split(`
16596
16674
  `).slice(-1)[0]}
16597
16675
  ` + ` Set LINEA_DEBUG=1 and run login --token again: ~/.linea/credential.log says whether git asked linea for the token at all.`);
@@ -16599,61 +16677,106 @@ async function usePersonalToken(ctx, cfg, token, username) {
16599
16677
  }
16600
16678
  return `${name} (${cfg.url}) accepted the token${repos[0] ? " for its API and for git, through the credential helper too" : " for its API (it has no SPL repository to try git on yet)"}: get, push and the registry use it from now on.`;
16601
16679
  }
16680
+ var timing = { sleep: (ms, signal) => new Promise((resolve) => {
16681
+ const t = setTimeout(resolve, ms);
16682
+ signal?.addEventListener("abort", () => {
16683
+ clearTimeout(t);
16684
+ resolve();
16685
+ }, { once: true });
16686
+ }) };
16687
+ async function runDeviceFlow(ctx, host, purpose) {
16688
+ const name = hostLabel(host);
16689
+ const start = await splalm.post(`/api/users/device/${host}`);
16690
+ ctx.print(`To sign in with ${name}, open ${start.verificationUri} and enter the code: ${start.userCode}`, "info");
16691
+ const complete = start.verificationUriComplete;
16692
+ if (complete && process.stdout.isTTY && !process.env["SSH_CONNECTION"])
16693
+ open_default(complete).catch(() => {});
16694
+ ctx.setStatus(`waiting for you to approve it with ${name} (code ${start.userCode})\u2026`);
16695
+ const path = purpose === "login" ? `/api/users/login/${host}/device` : `/api/users/identities/${host}/device`;
16696
+ let interval = Math.max(1, start.interval);
16697
+ const deadline = Date.now() + start.expiresIn * 1000;
16698
+ while (Date.now() < deadline) {
16699
+ await timing.sleep(interval * 1000, ctx.signal);
16700
+ if (ctx.signal?.aborted)
16701
+ throw new Error("Cancelled.");
16702
+ const answer = await splalm.post(path, { device_code: start.deviceCode, interval });
16703
+ if (answer["status"] === "pending") {
16704
+ interval = Math.max(interval, Number(answer["interval"] ?? interval));
16705
+ continue;
16706
+ }
16707
+ return answer;
16708
+ }
16709
+ throw new Error("The code expired before it was approved: run the command again.");
16710
+ }
16602
16711
  var login = {
16603
16712
  name: "login",
16604
- summary: "Sign in to LINEA: with your git host (opens your browser), or with your account here when LINEA keeps the repositories itself; --token gives a personal access token for git instead",
16605
- usage: "login [--host gitlab|github|local] [--token <token or file>] [--username name] [--password <password or file>]",
16606
- flags: ["--host name", "--token <token or file>", "--username name", "--password <password or file>"],
16713
+ summary: "Sign in to the LINEA server through one of its remotes: the browser, a code (--device), a token (--token) or, for LINEA git, a password",
16714
+ usage: "login [gitlab|github|local] [--device] [--token <token or file>] [--username name] [--password <password or file>]",
16715
+ flags: ["--device", "--token <token or file>", "--username name", "--password <password or file>", "--host name"],
16607
16716
  run: async (ctx) => {
16608
- const { flags } = parseFlags(ctx.args, { value: { token: undefined, username: undefined, host: undefined, password: undefined } });
16717
+ const { flags, positional } = parseFlags(ctx.args, { value: { token: undefined, username: undefined, host: undefined, password: undefined }, bool: { device: undefined } });
16609
16718
  const given = flagString(flags, "token");
16610
16719
  const personal = given === undefined ? undefined : readToken(given);
16611
16720
  const cfg = await splalm.get("/api/users/config");
16612
- const host = hostToSignIn(cfg, flagString(flags, "host"));
16721
+ const host = hostToSignIn(cfg, positional[0] ?? flagString(flags, "host"));
16722
+ const wasMode = modeOf(ctx.session);
16723
+ const entry = cfg.hosts?.find((h) => h.id === host);
16613
16724
  let username = ctx.session.user?.username;
16614
16725
  if (host === "local") {
16615
- if (personal !== undefined)
16616
- throw new Error("A personal token is for GitLab or GitHub; here you sign in with your account (the git token comes with it).");
16617
16726
  const password = flagString(flags, "password") ?? process.env["LINEA_PASSWORD"];
16618
- username = (await signInLocal(ctx, flagString(flags, "username"), password === undefined ? undefined : readSecret(password))).user.username;
16619
- } else if (personal === undefined || !ctx.session.authed) {
16620
- username = (await signIn(ctx, cfg, host)).user.username;
16621
- }
16622
- if (personal !== undefined) {
16727
+ if (personal !== undefined && password === undefined) {
16728
+ username = keepSession(ctx, await splalm.post("/api/users/login/local/token", { token: personal })).user.username;
16729
+ } else {
16730
+ if (personal !== undefined)
16731
+ throw new Error("For LINEA git give a password or a token, not both.");
16732
+ username = (await signInLocal(ctx, flagString(flags, "username"), password === undefined ? undefined : readSecret(password))).user.username;
16733
+ }
16734
+ } else if (personal !== undefined) {
16735
+ let res;
16736
+ try {
16737
+ res = await splalm.post(`/api/users/login/${host}/token`, { token: personal });
16738
+ } catch (e) {
16739
+ if (!(e instanceof SplalmError && e.status === 404) || !ctx.session.authed)
16740
+ throw e;
16741
+ }
16742
+ if (res)
16743
+ username = keepSession(ctx, res).user.username;
16623
16744
  ctx.print(await usePersonalToken(ctx, configOf(cfg, host), personal, flagString(flags, "username")), "info");
16624
- return `\u2713 Signed in${username ? ` as ${username}` : ""}.`;
16745
+ return `\u2713 Signed in${username ? ` as ${username}` : ""}.${modeChange(wasMode)}`;
16746
+ } else if (flags["device"]) {
16747
+ if (!entry?.device)
16748
+ throw new Error(`This LINEA has no sign-in with a code for ${hostLabel(host)}${entry ? " (its server is older than this CLI, or an administrator turned it off)" : ""}: use the browser (login ${host}) or a token (login ${host} --token <token or file>).`);
16749
+ const res = await runDeviceFlow(ctx, host, "login");
16750
+ username = keepSession(ctx, res).user.username;
16751
+ } else {
16752
+ username = (await signIn(ctx, cfg, host)).user.username;
16625
16753
  }
16626
- const git = await storeGitCredentials(ctx.session.baseUrl);
16754
+ const git = await storeGitCredentials(ctx.session.baseUrl, { host });
16627
16755
  ctx.print(git ? `Git access to ${git} is set up too: get and push work.` : "This LINEA server did not give git access (it may be older than this CLI). Give a personal access token for your git host: login --token <token or file>", "info");
16628
- return `\u2713 Signed in as ${username}.`;
16756
+ const others = (cfg.hosts ?? []).filter((h) => h.id !== host).map((h) => h.id);
16757
+ if (others.length)
16758
+ ctx.print(`This LINEA also has: ${others.join(", ")} (login <remote> to sign in with one, remote link <remote> to add an account)`, "info");
16759
+ return `\u2713 Signed in as ${username} with ${hostLabel(host)}.${modeChange(wasMode)}
16760
+ ${contextLine(ctx.session)}`;
16629
16761
  }
16630
16762
  };
16763
+ var modeChange = (was) => was === "offline" ? " Mode is now: server (it was offline)." : "";
16631
16764
  function readSecret(value) {
16632
16765
  return (fs10.existsSync(value) && fs10.statSync(value).isFile() ? fs10.readFileSync(value, "utf8") : value).replace(/\r?\n$/, "");
16633
16766
  }
16634
- var profile = {
16635
- name: "profile",
16636
- summary: "The git host you are working on (your profile) when you have accounts on more than one: profile, or profile <host> to switch",
16637
- usage: "profile [gitlab|github|local]",
16638
- run: async (ctx) => {
16639
- if (!ctx.session.authed)
16640
- return "Not signed in. Run: login";
16641
- const wanted = ctx.args.find((arg) => !arg.startsWith("-"));
16642
- const answer = wanted ? await splalm.put("/api/users/profile", { host: wanted }) : await splalm.post("/api/users/loginFromServiceToken").then((res) => res.user);
16643
- if (wanted) {
16644
- await storeGitCredentials(ctx.session.baseUrl, { force: true });
16645
- return `\u2713 Working on ${hostLabel(answer.activeHost ?? wanted)} now.`;
16646
- }
16647
- return [`Working on: ${answer.activeHost ? hostLabel(answer.activeHost) : "none (none of your hosts is on)"}`, `Accounts: ${(answer.hosts ?? []).map(hostLabel).join(", ") || "\u2014"}`].join(`
16648
- `);
16767
+ async function storeGitCredentials(server, { force = false, host } = {}) {
16768
+ const state = loadState();
16769
+ const wanted = host ?? state.user?.activeHost ?? undefined;
16770
+ const mine = wanted ? state.personal?.[wanted] : undefined;
16771
+ if (mine && mine.server === server) {
16772
+ saveState({ git: mine });
16773
+ return hostLabel(mine.provider);
16649
16774
  }
16650
- };
16651
- async function storeGitCredentials(server, { force = false } = {}) {
16652
- const kept = loadState().git;
16653
- if (!force && kept?.source === "token" && kept.server === server)
16775
+ const kept = state.git;
16776
+ if (!force && kept?.source === "token" && kept.server === server && (!wanted || kept.provider === wanted))
16654
16777
  return hostLabel(kept.provider);
16655
16778
  try {
16656
- const creds = await splalm.get("/api/users/git-credentials");
16779
+ const creds = await splalm.get(`/api/users/git-credentials${wanted ? `?host=${wanted}` : ""}`);
16657
16780
  if (!creds?.token)
16658
16781
  throw new Error("no token");
16659
16782
  saveState({ git: { ...creds, server, source: "server" } });
@@ -16665,7 +16788,7 @@ async function storeGitCredentials(server, { force = false } = {}) {
16665
16788
  }
16666
16789
  var logout = {
16667
16790
  name: "logout",
16668
- summary: "Sign out and clear stored credentials",
16791
+ summary: "Sign out of the LINEA server and clear what was stored for the sign-in (the mode stays)",
16669
16792
  usage: "logout",
16670
16793
  run: async (ctx) => {
16671
16794
  try {
@@ -16673,32 +16796,234 @@ var logout = {
16673
16796
  } catch {}
16674
16797
  configureClient({ token: "" });
16675
16798
  clearAuth();
16676
- ctx.updateSession({ authed: false, user: undefined });
16677
- return "Signed out.";
16799
+ ctx.updateSession({ authed: false, expired: false, user: undefined });
16800
+ return modeOf(ctx.session) === "server" ? `Signed out. Still in server mode (${shortServer(ctx.session.baseUrl)}): login to sign in again, or mode offline to work on this machine only.` : "Signed out. Offline: nothing here needed the server.";
16678
16801
  }
16679
16802
  };
16803
+ function gitAccessText(session) {
16804
+ const git = storedGit();
16805
+ if (process.env["LINEA_GIT_TOKEN"] || process.env["GITLAB_TOKEN"] || process.env["GITHUB_TOKEN"])
16806
+ return "from the environment";
16807
+ return git ? `${hostLabel(git.provider)} as ${git.username} (${git.source === "token" ? "your personal token" : "given by LINEA"})` : `none (login, or login --token <token or file>)`;
16808
+ }
16680
16809
  var whoami = {
16681
16810
  name: "whoami",
16682
- aliases: ["me"],
16683
- summary: "Show the signed-in user and current context",
16811
+ aliases: ["me", "account"],
16812
+ summary: "Where you are: the mode, the server, who you are, the remote you work on and the accounts you have",
16684
16813
  usage: "whoami",
16685
16814
  run: async (ctx) => {
16686
- if (!ctx.session.authed)
16687
- return "Not signed in. Run: login";
16688
- const res = await splalm.post("/api/users/loginFromServiceToken");
16689
- configureClient({ token: res.token });
16690
- saveState({ token: res.token, user: res.user });
16691
- ctx.updateSession({ authed: true, user: res.user });
16692
- const git = await storeGitCredentials(ctx.session.baseUrl);
16815
+ const lines = [];
16816
+ const fromEnv = process.env["LINEA_BASE_URL"] ? " (from LINEA_BASE_URL)" : "";
16817
+ if (modeOf(ctx.session) === "server" && ctx.session.authed) {
16818
+ try {
16819
+ const res = await splalm.post("/api/users/loginFromServiceToken");
16820
+ configureClient({ token: res.token });
16821
+ saveState({ token: res.token, user: res.user });
16822
+ ctx.updateSession({ authed: true, expired: false, user: res.user });
16823
+ await storeGitCredentials(ctx.session.baseUrl);
16824
+ } catch (e) {
16825
+ if (!(e instanceof SessionExpiredError))
16826
+ throw e;
16827
+ ctx.updateSession({ expired: true });
16828
+ }
16829
+ }
16830
+ const s = ctx.session;
16831
+ lines.push(contextLine(s));
16832
+ lines.push(` mode: ${modeOf(s)}${s.modeOverride ? " (this command only)" : ""}${modeOf(s) === "offline" ? " this machine only: mode server connects to LINEA" : ""}`);
16833
+ lines.push(` server: ${s.baseUrl}${fromEnv}${modeOf(s) === "offline" ? " (not used while offline)" : ""}`);
16834
+ if (s.user) {
16835
+ const checked = modeOf(s) === "server" && !s.expired;
16836
+ lines.push(` signed in: ${s.user.username}${checked ? "" : " (as of the last sign in; not checked now)"}`);
16837
+ lines.push(` remote: ${s.user.activeHost ? hostLabel(s.user.activeHost) : "none (none of your remotes is on)"} (the one you work on: remote use <name>)`);
16838
+ lines.push(` accounts: ${(s.user.hosts ?? []).map((h) => hostLabel(h)).join(", ") || "\u2014"}`);
16839
+ } else {
16840
+ lines.push(" signed in: no" + (modeOf(s) === "server" ? " (login)" : ""));
16841
+ }
16842
+ lines.push(` git access: ${gitAccessText(s)}`);
16843
+ return lines.join(`
16844
+ `);
16845
+ }
16846
+ };
16847
+ function keepRemotes(ctx, answer) {
16848
+ const user = { ...ctx.session.user ?? { userId: "", username: "" }, hosts: answer.hosts ?? [], activeHost: answer.activeHost ?? null };
16849
+ saveState({ user });
16850
+ ctx.updateSession({ user });
16851
+ }
16852
+ var profile = {
16853
+ name: "profile",
16854
+ hidden: true,
16855
+ summary: "Same as remote",
16856
+ usage: "profile [gitlab|github|local]",
16857
+ run: async (ctx) => {
16858
+ const wanted = ctx.args.find((arg) => !arg.startsWith("-"));
16859
+ return commandNamed(wanted ? "remote use" : "remote").run(ctx);
16860
+ }
16861
+ };
16862
+ var authCommands = [login, logout, whoami, profile];
16863
+
16864
+ // src/commands/remote.ts
16865
+ var nameOf = (h) => h.id === "local" || !h.url ? hostLabel(h.id) : `${hostLabel(h.id)} (${shortServer(h.url)})`;
16866
+ var methodsOf = (h) => [h.id === "local" || h.password ? "password" : "browser", ...h.device ? ["code"] : [], "token"].join(", ");
16867
+ async function refresh(ctx) {
16868
+ const res = await splalm.post("/api/users/loginFromServiceToken");
16869
+ keepRemotes(ctx, { hosts: res.user.hosts ?? [], activeHost: res.user.activeHost ?? null });
16870
+ return { hosts: res.user.hosts ?? [], activeHost: res.user.activeHost ?? null };
16871
+ }
16872
+ var remote = {
16873
+ name: "remote",
16874
+ summary: "The remotes of the LINEA server: which you have an account on, which one you work on, how to sign in with each",
16875
+ usage: "remote \xB7 remote use <name> \xB7 remote link <name> [--device] \xB7 remote unlink <name>",
16876
+ where: "server",
16877
+ run: async (ctx) => {
16878
+ const cfg = await splalm.get("/api/users/config");
16879
+ const mine = await refresh(ctx);
16880
+ const hosts = cfg.hosts ?? [];
16881
+ const own = mine.hosts[0];
16882
+ const width = Math.max(...hosts.map((h) => nameOf(h).length), 8);
16883
+ const rows = hosts.map((h) => {
16884
+ const has = mine.hosts.includes(h.id);
16885
+ const on = mine.activeHost === h.id;
16886
+ const state = has ? h.id === own ? "your sign-in account" : "linked" : h.id === "local" ? "no account (an administrator makes it)" : `not linked \u2192 remote link ${h.id}`;
16887
+ return ` ${on ? "\u25CF" : " "} ${nameOf(h).padEnd(width)} ${state.padEnd(24)} sign in with: ${methodsOf(h)}`;
16888
+ });
16693
16889
  return [
16694
- `${res.user.username} (id ${res.user.userId})`,
16695
- ` server: ${ctx.session.baseUrl}`,
16696
- ` git access: ${git ?? "none (login --token <token or file>)"}`
16890
+ `Remotes of ${shortServer(ctx.session.baseUrl)} (\u25CF = the one you work on):`,
16891
+ ...rows,
16892
+ "",
16893
+ "Work on another: remote use <name> \xB7 add an account: remote link <name> \xB7 drop one: remote unlink <name>"
16697
16894
  ].join(`
16698
16895
  `);
16699
16896
  }
16700
16897
  };
16701
- var authCommands = [login, logout, whoami, profile];
16898
+ var hostArg = (ctx, what) => {
16899
+ const name = ctx.args.find((a) => !a.startsWith("-"));
16900
+ if (!name)
16901
+ throw new Error(`Usage: ${what} <gitlab|github|local>`);
16902
+ return name;
16903
+ };
16904
+ var use = {
16905
+ name: "remote use",
16906
+ summary: "Work on another remote (the web page follows: it is the same choice)",
16907
+ usage: "remote use <gitlab|github|local>",
16908
+ where: "server",
16909
+ run: async (ctx) => {
16910
+ const host = hostArg(ctx, "remote use");
16911
+ const answer = await splalm.put("/api/users/profile", { host });
16912
+ keepRemotes(ctx, answer);
16913
+ await storeGitCredentials(ctx.session.baseUrl, { force: true, host: answer.activeHost ?? host });
16914
+ return `\u2713 Working on ${hostLabel(answer.activeHost ?? host)} now (the web page too).`;
16915
+ }
16916
+ };
16917
+ var link = {
16918
+ name: "remote link",
16919
+ summary: "Add your account on another remote to yours here (browser, or --device for a machine with no browser)",
16920
+ usage: "remote link <gitlab|github> [--device]",
16921
+ flags: ["--device"],
16922
+ where: "server",
16923
+ run: async (ctx) => {
16924
+ const { flags } = parseFlags(ctx.args, { bool: { device: undefined } });
16925
+ const host = hostArg(ctx, "remote link");
16926
+ if (host === "local")
16927
+ return "\u2717 LINEA git accounts are not linked: they sign in with a password (login local).";
16928
+ const cfg = await splalm.get("/api/users/config");
16929
+ hostToSignIn(cfg, host);
16930
+ let answer;
16931
+ if (flags["device"]) {
16932
+ answer = await runDeviceFlow(ctx, host, "link");
16933
+ } else {
16934
+ const { code, redirectUri } = await browserCode(ctx, cfg, host);
16935
+ answer = await splalm.post(`/api/users/identities/${host}/native`, { code, redirect_uri: redirectUri });
16936
+ }
16937
+ keepRemotes(ctx, answer);
16938
+ return `\u2713 ${hostLabel(host)} account linked. Work on it with: remote use ${host}`;
16939
+ }
16940
+ };
16941
+ var unlink = {
16942
+ name: "remote unlink",
16943
+ summary: "Forget your account on a remote (not the one you sign in with)",
16944
+ usage: "remote unlink <gitlab|github>",
16945
+ where: "server",
16946
+ run: async (ctx) => {
16947
+ const host = hostArg(ctx, "remote unlink");
16948
+ const answer = await splalm.del(`/api/users/identities/${host}`);
16949
+ const wasActive = loadState().user?.activeHost === host;
16950
+ keepRemotes(ctx, answer);
16951
+ if (wasActive)
16952
+ await storeGitCredentials(ctx.session.baseUrl, { force: true });
16953
+ return `\u2713 ${hostLabel(host)} account unlinked.${wasActive ? ` You work on ${answer.activeHost ? hostLabel(answer.activeHost) : "none"} now.` : ""}`;
16954
+ }
16955
+ };
16956
+ var remoteCommands = [remote, use, link, unlink];
16957
+
16958
+ // src/commands/mode.ts
16959
+ var mode = {
16960
+ name: "mode",
16961
+ summary: "Show or choose the mode: server (the LINEA server) or offline (this machine only)",
16962
+ usage: "mode [server|offline]",
16963
+ run: ({ args, session, updateSession }) => {
16964
+ const wanted = args.find((a) => !a.startsWith("-"));
16965
+ if (!wanted) {
16966
+ return [
16967
+ contextLine(session),
16968
+ " server: the LINEA server and its remotes: your SPLs there, push, pipelines (mode server)",
16969
+ " offline: this machine only: SPLs in folders, generate here, no server asked (mode offline)",
16970
+ ` now: ${modeOf(session)}${session.modeOverride ? " (this command only)" : ""} \xB7 server: ${shortServer(session.baseUrl)} \xB7 --offline works for one command`
16971
+ ].join(`
16972
+ `);
16973
+ }
16974
+ if (wanted !== "server" && wanted !== "offline")
16975
+ return "Usage: mode [server|offline]";
16976
+ updateSession({ mode: wanted, modeOverride: false });
16977
+ saveState({ mode: wanted });
16978
+ if (wanted === "offline")
16979
+ return `\u2713 Offline: this machine only; the server is not asked. mode server to connect again.`;
16980
+ return session.authed ? `\u2713 Server mode.
16981
+ ${contextLine({ ...session, mode: "server", modeOverride: false })}` : `\u2713 Server mode (${shortServer(session.baseUrl)}). You are not signed in: login [remote]`;
16982
+ }
16983
+ };
16984
+ var online2 = { name: "online", hidden: true, summary: "Same as mode server", run: (ctx) => commandNamed("mode").run({ ...ctx, args: ["server"] }) };
16985
+ var offline = { name: "offline", hidden: true, summary: "Same as mode offline", run: (ctx) => commandNamed("mode").run({ ...ctx, args: ["offline"] }) };
16986
+ function normalizeServer(given) {
16987
+ const withScheme = /^https?:\/\//.test(given) ? given : /^(localhost|127\.|\[::1\])/.test(given) ? `http://${given}` : `https://${given}`;
16988
+ return withScheme.replace(/\/+$/, "");
16989
+ }
16990
+ var server = {
16991
+ name: "server",
16992
+ summary: "The LINEA server: show it and the remotes it has, or point linea at another one (that signs you out)",
16993
+ usage: "server [url] [--yes]",
16994
+ flags: ["--yes"],
16995
+ run: async (ctx) => {
16996
+ const given = ctx.args.find((a) => !a.startsWith("-"));
16997
+ if (!given) {
16998
+ const lines = [contextLine(ctx.session), ` server: ${ctx.session.baseUrl}${process.env["LINEA_BASE_URL"] ? " (from LINEA_BASE_URL)" : ""}`];
16999
+ try {
17000
+ const cfg = await splalm.get("/api/users/config");
17001
+ lines.push(" reachable: yes");
17002
+ lines.push(` remotes: ${(cfg.hosts ?? []).map((h) => `${h.id}${h.id === cfg.primary ? " (primary)" : ""}`).join(", ") || "\u2014"}`);
17003
+ } catch {
17004
+ lines.push(" reachable: no (check the address; mode offline works without it)");
17005
+ }
17006
+ return lines.join(`
17007
+ `);
17008
+ }
17009
+ const baseUrl = normalizeServer(given);
17010
+ if (baseUrl === ctx.session.baseUrl.replace(/\/+$/, ""))
17011
+ return `Already on ${baseUrl}.`;
17012
+ if (ctx.session.authed && !ctx.args.includes("--yes")) {
17013
+ return `\u2717 Changing the server signs you out of ${shortServer(ctx.session.baseUrl)}. Run it again with --yes: server ${given} --yes`;
17014
+ }
17015
+ try {
17016
+ if (ctx.session.authed)
17017
+ await splalm.post("/api/users/logout");
17018
+ } catch {}
17019
+ configureClient({ baseUrl, token: "" });
17020
+ clearAuth();
17021
+ saveState({ baseUrl, mode: "server" });
17022
+ ctx.updateSession({ baseUrl, mode: "server", authed: false, expired: false, user: undefined });
17023
+ return `\u2713 Server: ${baseUrl}. Signed out; mode is server. login [remote] to sign in.`;
17024
+ }
17025
+ };
17026
+ var modeCommands = [mode, online2, offline, server];
16702
17027
 
16703
17028
  // src/core/editor.ts
16704
17029
  import { spawn, spawnSync } from "child_process";
@@ -16778,7 +17103,8 @@ var config2 = {
16778
17103
  summary: "Show the settings, or set one: workspace, editor, server, theme",
16779
17104
  usage: "config [workspace|editor|server|theme] [value] (config <folder> still sets the workspace)",
16780
17105
  arg: "file",
16781
- run: ({ args, session, updateSession }) => {
17106
+ run: (ctx) => {
17107
+ const { args, session, updateSession } = ctx;
16782
17108
  const [first, value] = args.filter((a) => !a.startsWith("--"));
16783
17109
  const unset = args.includes("--unset");
16784
17110
  if (!first) {
@@ -16796,6 +17122,7 @@ var config2 = {
16796
17122
  ` editor ${session.editor ?? "(automatic)"} \u2192 ${editor}`,
16797
17123
  ` server ${session.baseUrl}`,
16798
17124
  ` theme ${resolveTheme(process.env["LINEA_THEME"], session.theme).name} the colours of the window (config theme lists them)`,
17125
+ ` mode ${session.mode ?? (session.authed ? "server" : "offline")} (mode server|offline)`,
16799
17126
  ` signed in ${session.authed ? session.user?.username ?? "yes" : "no"}`,
16800
17127
  "",
16801
17128
  "Change one with: config <setting> <value> (config editor --unset goes back to automatic)."
@@ -16845,14 +17172,7 @@ var config2 = {
16845
17172
  return `\u2713 Theme set to ${found.name}. It applies the next time you open linea.`;
16846
17173
  }
16847
17174
  case "server": {
16848
- if (!given)
16849
- return `server: ${session.baseUrl}`;
16850
- if (!/^https?:\/\//.test(given))
16851
- throw new Error("The server is an address: http://\u2026 or https://\u2026");
16852
- const baseUrl = given.replace(/\/+$/, "");
16853
- configureClient({ baseUrl });
16854
- updateSession({ baseUrl });
16855
- return `\u2713 Server set to ${given}. Sign in again with: login`;
17175
+ return commandNamed("server").run({ ...ctx, args: given ? [given, ...args.filter((a) => a === "--yes")] : [] });
16856
17176
  }
16857
17177
  }
16858
17178
  }
@@ -47551,20 +47871,6 @@ var Bango = class {
47551
47871
  // src/core/workspace.ts
47552
47872
  configureWorkspace({ createEngine: () => new Bango, sourceOf: (folders) => packageSourceOf(folders) });
47553
47873
 
47554
- // src/commands/lookup.ts
47555
- var find = () => {
47556
- return;
47557
- };
47558
- function setLookup(fn) {
47559
- find = fn;
47560
- }
47561
- function commandNamed(name) {
47562
- const cmd = find(name);
47563
- if (!cmd)
47564
- throw new Error(`Internal: no command "${name}".`);
47565
- return cmd;
47566
- }
47567
-
47568
47874
  // src/core/uvlview.ts
47569
47875
  var GROUPS2 = { mandatory: "mandatory", optional: "optional", or: "or", alternative: "alternative" };
47570
47876
  var MARK = { root: "\u25A0", mandatory: "\u25CF", optional: "\u25CB", or: "\u25C6", alternative: "\u25C7", group: "\u25AB" };
@@ -48205,6 +48511,7 @@ var list2 = {
48205
48511
  };
48206
48512
  var show3 = {
48207
48513
  name: "product show",
48514
+ where: "both",
48208
48515
  summary: "One product: its features, languages, version, models, and what LINEA says of its merge requests",
48209
48516
  usage: "product show [product]",
48210
48517
  arg: "product",
@@ -48228,7 +48535,7 @@ var show3 = {
48228
48535
  ];
48229
48536
  if (isModularLine2(lineDir))
48230
48537
  lines.push("", await describeProductModels(session, name));
48231
- const merge = origin?.productId && session.authed && !session.local ? await mergeRequestsOf(origin.productId) : undefined;
48538
+ const merge = origin?.productId && online(session) ? await mergeRequestsOf(origin.productId) : undefined;
48232
48539
  if (merge)
48233
48540
  lines.push("", merge);
48234
48541
  return lines.join(`
@@ -48708,8 +49015,8 @@ var clone = {
48708
49015
  const target = positional[0];
48709
49016
  if (!target)
48710
49017
  return "Usage: clone <spl>[:product] [--products all|none|a,b] [--dir folder]";
48711
- if (!session.authed)
48712
- throw new Error("Sign in first: login (it asks the server where your SPLs are).");
49018
+ if (!online(session))
49019
+ throw new Error(needsServerText("get <spl>", session));
48713
49020
  const [lineArg, productArg] = target.split(":");
48714
49021
  setStatus("asking LINEA for your SPLs\u2026");
48715
49022
  const enrolled = await splalm.get("/api/lines/enrolled");
@@ -48917,10 +49224,10 @@ var push = {
48917
49224
  const direct = Boolean(flags["direct"]);
48918
49225
  const here = findContext(session.cwd ?? process.cwd());
48919
49226
  if (here.line && !isRepo(here.line.dir)) {
48920
- if (!session.authed || session.local) {
48921
- return `${path14.basename(here.line.dir)} is only on this machine. Sign in (login) and push uploads it to LINEA.`;
49227
+ if (!online(session)) {
49228
+ return `${path14.basename(here.line.dir)} is only on this machine. In server mode (mode server, then login), push uploads it to LINEA.`;
48922
49229
  }
48923
- return link.run(ctx);
49230
+ return link2.run(ctx);
48924
49231
  }
48925
49232
  const scope = checkoutsInScope(session);
48926
49233
  if (!scope.length)
@@ -48978,15 +49285,15 @@ var push = {
48978
49285
  }
48979
49286
  };
48980
49287
  var isProductDir = (dir) => fs15.existsSync(path14.join(dir, ".linea", "spec.json"));
48981
- var link = {
49288
+ var link2 = {
48982
49289
  name: "link",
48983
49290
  summary: "Upload an SPL made here to LINEA: it is created there, and this folder becomes its checkout",
48984
49291
  usage: "link [--desc text] [--namespace id]",
48985
49292
  flags: ["--desc text", "--namespace id"],
48986
49293
  run: async ({ args, session, setStatus }) => {
48987
49294
  const { flags } = parseFlags(args, { value: { desc: undefined, namespace: undefined } });
48988
- if (!session.authed)
48989
- throw new Error("Sign in first: login.");
49295
+ if (!online(session))
49296
+ throw new Error(needsServerText("link", session));
48990
49297
  const folder = findContext(session.cwd ?? process.cwd());
48991
49298
  const lineDir = folder.line?.dir;
48992
49299
  if (!lineDir)
@@ -49411,9 +49718,9 @@ var catalogCommands = [list3, add, remove];
49411
49718
  import fs17 from "fs";
49412
49719
  var workdirOf3 = (session) => session.workdir ?? defaultDataDir();
49413
49720
  var LOCATION3 = /^(gitlab|github):/;
49414
- var online = (session) => session.authed && !session.local;
49415
49721
  var splList = {
49416
49722
  name: "spl list",
49723
+ where: "both",
49417
49724
  summary: "Your SPLs: the ones on this machine and the ones on LINEA, side by side",
49418
49725
  usage: "spl list [--local]",
49419
49726
  flags: ["--local"],
@@ -49428,10 +49735,8 @@ var splList = {
49428
49735
  byLineId.set(origin.lineId, row);
49429
49736
  }
49430
49737
  let note = "";
49431
- if (!session.authed)
49432
- note = "Not signed in: login shows the SPLs of LINEA too.";
49433
- else if (session.local)
49434
- note = "";
49738
+ if (!online(session))
49739
+ note = modeOf(session) === "offline" ? "Offline: only the SPLs on this machine. mode server shows the SPLs of LINEA too." : "";
49435
49740
  else {
49436
49741
  try {
49437
49742
  for (const l of await splalm.get("/api/lines/enrolled")) {
@@ -49460,6 +49765,7 @@ var splList = {
49460
49765
  };
49461
49766
  var splNew = {
49462
49767
  name: "spl new",
49768
+ where: "both",
49463
49769
  summary: "Create an SPL. Made of modules by default (--plain for the classic kind); signed in, it is made on LINEA and comes to your folder",
49464
49770
  usage: "spl new <name> [--modules gitlab:g/m,github:o/m] [--plain] [--desc text] [--namespace id] [--local]",
49465
49771
  flags: ["--modules a,b", "--plain", "--desc text", "--namespace id", "--local"],
@@ -49482,8 +49788,7 @@ var splNew = {
49482
49788
  const out = [createModularLineHere(session, name, tracked.ctx.updateSession)];
49483
49789
  for (const m of modules)
49484
49790
  out.push(String(await commandNamed("spl add").run({ ...tracked.now(), args: [m] })));
49485
- if (!session.authed && !session.local)
49486
- out.push("It is only on this machine: sign in (login) and push uploads it to LINEA.");
49791
+ out.push("Offline: it is only on this machine. After `mode server` (and login), push uploads it to LINEA.");
49487
49792
  return out.join(`
49488
49793
  `);
49489
49794
  }
@@ -49515,6 +49820,7 @@ function trackSession(ctx) {
49515
49820
  }
49516
49821
  var productNew = {
49517
49822
  name: "product new",
49823
+ where: "both",
49518
49824
  summary: "Create a product: a name and the features it selects, or a spec file. In an SPL that is on LINEA it is made there and comes to your folder",
49519
49825
  usage: "product new <name> [--features A,B] [--version x.y.z] [--local] | product new --from <spec.json>",
49520
49826
  flags: ["--from spec.json", "--features A,B", "--version x.y.z", "--local"],
@@ -49943,6 +50249,7 @@ async function runChecks(session, opts) {
49943
50249
  } catch (e) {
49944
50250
  checks.push({ level: "warn", label: "editor", detail: e.message });
49945
50251
  }
50252
+ checks.push({ level: "ok", label: "mode", detail: `${modeOf(session)}${modeOf(session) === "offline" ? " (this machine only)" : ` (${session.baseUrl})`}` });
49946
50253
  try {
49947
50254
  const { config, source } = gitSettings();
49948
50255
  const where = config.provider === "github" ? config.github?.webUrl ?? "github.com" : config.provider === "local" ? config.local?.baseUrl ?? "" : config.gitlab?.url ?? "";
@@ -50010,6 +50317,8 @@ var setupCommands = [init, doctor, cd];
50010
50317
  var commands = [
50011
50318
  ...helpCommands,
50012
50319
  ...authCommands,
50320
+ ...remoteCommands,
50321
+ ...modeCommands,
50013
50322
  ...configCommands,
50014
50323
  ...setupCommands,
50015
50324
  ...bridgeCommands,
@@ -50063,20 +50372,32 @@ function resolveCommand(tokens) {
50063
50372
 
50064
50373
  // src/commands/dispatch.ts
50065
50374
  function splitGlobals(tokens) {
50066
- return { rest: tokens.filter((t) => t !== "--json" && t !== "--local"), json: tokens.includes("--json"), local: tokens.includes("--local") };
50375
+ const words = ["--json", "--offline", "--local"];
50376
+ return { rest: tokens.filter((t) => !words.includes(t)), json: tokens.includes("--json"), offline: tokens.includes("--offline") || tokens.includes("--local") };
50067
50377
  }
50378
+ function gate(cmd, session) {
50379
+ const where = cmd.where ?? (cmd.requiresAuth ? "server" : "machine");
50380
+ if (where === "machine")
50381
+ return;
50382
+ if (online(session))
50383
+ return;
50384
+ if (where === "both" && modeOf(session) === "offline")
50385
+ return;
50386
+ return needsServerText(cmd.name, session);
50387
+ }
50388
+ var showsContext = (cmd) => (cmd.where ?? (cmd.requiresAuth ? "server" : "machine")) !== "machine";
50068
50389
  var firstPositional = (args) => args.find((a) => !a.startsWith("-"));
50069
50390
  async function execute(opts) {
50070
- const { rest, json, local } = splitGlobals(opts.tokens);
50071
- const session = { ...opts.session, ...json ? { json } : {}, ...local ? { local } : {} };
50391
+ const { rest, json, offline } = splitGlobals(opts.tokens);
50392
+ const session = { ...opts.session, ...json ? { json } : {}, ...offline ? { mode: "offline", modeOverride: true } : {} };
50072
50393
  const resolved = resolveCommand(rest);
50073
50394
  if ("error" in resolved)
50074
50395
  return { code: 2, text: resolved.error, error: true, json };
50075
50396
  const { cmd } = resolved;
50076
50397
  let { args } = resolved;
50077
- if (cmd.requiresAuth && !session.authed) {
50078
- return { code: 1, text: `${cmd.name} needs you signed in: run login`, error: true, json };
50079
- }
50398
+ const refused = gate(cmd, session);
50399
+ if (refused)
50400
+ return { code: 1, text: refused, error: true, json, context: contextLine(session) };
50080
50401
  if (cmd.arg === "product" && opts.folder?.product && !firstPositional(args))
50081
50402
  args = [opts.folder.product.name, ...args];
50082
50403
  let data;
@@ -50102,6 +50423,7 @@ async function execute(opts) {
50102
50423
  return {
50103
50424
  code: usage ? 2 : failed ? 1 : 0,
50104
50425
  text,
50426
+ ...showsContext(cmd) ? { context: contextLine(ctx.session) } : {},
50105
50427
  ...usage ? { error: true } : {},
50106
50428
  ...data !== undefined ? { data } : {},
50107
50429
  json
@@ -50117,7 +50439,7 @@ function render2(outcome) {
50117
50439
  }
50118
50440
 
50119
50441
  // src/shell.ts
50120
- var KEPT = ["baseUrl", "user", "workdir", "editor", "theme"];
50442
+ var KEPT = ["baseUrl", "user", "workdir", "editor", "theme", "mode"];
50121
50443
  function persistSession2(patch) {
50122
50444
  const kept = {};
50123
50445
  for (const key of KEPT)
@@ -50147,6 +50469,9 @@ async function runShell2(argv, out = process.stdout, err = process.stderr) {
50147
50469
  };
50148
50470
  const outcome = await execute({ tokens: argv, session, folder, hooks });
50149
50471
  const text = render2(outcome);
50472
+ if (outcome.context && !outcome.json)
50473
+ err.write(`${colorize(outcome.context, Boolean(err.isTTY) && !process.env["NO_COLOR"])}
50474
+ `);
50150
50475
  const colour = Boolean(out.isTTY) && !outcome.json && !outcome.error && !process.env["NO_COLOR"];
50151
50476
  if (text)
50152
50477
  (outcome.error && !outcome.json ? err : out).write(`${colorize(text, colour)}
@@ -50154,4 +50479,4 @@ async function runShell2(argv, out = process.stdout, err = process.stderr) {
50154
50479
  return outcome.code;
50155
50480
  }
50156
50481
 
50157
- export { onTokenRefreshed, startAutoRefresh, splalm, findContext, displayPath, buildSession, guideState, tipsFor, commandOfTip, rankCommands, guideStateAsync, theme, TONE_COLOR, parseLine, clip, brief, KEYS_HELP, tokenize, placesFrom, describePlace, getCommand, visibleCommands, resolveCommand, execute, render2, persistSession2, runShell2 };
50482
+ export { onTokenRefreshed, startAutoRefresh, splalm, findContext, displayPath, buildSession, modeOf, online, contextLine, guideState, tipsFor, commandOfTip, rankCommands, guideStateAsync, theme, TONE_COLOR, parseLine, clip, brief, KEYS_HELP, tokenize, placesFrom, describePlace, getCommand, visibleCommands, resolveCommand, execute, render2, persistSession2, runShell2 };