@thatopen/services 0.35.0 → 0.36.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 (40) hide show
  1. package/dist/built-in/index.d.ts +13 -13
  2. package/dist/cli/lib/browser-session.d.ts +17 -0
  3. package/dist/cli/lib/config.d.ts +6 -0
  4. package/dist/cli.js +334 -38
  5. package/dist/cli.js.map +1 -1
  6. package/dist/core/browser-sign-in.d.ts +50 -0
  7. package/dist/core/browser-sign-in.test.d.ts +1 -0
  8. package/dist/core/builtin-recipes/index.d.ts +2 -2
  9. package/dist/core/builtin-recipes/layer-to-native.d.ts +19 -0
  10. package/dist/core/builtin-recipes/records-to-native.d.ts +43 -0
  11. package/dist/core/builtin-recipes/shapes-to-families.d.ts +9 -4
  12. package/dist/core/builtin-recipes/shared.d.ts +8 -11
  13. package/dist/core/channel.d.ts +1 -1
  14. package/dist/core/client.d.ts +46 -2
  15. package/dist/core/frag-items.d.ts +1 -1
  16. package/dist/core/history.d.ts +9 -9
  17. package/dist/core/op-builder.d.ts +2 -2
  18. package/dist/core/platform-client.d.ts +6 -3
  19. package/dist/core/project-recipes.d.ts +1 -1
  20. package/dist/core/recipes.d.ts +31 -5
  21. package/dist/index.cjs.js +23 -20
  22. package/dist/index.cjs.js.map +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.es.js +4284 -3455
  25. package/dist/index.es.js.map +1 -1
  26. package/docs/ai-quickstart.md +21 -21
  27. package/docs/builtin/paths.json +1 -1
  28. package/docs/cli/login.md +6 -3
  29. package/docs/client/paths.json +2 -2
  30. package/docs/flow-architecture.md +53 -53
  31. package/docs/flow-plugin-guide.md +13 -13
  32. package/docs/recipes-guide.md +24 -24
  33. package/docs/rhino-interop-quickstart.md +1 -1
  34. package/package.json +1 -1
  35. package/src/built-in/UIManager/src/git-history-panel/example.ts +2 -2
  36. package/src/built-in/index.ts +13 -13
  37. package/src/core/examples/channel.ts +2 -2
  38. package/src/core/examples/history.ts +4 -4
  39. package/dist/core/builtin-recipes/records-to-revit.d.ts +0 -28
  40. package/dist/core/builtin-recipes/rhino-to-revit.d.ts +0 -16
@@ -2046,7 +2046,7 @@ export declare const GISManager: typeof _GISManager & {
2046
2046
  export interface RevitFlowChange {
2047
2047
  /** create → element added, update → geometry/data changed, delete → removed. */
2048
2048
  type: "create" | "update" | "delete" | string;
2049
- /** Revit UniqueId (GUID). Resolves to a fragments localId via getLocalIdsByGuids. */
2049
+ /** The authoring tool's UniqueId (GUID). Resolves to a fragments localId via getLocalIdsByGuids. */
2050
2050
  uniqueId: string;
2051
2051
  }
2052
2052
  /** Per-commit change tallies, mirrored from the add-in's `counts` block. */
@@ -2056,7 +2056,7 @@ export interface RevitFlowCounts {
2056
2056
  removed: number;
2057
2057
  }
2058
2058
  /**
2059
- * A revit-flow commit — one push of changes from the Revit add-in. `id` is a
2059
+ * A revit-flow commit — one push of changes from the authoring tool's add-in. `id` is a
2060
2060
  * monotonic integer; `parent` points at the previous commit (null for the
2061
2061
  * root). The first commit is the baseline: its geometry IS the visible model
2062
2062
  * file. Later commits carry only their delta geometry, in a HIDDEN .frag whose
@@ -2066,8 +2066,8 @@ export interface RevitFlowCommit {
2066
2066
  /**
2067
2067
  * WHAT this commit is. Identity, minted by whoever wrote it, meaningful outside the model it
2068
2068
  * belongs to — which the old integer was not: that was the platform's storage version, a number
2069
- * the CDE handed out. An application that does not push through a Revit central has no such
2070
- * number, and an integer sequence asserts one line of history, which Revit's central enforces and
2069
+ * the CDE handed out. An application that does not push through a central model has no such
2070
+ * number, and an integer sequence asserts one line of history, which the authoring tool's central model enforces and
2071
2071
  * nothing else has to.
2072
2072
  */
2073
2073
  guid: string;
@@ -2079,8 +2079,8 @@ export interface RevitFlowCommit {
2079
2079
  * MERGE means naming both lines, and that needs this. The first entry is the line the commit
2080
2080
  * continues, which is what lets the panel lay out lanes without guessing which side is the trunk.
2081
2081
  *
2082
- * Revit never writes more than one: its central IS a single line and it merges inside itself
2083
- * rather than in this graph. The list is for the applications that are not Revit.
2082
+ * The native authoring tool never writes more than one: its central IS a single line and it merges inside itself
2083
+ * rather than in this graph. The list is for the applications that are not that tool.
2084
2084
  */
2085
2085
  parents?: string[] | null;
2086
2086
  /**
@@ -2100,7 +2100,7 @@ export interface RevitFlowCommit {
2100
2100
  * What the author said this commit was for, in their own words. Absent when nobody said
2101
2101
  * anything, which is most commits.
2102
2102
  *
2103
- * In Revit it comes from the Comment box in its own Synchronize with Central dialog, which
2103
+ * In the native authoring tool it comes from the Comment box in its own Synchronize with Central dialog, which
2104
2104
  * people have been typing into for years while it went nowhere. Free text: never parsed, never
2105
2105
  * relied on for structure.
2106
2106
  */
@@ -2120,7 +2120,7 @@ export interface RevitFlowCommit {
2120
2120
  /**
2121
2121
  * Platform user id of the committer, recorded by the add-in from its API key. Lets the
2122
2122
  * UI resolve the author to a real project member (avatar + name) via getProjectData,
2123
- * instead of deriving initials from the raw Revit username. Absent on history written
2123
+ * instead of deriving initials from the raw authoring-tool username. Absent on history written
2124
2124
  * before this was recorded, or when the key isn't a readable JWT.
2125
2125
  */
2126
2126
  userId?: string;
@@ -2142,7 +2142,7 @@ export interface RevitFlowCommit {
2142
2142
  full?: boolean;
2143
2143
  /**
2144
2144
  * Interoperability operations this commit materialised. Present only when somebody in
2145
- * Revit pulled a deferred edit: the commit is the native half of it, and this is the
2145
+ * the authoring tool pulled a deferred edit: the commit is the native half of it, and this is the
2146
2146
  * link back to the operation that asked for it. Ordinary hand-authored commits, which
2147
2147
  * are nearly all of them, carry no such key at all.
2148
2148
  */
@@ -2172,7 +2172,7 @@ export interface RevitFlowHistory {
2172
2172
  *
2173
2173
  * Operations are NOT commits and do not live in the graph: a commit is immutable past, an
2174
2174
  * operation is optional future. They sit above the model's HEAD until somebody opens the
2175
- * model in Revit and applies one, at which point they become a commit and stop being
2175
+ * model in the authoring tool and applies one, at which point they become a commit and stop being
2176
2176
  * pending. Mirrors the add-in's `revitflow_ops.json`.
2177
2177
  */
2178
2178
  export interface RevitFlowOp {
@@ -2283,10 +2283,10 @@ declare class _GitHistoryManager extends OBC.Component {
2283
2283
  /**
2284
2284
  * Which mark to draw on a commit, by the application that wrote it.
2285
2285
  *
2286
- * Every commit already says who made it, in `source`. The panel used to draw the Revit logo on
2287
- * all of them regardless, which was true while Revit was the only thing that could write one and
2286
+ * Every commit already says who made it, in `source`. The panel used to draw the authoring tool's logo on
2287
+ * all of them regardless, which was true while the authoring tool was the only thing that could write one and
2288
2288
  * became a lie the moment anything else did: a commit from another tool would claim to be a
2289
- * Revit commit, on the one part of the row whose whole job is to say where a change came from.
2289
+ * commit of the authoring tool, on the one part of the row whose whole job is to say where a change came from.
2290
2290
  *
2291
2291
  * The format is deliberately open about who writes history, so the icons have to be too. This is
2292
2292
  * the registry. Only `revit` is built in; an application adds its own:
@@ -0,0 +1,17 @@
1
+ import { BrowserSession } from '../../core/browser-sign-in';
2
+
3
+ /** Best effort: on a machine with no browser, the address is on the screen anyway. */
4
+ export declare function openInBrowser(url: string): void;
5
+ /**
6
+ * Before a command runs, a browser sign-in whose access token is about to expire
7
+ * gets a new one, in the same config it came from. A login with `--token` has no
8
+ * session and is left alone.
9
+ *
10
+ * If the renewal fails the command goes on, and fails on its own call with the
11
+ * platform's answer, unless the session was cut: then it says to log in again.
12
+ */
13
+ export declare function renewStoredSession(cwd?: string): Promise<void>;
14
+ /** The stored session this token belongs to, if it came from a browser sign-in. */
15
+ export declare function storedSessionFor(accessToken: string, cwd?: string): BrowserSession | undefined;
16
+ /** Puts a renewed session back where it came from: its refresh token has rotated. */
17
+ export declare function storeSession(session: BrowserSession, cwd?: string): void;
@@ -1,6 +1,10 @@
1
+ import { BrowserSession } from '../../core/browser-sign-in';
2
+
1
3
  export interface ThatOpenConfig {
2
4
  accessToken: string;
3
5
  apiUrl: string;
6
+ /** Present after a login through the browser: what renews `accessToken`. */
7
+ session?: BrowserSession;
4
8
  }
5
9
  export declare function readConfig(): ThatOpenConfig | null;
6
10
  export declare function writeConfig(config: ThatOpenConfig): void;
@@ -9,6 +13,8 @@ export type ProjectType = 'APP' | 'COMPONENT';
9
13
  export interface ThatOpenLocalConfig {
10
14
  accessToken: string;
11
15
  apiUrl: string;
16
+ /** Present after a login through the browser: what renews `accessToken`. */
17
+ session?: BrowserSession;
12
18
  appId?: string;
13
19
  componentId?: string;
14
20
  /** Project type marker set by `thatopen create`. */
package/dist/cli.js CHANGED
@@ -3428,6 +3428,80 @@ commander.InvalidOptionArgumentError = InvalidArgumentError2;
3428
3428
  const {
3429
3429
  Command: Command2
3430
3430
  } = commander;
3431
+ const SERVICES_SDK_CONNECTOR_ID = "services-sdk";
3432
+ const post = async (url2, body) => {
3433
+ const response = await fetch(url2, {
3434
+ method: "POST",
3435
+ headers: { "Content-Type": "application/json" },
3436
+ body: JSON.stringify(body)
3437
+ });
3438
+ if (!response.ok) {
3439
+ const text2 = await response.text().catch(() => "");
3440
+ let message = text2;
3441
+ try {
3442
+ message = JSON.parse(text2).message ?? text2;
3443
+ } catch {
3444
+ }
3445
+ throw new Error(message || `The platform answered ${response.status}`);
3446
+ }
3447
+ return await response.json();
3448
+ };
3449
+ const wait = (ms, signal) => new Promise((resolve2, reject) => {
3450
+ const timer = setTimeout(resolve2, ms);
3451
+ signal?.addEventListener(
3452
+ "abort",
3453
+ () => {
3454
+ clearTimeout(timer);
3455
+ reject(new Error("Sign-in cancelled"));
3456
+ },
3457
+ { once: true }
3458
+ );
3459
+ });
3460
+ const deviceUrl = (apiUrl, path2) => `${apiUrl.replace(/\/$/, "")}/api/connectors/device/${path2}`;
3461
+ async function signInWithBrowser(options) {
3462
+ const { apiUrl, application, machine, version: version2, onVerification, signal } = options;
3463
+ const start = await post(deviceUrl(apiUrl, "start"), {
3464
+ application,
3465
+ machine,
3466
+ connectorId: SERVICES_SDK_CONNECTOR_ID
3467
+ });
3468
+ await onVerification({
3469
+ url: start.verification_uri_complete,
3470
+ userCode: start.user_code,
3471
+ manualUrl: start.verification_uri
3472
+ });
3473
+ const deadline = Date.now() + start.expires_in * 1e3;
3474
+ while (Date.now() < deadline) {
3475
+ await wait(start.interval * 1e3, signal);
3476
+ const claim = await post(deviceUrl(apiUrl, "claim"), {
3477
+ deviceCode: start.device_code,
3478
+ connectorId: SERVICES_SDK_CONNECTOR_ID,
3479
+ pluginVersion: version2
3480
+ });
3481
+ if (claim.status === "confirmed") {
3482
+ return {
3483
+ apiUrl,
3484
+ accessToken: claim.accessToken,
3485
+ expiresAt: Date.now() + claim.expiresIn * 1e3,
3486
+ installId: claim.installId,
3487
+ refreshToken: claim.refreshToken
3488
+ };
3489
+ }
3490
+ }
3491
+ throw new Error("The code expired before it was confirmed. Try again.");
3492
+ }
3493
+ async function refreshBrowserSession(session) {
3494
+ const next = await post(deviceUrl(session.apiUrl, "refresh"), {
3495
+ installId: session.installId,
3496
+ refreshToken: session.refreshToken
3497
+ });
3498
+ return {
3499
+ ...session,
3500
+ accessToken: next.accessToken,
3501
+ expiresAt: Date.now() + next.expiresIn * 1e3,
3502
+ refreshToken: next.refreshToken
3503
+ };
3504
+ }
3431
3505
  const CONFIG_DIR = require$$2.join(node_os.homedir(), ".thatopen");
3432
3506
  const CONFIG_FILE = require$$2.join(CONFIG_DIR, "config.json");
3433
3507
  function readConfig() {
@@ -3482,6 +3556,42 @@ function requireResolvedConfig(cwd) {
3482
3556
  }
3483
3557
  return config2;
3484
3558
  }
3559
+ const RENEW_BEFORE_MS = 6e4;
3560
+ function openInBrowser(url2) {
3561
+ const [command2, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url2]] : process.platform === "darwin" ? ["open", [url2]] : ["xdg-open", [url2]];
3562
+ require$$1.execFile(command2, [...args], () => {
3563
+ });
3564
+ }
3565
+ async function renewStoredSession(cwd) {
3566
+ const local = readLocalConfig(cwd);
3567
+ const stored = local?.session ?? readConfig()?.session;
3568
+ if (!stored || stored.expiresAt - Date.now() > RENEW_BEFORE_MS) return;
3569
+ let next;
3570
+ try {
3571
+ next = await refreshBrowserSession(stored);
3572
+ } catch (error2) {
3573
+ console.error(
3574
+ `Could not renew your sign-in: ${error2 instanceof Error ? error2.message : String(error2)}`
3575
+ );
3576
+ console.error("If this keeps happening, run `thatopen login` again.");
3577
+ return;
3578
+ }
3579
+ storeSession(next, cwd);
3580
+ }
3581
+ function storedSessionFor(accessToken, cwd) {
3582
+ return [readLocalConfig(cwd)?.session, readConfig()?.session].find(
3583
+ (session) => session?.accessToken === accessToken
3584
+ );
3585
+ }
3586
+ function storeSession(session, cwd) {
3587
+ const fields = {
3588
+ accessToken: session.accessToken,
3589
+ apiUrl: session.apiUrl,
3590
+ session
3591
+ };
3592
+ if (readLocalConfig(cwd)?.session) updateLocalConfig(fields, cwd);
3593
+ else writeConfig(fields);
3594
+ }
3485
3595
  const PACKET_TYPES = /* @__PURE__ */ Object.create(null);
3486
3596
  PACKET_TYPES["open"] = "0";
3487
3597
  PACKET_TYPES["close"] = "1";
@@ -6896,7 +7006,7 @@ class ProjectHistory {
6896
7006
  * @internal The documents' folders (the root's children), listed ONCE and
6897
7007
  * shared by every document. Each document listing them for itself was ~150
6898
7008
  * requests on one Coordinator load with ~30 documents, and the platform
6899
- * answers 429 past 100 a minute: the app then showed no Revit document and
7009
+ * answers 429 past 100 a minute: the app then showed no authoring-tool document and
6900
7010
  * a queued request never arrived (13-10). Listed again after 30 s, when a
6901
7011
  * folder is made, or when asked `fresh`.
6902
7012
  */
@@ -7005,8 +7115,8 @@ class FlowDoc {
7005
7115
  * takes the fragments engine, which this package deliberately does not
7006
7116
  * carry.
7007
7117
  *
7008
- * UniqueIds are the native application's own stable element ids (a Revit
7009
- * UniqueId survives syncs, machines and full exports), which is what makes
7118
+ * UniqueIds are the native application's own stable element ids (the authoring
7119
+ * tool's UniqueId survives syncs, machines and full exports), which is what makes
7010
7120
  * replace-by-uniqueId the whole composition rule.
7011
7121
  *
7012
7122
  * When the baseline is NEWER than the asked version (somebody published
@@ -8400,7 +8510,51 @@ function printOf(value2) {
8400
8510
  }
8401
8511
  return (hash >>> 0).toString(36);
8402
8512
  }
8403
- async function readPickedFrag(context, picked) {
8513
+ async function streamedContents(context, bytes, name) {
8514
+ if (bytes[0] !== 123) return null;
8515
+ let record2;
8516
+ try {
8517
+ record2 = JSON.parse(new TextDecoder().decode(bytes));
8518
+ } catch {
8519
+ return null;
8520
+ }
8521
+ if (!record2?.entry?.object || !record2.parts) return null;
8522
+ const reader = context.client.recipes.streamedReader();
8523
+ if (!reader) throw new Error(`${name} is a streamed model, and this app cannot read those: it provides no reader for them.`);
8524
+ context.progress(`Downloading the pieces of ${name}`);
8525
+ const objects = /* @__PURE__ */ new Map();
8526
+ const objectOf = (id2) => {
8527
+ let got = objects.get(id2);
8528
+ if (!got) {
8529
+ got = (async () => {
8530
+ const response = await context.client.downloadHiddenFile(id2);
8531
+ if (!response.ok) throw new Error(`Reading a piece of ${name} answered ${response.status}`);
8532
+ return new Uint8Array(await response.arrayBuffer());
8533
+ })();
8534
+ objects.set(id2, got);
8535
+ }
8536
+ return got;
8537
+ };
8538
+ const cut = async (ranges) => {
8539
+ const pieces = await Promise.all((ranges ?? []).map(async (r) => (await objectOf(r.object)).subarray(r.offset, r.offset + r.length)));
8540
+ const out = new Uint8Array(pieces.reduce((n, p) => n + p.length, 0));
8541
+ let at = 0;
8542
+ for (const piece of pieces) {
8543
+ out.set(piece, at);
8544
+ at += piece.length;
8545
+ }
8546
+ return out;
8547
+ };
8548
+ const [entry, container, sidecar, lod] = await Promise.all([
8549
+ cut([record2.entry]),
8550
+ cut(record2.parts.container),
8551
+ cut(record2.parts.sidecar),
8552
+ cut(record2.parts.lod)
8553
+ ]);
8554
+ context.progress(`Reading ${name}`);
8555
+ return await reader({ entry, container, sidecar, lod }, name);
8556
+ }
8557
+ async function readPickedFrag(context, picked, options) {
8404
8558
  if (!picked?.fileId) throw new Error("Choose the model file to read.");
8405
8559
  context.progress(`Downloading ${picked.name}`);
8406
8560
  let bytes = new Uint8Array(
@@ -8426,8 +8580,38 @@ async function readPickedFrag(context, picked) {
8426
8580
  context.progress(`Reading ${picked.name}`);
8427
8581
  bytes = await importer(bytes, picked.name);
8428
8582
  }
8429
- return { picked, contents: await readFrag(bytes), site, shapes };
8583
+ const streamed = await streamedContents(context, bytes, picked.name);
8584
+ if (extension === "frag" && options?.shapes && !streamed) {
8585
+ const reader = context.client.recipes.shapesFor("frag");
8586
+ if (reader) {
8587
+ context.progress(`Reading the shapes of ${picked.name}`);
8588
+ shapes = await reader(bytes, picked.name);
8589
+ }
8590
+ }
8591
+ const contents = streamed ?? await readFrag(bytes);
8592
+ const origin = contents.metadata?.thatOpenModelling?.origin;
8593
+ if (shapes && Array.isArray(origin) && (origin[0] || origin[1])) {
8594
+ const done = /* @__PURE__ */ new Set();
8595
+ for (const el of shapes.elements.values())
8596
+ for (const piece of el.pieces) {
8597
+ if (done.has(piece)) continue;
8598
+ done.add(piece);
8599
+ piece.matrix = piece.matrix.map((n, i) => i === 12 ? n - (origin[0] ?? 0) : i === 13 ? n - (origin[1] ?? 0) : n);
8600
+ }
8601
+ for (const el of shapes.elements.values())
8602
+ if (el.rebar) el.rebar = moveBar(el.rebar, (p) => [p[0] - (origin[0] ?? 0), p[1] - (origin[1] ?? 0), p[2]]);
8603
+ }
8604
+ if (shapes && site?.elevation) {
8605
+ for (const el of shapes.elements.values())
8606
+ if (el.rebar) el.rebar = moveBar(el.rebar, (p) => [p[0], p[1], p[2] - site.elevation]);
8607
+ }
8608
+ return { picked, contents, site, shapes };
8430
8609
  }
8610
+ const moveBar = (bar, to) => ({
8611
+ ...bar,
8612
+ path: bar.path.map(to),
8613
+ ...bar.paths ? { paths: bar.paths.map((one) => one.map(to)) } : {}
8614
+ });
8431
8615
  function siteLocationOf(bytes) {
8432
8616
  const text2 = new TextDecoder("latin1").decode(bytes);
8433
8617
  const entity = (id2) => new RegExp(`^${id2}=\\s*([A-Z0-9_]+)\\((.*)\\);\\s*$`, "m").exec(text2);
@@ -8688,6 +8872,15 @@ class Recipes {
8688
8872
  importerFor(extension) {
8689
8873
  return this.#importers.get(extension.toLowerCase());
8690
8874
  }
8875
+ #streamed;
8876
+ /** Says how this host reads a streamed .frag's pieces ({@link StreamedReader}). */
8877
+ provideStreamedReader(reader) {
8878
+ this.#streamed = reader;
8879
+ }
8880
+ /** The streamed reader provided, or undefined. */
8881
+ streamedReader() {
8882
+ return this.#streamed;
8883
+ }
8691
8884
  /** Registers a recipe. One per name; a second with the same name throws. */
8692
8885
  register(recipe) {
8693
8886
  if (this.#registry.has(recipe.name)) {
@@ -9009,6 +9202,83 @@ class EngineServicesClient {
9009
9202
  this.localServerUrl = lsUrl;
9010
9203
  }
9011
9204
  }
9205
+ /**
9206
+ * Signs in through the browser, as the plugins do, and returns a client
9207
+ * that keeps its access token fresh while the process lives. For a program
9208
+ * outside the platform; an app inside it uses {@link fromPlatformContext}.
9209
+ *
9210
+ * Keep the session given to `onSession` to start again without asking the
9211
+ * person, with {@link fromBrowserSession}. Its refresh token rotates, so each
9212
+ * one replaces the last.
9213
+ *
9214
+ * @example
9215
+ * ```ts
9216
+ * const client = await EngineServicesClient.signInWithBrowser({
9217
+ * apiUrl: 'https://platform.thatopen.com',
9218
+ * application: 'My tool',
9219
+ * machine: os.hostname(),
9220
+ * version: '1.0.0',
9221
+ * onVerification: ({ url, userCode }) => {
9222
+ * console.log(`Confirm ${userCode} at ${url}`);
9223
+ * },
9224
+ * onSession: (session) => save(session),
9225
+ * });
9226
+ * ```
9227
+ */
9228
+ static async signInWithBrowser(options) {
9229
+ const session = await signInWithBrowser(options);
9230
+ options.onSession?.(session);
9231
+ return EngineServicesClient.fromBrowserSession(session, options);
9232
+ }
9233
+ /**
9234
+ * A client from a session kept earlier. It renews the access token shortly
9235
+ * before it expires, without keeping the process alive for it; call
9236
+ * {@link stopRenewing} when done with a client in a process that goes on.
9237
+ */
9238
+ static fromBrowserSession(session, options) {
9239
+ const client = new EngineServicesClient(
9240
+ session.accessToken,
9241
+ session.apiUrl,
9242
+ { useBearer: true }
9243
+ );
9244
+ client.renewFrom(session, options?.onSession);
9245
+ return client;
9246
+ }
9247
+ renewal = null;
9248
+ renewFrom(session, onSession) {
9249
+ const renewBefore = 6e4;
9250
+ const delay = Math.max(session.expiresAt - Date.now() - renewBefore, 0);
9251
+ this.renewal = setTimeout(async () => {
9252
+ try {
9253
+ const next = await refreshBrowserSession(session);
9254
+ this.setAccessToken(next.accessToken);
9255
+ onSession?.(next);
9256
+ this.renewFrom(next, onSession);
9257
+ } catch {
9258
+ this.renewFrom(
9259
+ { ...session, expiresAt: Date.now() + renewBefore + 6e4 },
9260
+ onSession
9261
+ );
9262
+ }
9263
+ }, delay);
9264
+ this.renewal.unref?.();
9265
+ }
9266
+ /** Stops renewing the access token of a client from a browser session. */
9267
+ stopRenewing() {
9268
+ if (this.renewal) clearTimeout(this.renewal);
9269
+ this.renewal = null;
9270
+ }
9271
+ /**
9272
+ * Replaces the access token used by every call from now on.
9273
+ * @param accessToken - The new token.
9274
+ */
9275
+ setAccessToken(accessToken) {
9276
+ this.accessToken = accessToken;
9277
+ this.context = {
9278
+ ...this.context,
9279
+ accessToken
9280
+ };
9281
+ }
9012
9282
  /**
9013
9283
  * Sets the number of automatic retries for failed requests. Retries use
9014
9284
  * exponential backoff with jitter and honour `Retry-After`; only network
@@ -9998,7 +10268,7 @@ return main;`);
9998
10268
  return new ProjectDocuments(this, projectId);
9999
10269
  }
10000
10270
  /**
10001
- * A project's history of connected documents (Revit models, AutoCAD
10271
+ * A project's history of connected documents (authoring-tool models, CAD
10002
10272
  * drawings…): their version timelines and their change requests. See
10003
10273
  * `src/core/history.ts` — this surface is the only supported way to read
10004
10274
  * or write it; the storage underneath is private and will move.
@@ -10458,6 +10728,12 @@ return main;`);
10458
10728
  }
10459
10729
  }
10460
10730
  function cliClient(accessToken, apiUrl) {
10731
+ const session = storedSessionFor(accessToken);
10732
+ if (session) {
10733
+ return EngineServicesClient.fromBrowserSession(session, {
10734
+ onSession: storeSession
10735
+ });
10736
+ }
10461
10737
  return new EngineServicesClient(accessToken, apiUrl, { useBearer: true });
10462
10738
  }
10463
10739
  function ensureNpmrcIgnored(dir) {
@@ -10514,7 +10790,39 @@ async function configureBetaNpmrc(dir) {
10514
10790
  console.log(" token in .npmrc manually if the install fails.");
10515
10791
  }
10516
10792
  }
10517
- const loginCommand = new Command2("login").description("Authenticate with the ThatOpen platform").option("--token <token>", "Access token from the dashboard").option(
10793
+ const PACKAGE_VERSION = JSON.parse(
10794
+ require$$3$1.readFileSync(require$$2.join(__dirname, "..", "package.json"), "utf-8")
10795
+ ).version;
10796
+ const signIn = async (apiUrl) => {
10797
+ try {
10798
+ return await signInWithBrowser({
10799
+ apiUrl,
10800
+ application: "That Open CLI",
10801
+ machine: node_os.hostname(),
10802
+ version: PACKAGE_VERSION,
10803
+ onVerification: ({ url: url2, userCode, manualUrl }) => {
10804
+ console.log("");
10805
+ console.log(` Your code: ${userCode}`);
10806
+ console.log("");
10807
+ console.log(" Confirm it in the browser that has just opened.");
10808
+ console.log(` If none did, go to ${manualUrl} and enter the code.`);
10809
+ console.log("");
10810
+ openInBrowser(url2);
10811
+ }
10812
+ });
10813
+ } catch (err) {
10814
+ const msg = err instanceof Error ? err.message : String(err);
10815
+ console.error(`Could not sign in: ${msg}`);
10816
+ console.error(
10817
+ "You can also log in with a token from the dashboard: thatopen login --token <token>"
10818
+ );
10819
+ process.exit(1);
10820
+ }
10821
+ };
10822
+ const loginCommand = new Command2("login").description("Authenticate with the ThatOpen platform").option(
10823
+ "--token <token>",
10824
+ "Access token from the dashboard. Without one, you sign in through your browser"
10825
+ ).option(
10518
10826
  "--api-url <url>",
10519
10827
  "API URL (defaults to production; pass https://dev.platform.thatopen.com for the dev environment)",
10520
10828
  "https://platform.thatopen.com"
@@ -10522,26 +10830,11 @@ const loginCommand = new Command2("login").description("Authenticate with the Th
10522
10830
  "--local",
10523
10831
  "Save credentials to local .thatopen file instead of global config"
10524
10832
  ).action(async (opts) => {
10525
- if (!opts.token) {
10526
- console.log("");
10527
- console.log(" To log in, you need an access token from the ThatOpen platform.");
10528
- console.log("");
10529
- console.log(" 1. Go to your ThatOpen dashboard");
10530
- console.log(" 2. Navigate to Data > API Tokens");
10531
- console.log(" 3. Create a new token and copy it");
10532
- console.log("");
10533
- console.log(" Then run:");
10534
- if (opts.local) {
10535
- console.log(" npm run login -- --token <your-token>");
10536
- } else {
10537
- console.log(" thatopen login --token <your-token>");
10538
- }
10539
- console.log("");
10540
- process.exit(1);
10541
- }
10542
10833
  const apiUrl = opts.apiUrl.replace(/\/$/, "");
10834
+ const session = opts.token ? void 0 : await signIn(apiUrl);
10835
+ const accessToken = opts.token ?? session.accessToken;
10543
10836
  console.log("Validating token...");
10544
- const client = cliClient(opts.token, apiUrl);
10837
+ const client = cliClient(accessToken, apiUrl);
10545
10838
  try {
10546
10839
  await client.listApps();
10547
10840
  } catch (err) {
@@ -10551,10 +10844,10 @@ const loginCommand = new Command2("login").description("Authenticate with the Th
10551
10844
  process.exit(1);
10552
10845
  }
10553
10846
  if (opts.local) {
10554
- updateLocalConfig({ accessToken: opts.token, apiUrl });
10847
+ updateLocalConfig({ accessToken, apiUrl, session });
10555
10848
  console.log("Logged in successfully. Config saved to .thatopen");
10556
10849
  } else {
10557
- writeConfig({ accessToken: opts.token, apiUrl });
10850
+ writeConfig({ accessToken, apiUrl, session });
10558
10851
  console.log(
10559
10852
  "Logged in successfully. Config saved to ~/.thatopen/config.json"
10560
10853
  );
@@ -28263,9 +28556,9 @@ var traverse$1 = jsonSchemaTraverse.exports = function(schema, opts, cb) {
28263
28556
  cb = opts.cb || cb;
28264
28557
  var pre = typeof cb == "function" ? cb : cb.pre || function() {
28265
28558
  };
28266
- var post = cb.post || function() {
28559
+ var post2 = cb.post || function() {
28267
28560
  };
28268
- _traverse(opts, pre, post, schema, "", schema);
28561
+ _traverse(opts, pre, post2, schema, "", schema);
28269
28562
  };
28270
28563
  traverse$1.keywords = {
28271
28564
  additionalItems: true,
@@ -28311,7 +28604,7 @@ traverse$1.skipKeywords = {
28311
28604
  maxProperties: true,
28312
28605
  minProperties: true
28313
28606
  };
28314
- function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
28607
+ function _traverse(opts, pre, post2, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
28315
28608
  if (schema && typeof schema == "object" && !Array.isArray(schema)) {
28316
28609
  pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
28317
28610
  for (var key in schema) {
@@ -28319,18 +28612,18 @@ function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr,
28319
28612
  if (Array.isArray(sch)) {
28320
28613
  if (key in traverse$1.arrayKeywords) {
28321
28614
  for (var i = 0; i < sch.length; i++)
28322
- _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
28615
+ _traverse(opts, pre, post2, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
28323
28616
  }
28324
28617
  } else if (key in traverse$1.propsKeywords) {
28325
28618
  if (sch && typeof sch == "object") {
28326
28619
  for (var prop in sch)
28327
- _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
28620
+ _traverse(opts, pre, post2, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
28328
28621
  }
28329
28622
  } else if (key in traverse$1.keywords || opts.allKeys && !(key in traverse$1.skipKeywords)) {
28330
- _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
28623
+ _traverse(opts, pre, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
28331
28624
  }
28332
28625
  }
28333
- post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
28626
+ post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
28334
28627
  }
28335
28628
  }
28336
28629
  function escapeJsonPtr(str) {
@@ -30852,11 +31145,11 @@ uri$1.default = uri;
30852
31145
  }
30853
31146
  function addRule(keyword2, definition, dataType2) {
30854
31147
  var _a;
30855
- const post = definition === null || definition === void 0 ? void 0 : definition.post;
30856
- if (dataType2 && post)
31148
+ const post2 = definition === null || definition === void 0 ? void 0 : definition.post;
31149
+ if (dataType2 && post2)
30857
31150
  throw new Error('keyword with "post" flag cannot have "type"');
30858
31151
  const { RULES } = this;
30859
- let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType2);
31152
+ let ruleGroup = post2 ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType2);
30860
31153
  if (!ruleGroup) {
30861
31154
  ruleGroup = { type: dataType2, rules: [] };
30862
31155
  RULES.rules.push(ruleGroup);
@@ -35042,6 +35335,9 @@ process.on("exit", () => {
35042
35335
  });
35043
35336
  const program = new Command2();
35044
35337
  program.name("thatopen").description("CLI for ThatOpen Engine Services").version(pkg.version);
35338
+ program.hook("preAction", async (_program, command2) => {
35339
+ if (command2.name() !== "login") await renewStoredSession();
35340
+ });
35045
35341
  program.addCommand(loginCommand);
35046
35342
  program.addCommand(createCommand);
35047
35343
  program.addCommand(publishCommand);
@@ -35052,5 +35348,5 @@ program.addCommand(swapCommand);
35052
35348
  program.addCommand(revitCommand);
35053
35349
  program.addCommand(rhinoCommand);
35054
35350
  program.addCommand(mcpCommand);
35055
- program.parse(process.argv);
35351
+ program.parseAsync(process.argv);
35056
35352
  //# sourceMappingURL=cli.js.map