@r-33/opencode 0.4.7-rc.21 → 0.4.7-rc.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,219 +1,22 @@
1
- // src/auth/auth-error/auth-error.ts
2
- var AuthError = class extends Error {
3
- constructor(code, options) {
4
- super(
5
- "Route 33 authorization failed",
6
- options?.cause === void 0 ? void 0 : { cause: options.cause }
7
- );
8
- this.code = code;
9
- this.name = "AuthError";
10
- this.statusCode = options?.statusCode;
11
- }
12
- code;
13
- statusCode;
14
- };
15
-
16
- // src/auth/build-authorize-url/build-authorize-url.ts
17
- var buildAuthorizeUrl = (issuerUrl2, request) => {
18
- const url = new URL("/authorize", issuerUrl2);
19
- url.search = new URLSearchParams({
20
- client_id: request.clientId,
21
- code_challenge: request.codeChallenge,
22
- code_challenge_method: "S256",
23
- redirect_uri: request.redirectUri,
24
- response_type: "code",
25
- scope: request.scope,
26
- state: request.state
27
- }).toString();
28
- return url;
29
- };
30
-
31
- // src/contract/adapters/contract-parse-error/contract-parse-error.ts
32
- var ContractParseError = class extends Error {
33
- };
34
-
35
- // src/contract/adapters/gateway-api-key/gateway-api-key.ts
36
- var GatewayApiKey = class {
37
- value;
38
- constructor(value) {
39
- this.value = value;
40
- }
41
- };
42
-
43
- // src/contract/adapters/management-jwt/management-jwt.ts
44
- var ManagementJwt = class {
45
- value;
46
- constructor(value) {
47
- this.value = value;
48
- }
49
- };
50
-
51
- // src/contract/adapters/parse-gateway-key/parse-gateway-key.ts
52
- var parseGatewayKey = (value) => {
53
- if (typeof value !== "string" || value.length === 0) {
54
- throw new Error("gateway key must be non-empty");
55
- }
56
- return new GatewayApiKey(value);
57
- };
58
-
59
- // src/contract/adapters/parse-management-jwt/parse-management-jwt.ts
60
- var parseManagementJwt = (value) => {
61
- if (typeof value !== "string" || value.length === 0) {
62
- throw new Error("management token must be non-empty");
63
- }
64
- return new ManagementJwt(value);
65
- };
66
-
67
- // src/contract/predicates/has-string-fields/has-string-fields.ts
68
- var hasStringFields = (record, fields) => fields.every((field) => typeof record[field] === "string");
69
-
70
- // src/contract/predicates/is-nullable-string/is-nullable-string.ts
71
- var isNullableString = (value) => typeof value === "string" || value === null;
72
-
73
- // src/contract/predicates/is-owner-type/is-owner-type.ts
74
- var isOwnerType = (value) => value === "project" || value === "user_personal" || value === "user_project";
75
-
76
- // src/contract/predicates/is-record/is-record.ts
77
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
78
-
79
- // src/contract/adapters/parse-management-subject/parse-management-subject.ts
80
- var parseManagementSubject = (credential) => {
81
- const encodedPayload = credential.value.split(".")[1];
82
- if (encodedPayload === void 0 || encodedPayload.length === 0) {
83
- throw new ContractParseError("management token carries no usable subject");
84
- }
85
- let payload;
86
- try {
87
- payload = JSON.parse(
88
- Buffer.from(encodedPayload, "base64url").toString("utf8")
89
- );
90
- } catch {
91
- throw new ContractParseError("management token payload is not JSON");
92
- }
93
- if (!isRecord(payload)) {
94
- throw new ContractParseError("management token payload is not an object");
95
- }
96
- const subject = payload["sub"];
97
- if (typeof subject !== "string" || subject.length === 0) {
98
- throw new ContractParseError("management token carries no usable subject");
99
- }
100
- return subject;
101
- };
102
-
103
- // src/contract/auth-session/parse-token-set/parse-token-set.ts
104
- var parseTokenSet = (value) => {
105
- if (!isRecord(value)) {
106
- throw new ContractParseError("invalid token response");
107
- }
108
- if (typeof value["access_token"] !== "string" || typeof value["expires_in"] !== "number" || value["token_type"] !== "Bearer") {
109
- throw new ContractParseError("invalid token response");
110
- }
111
- return {
112
- access_token: value["access_token"],
113
- expires_in: value["expires_in"],
114
- token_type: "Bearer",
115
- ...typeof value["id_token"] === "string" ? { id_token: value["id_token"] } : {},
116
- ...typeof value["refresh_token"] === "string" ? { refresh_token: value["refresh_token"] } : {},
117
- ...typeof value["scope"] === "string" ? { scope: value["scope"] } : {}
118
- };
119
- };
1
+ // src/index.ts
2
+ import { createAuthSession as createAuthSession2 } from "@r-33/auth-browser";
120
3
 
121
- // src/auth/exchange-code-and-parse/exchange-code-and-parse.ts
122
- var exchangeCodeAndParse = async (options) => {
123
- const body = new URLSearchParams({
124
- client_id: options.clientId,
125
- code: options.input.code,
126
- code_verifier: options.input.codeVerifier,
127
- grant_type: "authorization_code",
128
- redirect_uri: options.input.redirectUri
129
- });
130
- let response;
131
- try {
132
- response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
133
- body,
134
- headers: { "content-type": "application/x-www-form-urlencoded" },
135
- method: "POST"
136
- });
137
- } catch (cause) {
138
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
139
- }
140
- if (!response.ok) {
141
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", {
142
- statusCode: response.status
143
- });
144
- }
145
- let payload;
146
- try {
147
- payload = await response.json();
148
- } catch (cause) {
149
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
150
- }
151
- try {
152
- return parseTokenSet(payload);
153
- } catch (cause) {
154
- if (cause instanceof ContractParseError) {
155
- throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
156
- }
157
- throw cause;
158
- }
4
+ // src/cli/read-env-base-url/read-env-base-url.ts
5
+ var readEnvBaseUrl = (env = process.env) => {
6
+ const value = env["ROUTE33_BASE_URL"]?.trim();
7
+ return value === "" ? void 0 : value;
159
8
  };
160
9
 
161
- // src/auth/refresh-session/refresh-session.ts
162
- var refreshSession = async (options) => {
163
- const body = new URLSearchParams({
164
- client_id: options.clientId,
165
- grant_type: "refresh_token",
166
- refresh_token: options.refreshToken
167
- });
168
- let response;
169
- try {
170
- response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
171
- body,
172
- headers: { "content-type": "application/x-www-form-urlencoded" },
173
- method: "POST"
174
- });
175
- } catch (cause) {
176
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
177
- }
178
- if (!response.ok) {
179
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", {
180
- statusCode: response.status
181
- });
182
- }
183
- let payload;
184
- try {
185
- payload = await response.json();
186
- } catch (cause) {
187
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
188
- }
189
- try {
190
- return parseTokenSet(payload);
191
- } catch (cause) {
192
- if (cause instanceof ContractParseError) {
193
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
194
- }
195
- throw cause;
196
- }
10
+ // src/cli/read-env-api-base/read-env-api-base.ts
11
+ var readEnvApiBase = (env = process.env) => {
12
+ const value = env["ROUTE33_API_BASE"]?.trim();
13
+ return value === "" ? void 0 : value;
197
14
  };
198
15
 
199
- // src/auth/create-auth-session/create-auth-session.ts
200
- var createAuthSession = (options) => {
201
- const tokenUrl = new URL("/oauth/token", options.issuerUrl);
202
- return {
203
- authorizationUrl: (request) => buildAuthorizeUrl(options.issuerUrl, request),
204
- exchangeCode: (input) => exchangeCodeAndParse({
205
- clientId: options.clientId,
206
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
207
- input,
208
- tokenUrl
209
- }),
210
- refresh: (refreshToken) => refreshSession({
211
- clientId: options.clientId,
212
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
213
- refreshToken,
214
- tokenUrl
215
- })
216
- };
16
+ // src/cli/read-env-auth-issuer/read-env-auth-issuer.ts
17
+ var readEnvAuthIssuer = (env = process.env) => {
18
+ const value = env["ROUTE33_AUTH_ISSUER"]?.trim();
19
+ return value === "" ? void 0 : value;
217
20
  };
218
21
 
219
22
  // src/shared/default-auth-issuer-url/default-auth-issuer-url.ts
@@ -261,260 +64,6 @@ var resolveCacheDir = (env) => {
261
64
  );
262
65
  };
263
66
 
264
- // src/auth/open-browser-and-capture/open-browser-and-capture.ts
265
- import { timingSafeEqual } from "node:crypto";
266
-
267
- // src/auth/loopback-callback/loopback-callback.ts
268
- import { createServer } from "node:http";
269
-
270
- // src/auth/loopback-callback/callback-page/callback-page.ts
271
- var MARK_PATHS = [
272
- "M310.6,175.8c0-6.1-2.7-11.8-7.2-15.9l-127.6-114.4V7h-43.5v48.3c0,6.2,2.6,12.1,7.2,16.2l92.5,82.9H0v43.5h234.7l-95.6,91.4c-4.3,4.1-6.7,9.8-6.7,15.7v48.3h43.5v-39l128.1-122.4c4.4-4.2,6.8-10,6.7-16.1h0Z",
273
- "M457.2,175.9v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4-13.3,14.8-23.2,19.5-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,9,19.4,9,31.2s-3,21.2-9.1,29.8-14.4,15.3-25.1,20.1c-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2c18.6-8.8,33.3-20.8,44-36,10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6c-12.8-14.9-30.8-24.2-54-27.8h0Z",
274
- "M763,203.7c-12.8-14.9-30.8-24.2-54-27.8v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-8.9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4c-5.6,8.3-13.3,14.8-23.2,19.5s-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,8.9,19.4,8.9,31.2s-3,21.2-9.1,29.8c-6.1,8.6-14.4,15.3-25.1,20.1-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2,33.3-20.8,44-36c10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6h0Z"
275
- ];
276
- var BRAND_MARK = `<svg class="r33-mark" viewBox="0 0 782.2 360.3" fill="currentColor" role="img" aria-label="route33.ai" xmlns="http://www.w3.org/2000/svg"><path d="${MARK_PATHS[0]}"/><path d="${MARK_PATHS[1]}"/><path d="${MARK_PATHS[2]}"/></svg>`;
277
- var PAGE_STYLE = `:root{color-scheme:dark;--r33-euro-blue:#0000FF;--r33-off-white:#F1F1F1;--r33-off-black:#121212;--r33-grey-300:#C9CBCF;--r33-radius-fillet:4px;--r33-space-2:8px;--r33-space-3:16px;--r33-space-4:24px;--r33-space-6:64px;--r33-font-body:"Geist","Helvetica Neue",Arial,sans-serif;--r33-font-mono:"Geist Mono","SFMono-Regular",Menlo,monospace;--r33-surface:var(--r33-off-black);--r33-text-primary:var(--r33-off-white);--r33-text-secondary:var(--r33-grey-300);--r33-fill-accent:var(--r33-euro-blue);--r33-on-fill-accent:var(--r33-off-white)}
278
- *{box-sizing:border-box}
279
- html,body{margin:0}
280
- .r33-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:var(--r33-space-6);background:var(--r33-surface);color:var(--r33-text-primary);font-family:var(--r33-font-body);-webkit-font-smoothing:antialiased}
281
- .r33-panel{display:grid;gap:var(--r33-space-4);max-width:460px;width:100%}
282
- .r33-mark{height:40px;width:auto;color:var(--r33-text-primary)}
283
- .r33-status{display:inline-flex;align-items:center;gap:var(--r33-space-2);font-size:11px;letter-spacing:0.08em;text-transform:uppercase;color:var(--r33-text-secondary)}
284
- .r33-status__dot{width:8px;height:8px;background:var(--r33-fill-accent)}
285
- .r33-status__dot--error{background:transparent;border:1px solid var(--r33-text-primary);border-radius:50%}
286
- .r33-headline{margin:0;font-size:48px;line-height:0.85;letter-spacing:-0.02em;font-weight:600;color:var(--r33-text-primary);text-wrap:balance}
287
- .r33-subline{margin:0;font-size:16px;line-height:1.45;color:var(--r33-text-secondary);max-width:40ch;text-wrap:pretty}
288
- .r33-code{margin:0;font-size:13px;letter-spacing:0.04em;color:var(--r33-text-secondary)}
289
- .r33-code__value{font-family:var(--r33-font-mono);text-transform:uppercase;color:var(--r33-text-primary)}
290
- @media (prefers-reduced-motion:reduce){*{animation-duration:1ms!important;transition-duration:1ms!important}}`;
291
- var buildCallbackPage = (state, errorCode) => {
292
- const isError = state === "error";
293
- const safeCode = (errorCode ?? "").replace(/[^a-z0-9_-]/gi, "");
294
- const title = isError ? "Sign-in failed" : "Signed in";
295
- const headline = isError ? "Sign-in failed" : "Signed in to route33";
296
- const subline = isError ? "Return to OpenCode and retry." : "Return to OpenCode \u2014 one more step may wait there: if it asks which budget covers usage, pick a project. This window can be closed.";
297
- const statusLabel = isError ? "Authentication error" : "Authenticated";
298
- const dotClass = isError ? "r33-status__dot r33-status__dot--error" : "r33-status__dot";
299
- const codeLine = isError && safeCode.length > 0 ? `<p class="r33-code">Error code: <span class="r33-code__value">${safeCode}</span></p>` : "";
300
- return `<!doctype html>
301
- <html lang="en" data-theme="dark">
302
- <head>
303
- <meta charset="utf-8">
304
- <meta name="viewport" content="width=device-width, initial-scale=1">
305
- <title>${title} \xB7 route33.ai</title>
306
- <style>${PAGE_STYLE}</style>
307
- </head>
308
- <body>
309
- <main class="r33-page">
310
- <div class="r33-panel">
311
- ${BRAND_MARK}
312
- <span class="r33-status"><span class="${dotClass}"></span>${statusLabel}</span>
313
- <h1 class="r33-headline">${headline}</h1>
314
- <p class="r33-subline">${subline}</p>
315
- ${codeLine}
316
- </div>
317
- </main>
318
- </body>
319
- </html>`;
320
- };
321
-
322
- // src/auth/loopback-callback/loopback-callback.ts
323
- var createAuthLoopbackCallback = async () => {
324
- let redirectUri = "http://127.0.0.1/callback";
325
- let resolveCapture;
326
- const captured = new Promise((resolve2) => {
327
- resolveCapture = resolve2;
328
- });
329
- const server = createServer((request, response) => {
330
- const url = new URL(request.url ?? "/", redirectUri);
331
- if (request.method !== "GET" || url.pathname !== "/callback") {
332
- response.writeHead(404).end();
333
- return;
334
- }
335
- const resolve2 = resolveCapture;
336
- resolveCapture = void 0;
337
- resolve2?.(url);
338
- const error = url.searchParams.get("error");
339
- const page = error === null || error.length === 0 ? buildCallbackPage("success") : buildCallbackPage("error", error);
340
- response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
341
- response.end(page);
342
- });
343
- await new Promise((resolve2, reject) => {
344
- const onError = (cause) => {
345
- reject(new AuthError("AUTH_CALLBACK_LISTEN_FAILED", { cause }));
346
- };
347
- server.once("error", onError);
348
- server.listen(0, "127.0.0.1", () => {
349
- server.off("error", onError);
350
- resolve2();
351
- });
352
- });
353
- const address = server.address();
354
- if (address === null || typeof address === "string") {
355
- server.close();
356
- throw new AuthError("AUTH_CALLBACK_LISTEN_FAILED");
357
- }
358
- redirectUri = `http://127.0.0.1:${String(address.port)}/callback`;
359
- return {
360
- redirectUri,
361
- close: () => {
362
- if (!server.listening) {
363
- return Promise.resolve();
364
- }
365
- return new Promise((resolve2, reject) => {
366
- server.close((cause) => {
367
- if (cause === void 0) {
368
- resolve2();
369
- return;
370
- }
371
- reject(new AuthError("AUTH_CALLBACK_CLEANUP_FAILED", { cause }));
372
- });
373
- });
374
- },
375
- wait: () => captured
376
- };
377
- };
378
-
379
- // src/auth/open-system-browser/open-system-browser.ts
380
- import { spawn } from "node:child_process";
381
- var openSystemBrowser = async (url, options = {}) => new Promise((resolve2, reject) => {
382
- let command = "xdg-open";
383
- let args = [url.href];
384
- if (process.platform === "darwin") {
385
- command = "open";
386
- } else if (process.platform === "win32") {
387
- command = "cmd";
388
- args = ["/c", "start", "", url.href];
389
- }
390
- if (options.spawnUrl !== void 0) {
391
- options.spawnUrl(command, args, { detached: true, stdio: "ignore" });
392
- resolve2();
393
- return;
394
- }
395
- const child = spawn(command, args, {
396
- detached: true,
397
- stdio: "ignore"
398
- });
399
- child.once("error", reject);
400
- child.once("spawn", () => {
401
- child.unref();
402
- resolve2();
403
- });
404
- });
405
-
406
- // src/auth/open-browser-and-capture/open-browser-and-capture.ts
407
- var openBrowserAndCapture = async (options) => {
408
- const callback = await createAuthLoopbackCallback();
409
- const authorizationUrl = options.authorizationUrl(callback.redirectUri);
410
- const browserRunner = options.browserRunner ?? ((url) => openSystemBrowser(url));
411
- let timer;
412
- const timeout = new Promise((_resolve, reject) => {
413
- timer = setTimeout(() => {
414
- reject(new AuthError("AUTH_CALLBACK_TIMEOUT"));
415
- }, options.timeoutMs ?? 12e4);
416
- });
417
- const launch = browserRunner(authorizationUrl).catch((cause) => {
418
- throw new AuthError("AUTH_BROWSER_LAUNCH_FAILED", { cause });
419
- });
420
- try {
421
- const completed = await Promise.race([
422
- Promise.all([launch, callback.wait()]),
423
- timeout
424
- ]);
425
- const callbackUrl = completed[1];
426
- const actualState = callbackUrl.searchParams.get("state");
427
- if (actualState === null) {
428
- throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
429
- }
430
- const expectedState = Buffer.from(options.expectedState);
431
- const receivedState = Buffer.from(actualState);
432
- if (expectedState.length !== receivedState.length || !timingSafeEqual(expectedState, receivedState)) {
433
- throw new AuthError("AUTH_CALLBACK_STATE_MISMATCH");
434
- }
435
- const code = callbackUrl.searchParams.get("code");
436
- if (code === null || code.length === 0) {
437
- throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
438
- }
439
- return { code, redirectUri: callback.redirectUri };
440
- } finally {
441
- if (timer !== void 0) {
442
- clearTimeout(timer);
443
- }
444
- await callback.close();
445
- }
446
- };
447
-
448
- // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
449
- import { randomBytes } from "node:crypto";
450
-
451
- // src/auth/pkce-challenge/pkce-challenge.ts
452
- import { createHash } from "node:crypto";
453
- var pkceChallenge = (verifier) => createHash("sha256").update(verifier).digest("base64url");
454
-
455
- // src/auth/pkce-verifier-and-challenge/pkce-verifier-and-challenge.ts
456
- var createPkceVerifierAndChallenge = () => {
457
- const codeVerifier = randomBytes(32).toString("base64url");
458
- return {
459
- codeChallenge: pkceChallenge(codeVerifier),
460
- codeVerifier,
461
- state: randomBytes(32).toString("base64url")
462
- };
463
- };
464
-
465
- // src/auth/requested-scopes/requested-scopes.ts
466
- var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
467
-
468
- // src/auth/login-flow/login-flow.ts
469
- var loginFlow = async (options) => {
470
- const log = options.logger ?? logger;
471
- log.info("auth.login.started");
472
- const pkce = createPkceVerifierAndChallenge();
473
- const captured = await openBrowserAndCapture({
474
- authorizationUrl: (redirectUri) => options.session.authorizationUrl({
475
- clientId: options.clientId,
476
- codeChallenge: pkce.codeChallenge,
477
- redirectUri,
478
- scope: REQUESTED_OAUTH_SCOPES,
479
- state: pkce.state
480
- }),
481
- ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
482
- expectedState: pkce.state,
483
- ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
484
- });
485
- const tokenSet = await options.session.exchangeCode({
486
- code: captured.code,
487
- codeVerifier: pkce.codeVerifier,
488
- redirectUri: captured.redirectUri
489
- });
490
- let credential;
491
- try {
492
- credential = parseManagementJwt(tokenSet.access_token);
493
- } catch (cause) {
494
- throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
495
- }
496
- log.info("auth.login.completed");
497
- return { credential, tokenSet };
498
- };
499
-
500
- // src/cli/read-env-base-url/read-env-base-url.ts
501
- var readEnvBaseUrl = (env = process.env) => {
502
- const value = env["ROUTE33_BASE_URL"]?.trim();
503
- return value === "" ? void 0 : value;
504
- };
505
-
506
- // src/cli/read-env-api-base/read-env-api-base.ts
507
- var readEnvApiBase = (env = process.env) => {
508
- const value = env["ROUTE33_API_BASE"]?.trim();
509
- return value === "" ? void 0 : value;
510
- };
511
-
512
- // src/cli/read-env-auth-issuer/read-env-auth-issuer.ts
513
- var readEnvAuthIssuer = (env = process.env) => {
514
- const value = env["ROUTE33_AUTH_ISSUER"]?.trim();
515
- return value === "" ? void 0 : value;
516
- };
517
-
518
67
  // src/cli/read-env-cache-dir/read-env-cache-dir.ts
519
68
  var readEnvCacheDir = (env = process.env) => resolveCacheDir(env);
520
69
 
@@ -596,6 +145,18 @@ var abortableSleep = (milliseconds, signal) => new Promise((resolve2, reject) =>
596
145
  // src/config/is-resendable-body/is-resendable-body.ts
597
146
  var isResendableBody = (body) => body === void 0 || typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof Blob || body instanceof URLSearchParams || body instanceof FormData;
598
147
 
148
+ // src/contract/predicates/has-string-fields/has-string-fields.ts
149
+ var hasStringFields = (record, fields) => fields.every((field) => typeof record[field] === "string");
150
+
151
+ // src/contract/predicates/is-nullable-string/is-nullable-string.ts
152
+ var isNullableString = (value) => typeof value === "string" || value === null;
153
+
154
+ // src/contract/predicates/is-owner-type/is-owner-type.ts
155
+ var isOwnerType = (value) => value === "project" || value === "user_personal" || value === "user_project";
156
+
157
+ // src/contract/predicates/is-record/is-record.ts
158
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
159
+
599
160
  // src/config/parse-exhaustion-envelope/parse-exhaustion-envelope.ts
600
161
  var parseExhaustionEnvelope = async (response) => {
601
162
  let body;
@@ -885,8 +446,8 @@ var catalogMemory = /* @__PURE__ */ new Map();
885
446
  var CATALOG_CACHE_VERSION = 2;
886
447
 
887
448
  // src/catalog/catalog-cache/hash-key/hash-key.ts
888
- import { createHash as createHash2 } from "node:crypto";
889
- var hashKey = (baseURL, gatewayKey) => createHash2("sha256").update(`${baseURL}
449
+ import { createHash } from "node:crypto";
450
+ var hashKey = (baseURL, gatewayKey) => createHash("sha256").update(`${baseURL}
890
451
  ${gatewayKey.value}`).digest("hex").slice(0, 12);
891
452
 
892
453
  // src/catalog/catalog-cache/is-catalog-model-record/is-catalog-model-record.ts
@@ -990,6 +551,66 @@ var catalogModelsUrl = (baseURL) => {
990
551
  // src/catalog/default-fetch-timeout-ms/default-fetch-timeout-ms.ts
991
552
  var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
992
553
 
554
+ // src/contract/adapters/contract-parse-error/contract-parse-error.ts
555
+ var ContractParseError = class extends Error {
556
+ };
557
+
558
+ // src/contract/adapters/gateway-api-key/gateway-api-key.ts
559
+ var GatewayApiKey = class {
560
+ value;
561
+ constructor(value) {
562
+ this.value = value;
563
+ }
564
+ };
565
+
566
+ // src/contract/adapters/management-jwt/management-jwt.ts
567
+ var ManagementJwt = class {
568
+ value;
569
+ constructor(value) {
570
+ this.value = value;
571
+ }
572
+ };
573
+
574
+ // src/contract/adapters/parse-gateway-key/parse-gateway-key.ts
575
+ var parseGatewayKey = (value) => {
576
+ if (typeof value !== "string" || value.length === 0) {
577
+ throw new Error("gateway key must be non-empty");
578
+ }
579
+ return new GatewayApiKey(value);
580
+ };
581
+
582
+ // src/contract/adapters/parse-management-jwt/parse-management-jwt.ts
583
+ var parseManagementJwt = (value) => {
584
+ if (typeof value !== "string" || value.length === 0) {
585
+ throw new Error("management token must be non-empty");
586
+ }
587
+ return new ManagementJwt(value);
588
+ };
589
+
590
+ // src/contract/adapters/parse-management-subject/parse-management-subject.ts
591
+ var parseManagementSubject = (credential) => {
592
+ const encodedPayload = credential.value.split(".")[1];
593
+ if (encodedPayload === void 0 || encodedPayload.length === 0) {
594
+ throw new ContractParseError("management token carries no usable subject");
595
+ }
596
+ let payload;
597
+ try {
598
+ payload = JSON.parse(
599
+ Buffer.from(encodedPayload, "base64url").toString("utf8")
600
+ );
601
+ } catch {
602
+ throw new ContractParseError("management token payload is not JSON");
603
+ }
604
+ if (!isRecord(payload)) {
605
+ throw new ContractParseError("management token payload is not an object");
606
+ }
607
+ const subject = payload["sub"];
608
+ if (typeof subject !== "string" || subject.length === 0) {
609
+ throw new ContractParseError("management token carries no usable subject");
610
+ }
611
+ return subject;
612
+ };
613
+
993
614
  // src/contract/gateway-catalog/parse-catalog-result/parse-catalog-result.ts
994
615
  var parseCatalogResult = (value) => {
995
616
  if (!isRecord(value) || !Array.isArray(value["data"])) {
@@ -2978,7 +2599,7 @@ var createLeaseInstallationFactory = (options) => {
2978
2599
  };
2979
2600
 
2980
2601
  // src/key-lease/scope-id/scope-id.ts
2981
- import { createHash as createHash3 } from "node:crypto";
2602
+ import { createHash as createHash2 } from "node:crypto";
2982
2603
  var deriveScopeId = (input) => {
2983
2604
  let identity;
2984
2605
  switch (input.attribution.kind) {
@@ -3001,7 +2622,7 @@ var deriveScopeId = (input) => {
3001
2622
  throw new TypeError(`Unexpected attribution: ${String(unexpected)}`);
3002
2623
  }
3003
2624
  }
3004
- return createHash3("sha256").update(JSON.stringify(identity)).digest("hex");
2625
+ return createHash2("sha256").update(JSON.stringify(identity)).digest("hex");
3005
2626
  };
3006
2627
 
3007
2628
  // src/requested-client-id/requested-client-id.ts
@@ -3116,6 +2737,47 @@ var TRUSTED_PARTY_COPY = {
3116
2737
  title: "Connect Route 33"
3117
2738
  };
3118
2739
 
2740
+ // src/ux/callback-page-copy/callback-page-copy.ts
2741
+ var CALLBACK_PAGE_COPY = {
2742
+ errorHeadline: "Sign-in failed",
2743
+ errorSubline: "Return to OpenCode and retry.",
2744
+ successHeadline: "Signed in to route33",
2745
+ successSubline: "Return to OpenCode \u2014 one more step may wait there: if it asks which budget covers usage, pick a project. This window can be closed."
2746
+ };
2747
+
2748
+ // src/route33-runtime/login-session/login-session.ts
2749
+ import { AuthError as AuthError2 } from "@r-33/auth-browser";
2750
+
2751
+ // src/route33-login/route33-login.ts
2752
+ import {
2753
+ AuthError,
2754
+ loginFlow
2755
+ } from "@r-33/auth-browser";
2756
+
2757
+ // src/requested-scopes/requested-scopes.ts
2758
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
2759
+
2760
+ // src/route33-login/route33-login.ts
2761
+ var route33Login = async (options) => {
2762
+ const log = options.logger ?? logger;
2763
+ const tokenSet = await loginFlow({
2764
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
2765
+ clientId: options.clientId,
2766
+ logger: log,
2767
+ pageCopy: CALLBACK_PAGE_COPY,
2768
+ scope: REQUESTED_OAUTH_SCOPES,
2769
+ session: options.session,
2770
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
2771
+ });
2772
+ let credential;
2773
+ try {
2774
+ credential = parseManagementJwt(tokenSet.access_token);
2775
+ } catch (cause) {
2776
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
2777
+ }
2778
+ return { credential, tokenSet };
2779
+ };
2780
+
3119
2781
  // src/route33-runtime/login-session/login-session.ts
3120
2782
  var EXPIRY_SKEW_MS = 6e4;
3121
2783
  var LoginSession = class {
@@ -3125,15 +2787,11 @@ var LoginSession = class {
3125
2787
  constructor(options) {
3126
2788
  this.#options = options;
3127
2789
  }
3128
- /**
3129
- * Resolves the login once per process, sharing in-flight attempts.
3130
- * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
3131
- * @returns The token set plus its typed management credential.
3132
- */
3133
2790
  /**
3134
2791
  * Clears the session: the cached login result and the stored refresh
3135
2792
  * token. The next login starts from scratch — /r33 logout and the
3136
2793
  * auto-reconnect path both land here.
2794
+ * @returns Resolved once the session and the stored refresh token are gone.
3137
2795
  */
3138
2796
  async clear() {
3139
2797
  this.#result = void 0;
@@ -3141,8 +2799,9 @@ var LoginSession = class {
3141
2799
  await this.#options.tokenStore?.set(void 0);
3142
2800
  }
3143
2801
  /**
3144
- *
3145
- * @param policy
2802
+ * Resolves the login once per process, sharing in-flight attempts.
2803
+ * @param policy - Whether this attempt may start a browser login; an in-flight attempt is always shared.
2804
+ * @returns The token set plus its typed management credential.
3146
2805
  */
3147
2806
  result(policy = {}) {
3148
2807
  if (this.#result !== void 0 && this.#expiresAt !== void 0 && Date.now() >= this.#expiresAt - EXPIRY_SKEW_MS) {
@@ -3168,10 +2827,10 @@ var LoginSession = class {
3168
2827
  return viaRefresh;
3169
2828
  }
3170
2829
  if (policy.allowBrowser === false) {
3171
- throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED");
2830
+ throw new AuthError2("AUTH_REAUTHENTICATION_REQUIRED");
3172
2831
  }
3173
2832
  await this.#options.presenter?.present(TRUSTED_PARTY_COPY);
3174
- const result = await loginFlow(this.#options.auth);
2833
+ const result = await route33Login(this.#options.auth);
3175
2834
  this.#trackExpiry(result.tokenSet.expires_in);
3176
2835
  await this.#persist(result.tokenSet.refresh_token);
3177
2836
  return result;
@@ -3185,23 +2844,29 @@ var LoginSession = class {
3185
2844
  if (stored === void 0 || stored === "") {
3186
2845
  return void 0;
3187
2846
  }
3188
- let tokenSet;
3189
- try {
3190
- tokenSet = await this.#options.auth.session.refresh(stored);
3191
- } catch {
3192
- logger.info("auth.refresh.fell-back-to-browser");
2847
+ const tokenSet = await this.#tryRefreshToken(stored);
2848
+ if (tokenSet === void 0) {
3193
2849
  return void 0;
3194
2850
  }
3195
2851
  let credential;
3196
2852
  try {
3197
2853
  credential = parseManagementJwt(tokenSet.access_token);
3198
2854
  } catch (cause) {
3199
- throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID", { cause });
2855
+ throw new AuthError2("AUTH_TOKEN_RESPONSE_INVALID", { cause });
3200
2856
  }
3201
2857
  this.#trackExpiry(tokenSet.expires_in);
3202
2858
  await this.#persist(tokenSet.refresh_token);
3203
2859
  return { credential, tokenSet };
3204
2860
  }
2861
+ async #tryRefreshToken(stored) {
2862
+ const session = this.#options.auth.session;
2863
+ try {
2864
+ return await session.refresh(stored);
2865
+ } catch {
2866
+ logger.info("auth.refresh.fell-back-to-browser");
2867
+ return void 0;
2868
+ }
2869
+ }
3205
2870
  #trackExpiry(expiresIn) {
3206
2871
  this.#expiresAt = Date.now() + expiresIn * 1e3;
3207
2872
  }
@@ -3638,6 +3303,15 @@ var createRoute33Plugin = (options = {}) => {
3638
3303
  };
3639
3304
  };
3640
3305
 
3306
+ // src/production-runtime-options/production-runtime-options.ts
3307
+ import { createAuthSession } from "@r-33/auth-browser";
3308
+
3309
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3310
+ import {
3311
+ createRoute33Client,
3312
+ Route33SdkError
3313
+ } from "@r-33/sdk";
3314
+
3641
3315
  // src/contract/management-keys/parse-api-key/parse-api-key.ts
3642
3316
  var parseApiKey = (value) => {
3643
3317
  if (!isRecord(value) || !isOwnerType(value["ownership_type"]) || !isNullableString(value["project_id"])) {
@@ -3836,251 +3510,145 @@ var ManagementError = class extends Error {
3836
3510
  statusCode;
3837
3511
  };
3838
3512
 
3839
- // src/management/management-http-transport/management-http-transport.ts
3840
- var ManagementHttpTransport = class {
3841
- #baseUrl;
3842
- #credential;
3843
- #fetchImpl;
3844
- #onUnauthorized;
3845
- #timeoutMs;
3846
- constructor(options) {
3847
- const baseUrl = options.baseUrl ?? "https://api.route33.ai/v1";
3848
- this.#baseUrl = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
3849
- this.#credential = options.credential;
3850
- this.#fetchImpl = options.fetchImpl ?? fetch;
3851
- this.#onUnauthorized = options.onUnauthorized;
3852
- this.#timeoutMs = options.timeoutMs ?? 1e4;
3853
- }
3854
- /** Sends a request and reads one JSON value under the request timeout.
3855
- * @param request - Management path, method, and optional JSON body.
3856
- * @returns The untrusted response value.
3857
- */
3858
- json(request) {
3859
- return this.#perform(request, async (response) => {
3860
- try {
3861
- return await response.json();
3862
- } catch (cause) {
3863
- throw new ContractParseError("invalid management response", { cause });
3864
- }
3865
- });
3866
- }
3867
- /** Sends a request whose successful response has no body.
3868
- * @param request - Management path and method.
3869
- */
3870
- empty(request) {
3871
- return this.#perform(request, () => Promise.resolve());
3872
- }
3873
- async #perform(request, consume) {
3874
- const controller = new AbortController();
3875
- const timer = setTimeout(() => {
3876
- controller.abort();
3877
- }, this.#timeoutMs);
3878
- const headers = new Headers({
3879
- accept: "application/json",
3880
- authorization: `Bearer ${this.#credential.value}`
3513
+ // src/management/sdk-management-keys/sdk-management-keys.ts
3514
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3515
+ var sdkManagementKeys = (options) => {
3516
+ const baseUrl = options.apiBaseUrl.replace(API_PREFIX_PATTERN, "");
3517
+ const timeoutMs = options.timeoutMs ?? 1e4;
3518
+ const fetchImpl = options.fetchImpl;
3519
+ const observingFetch = (status) => fetchImpl === void 0 ? void 0 : async (input, init) => {
3520
+ const response = await fetchImpl(input, init);
3521
+ status.code = response.status;
3522
+ return response;
3523
+ };
3524
+ const callClient = (accessToken, status) => {
3525
+ const provider = {
3526
+ getToken: () => Promise.resolve(accessToken.value),
3527
+ onUnauthorized: () => Promise.resolve(accessToken.value)
3528
+ };
3529
+ const observedFetch = observingFetch(status);
3530
+ return createRoute33Client({
3531
+ baseUrl,
3532
+ provider,
3533
+ timeoutMs,
3534
+ ...observedFetch === void 0 ? {} : { fetch: observedFetch }
3881
3535
  });
3882
- if (request.body !== void 0) {
3883
- headers.set("content-type", "application/json");
3536
+ };
3537
+ const mapFailure = (cause) => {
3538
+ if (cause instanceof ManagementError || cause instanceof ContractParseError) {
3539
+ return cause;
3540
+ }
3541
+ if (cause instanceof Route33SdkError) {
3542
+ const code = cause.code === "SDK_TIMEOUT" ? "MANAGEMENT_TIMEOUT" : "MANAGEMENT_NETWORK_ERROR";
3543
+ return new ManagementError(code, { cause });
3884
3544
  }
3545
+ if (cause instanceof SyntaxError) {
3546
+ return new ContractParseError("invalid management response", { cause });
3547
+ }
3548
+ return new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3549
+ };
3550
+ const call = async (accessToken, run) => {
3551
+ const status = { code: void 0 };
3885
3552
  try {
3886
- const send = () => this.#fetchImpl(new URL(request.path, this.#baseUrl), {
3887
- ...request.body === void 0 ? {} : { body: JSON.stringify(request.body) },
3888
- headers,
3889
- method: request.method,
3890
- signal: controller.signal
3891
- });
3892
- let response = await send();
3893
- if (response.status === 401 && this.#onUnauthorized !== void 0) {
3894
- await this.#onUnauthorized();
3895
- response = await send();
3896
- }
3897
- if (!response.ok) {
3553
+ const outcome = await run(callClient(accessToken, status));
3554
+ const code = status.code;
3555
+ if (code === void 0 || code < 200 || code >= 300) {
3898
3556
  throw new ManagementError(
3899
- response.status === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3900
- { statusCode: response.status }
3557
+ code === 401 ? "MANAGEMENT_UNAUTHORIZED" : "MANAGEMENT_HTTP_ERROR",
3558
+ { statusCode: code }
3901
3559
  );
3902
3560
  }
3903
- return await consume(response);
3561
+ return outcome.data;
3904
3562
  } catch (cause) {
3905
- if (cause instanceof ManagementError) {
3906
- throw cause;
3907
- }
3908
- if (controller.signal.aborted) {
3909
- throw new ManagementError("MANAGEMENT_TIMEOUT", { cause });
3910
- }
3911
- if (cause instanceof ContractParseError) {
3912
- throw cause;
3913
- }
3914
- throw new ManagementError("MANAGEMENT_NETWORK_ERROR", { cause });
3915
- } finally {
3916
- clearTimeout(timer);
3563
+ throw mapFailure(cause);
3917
3564
  }
3918
- }
3919
- };
3920
-
3921
- // src/management/http-management-keys/http-management-keys.ts
3922
- var HttpManagementKeys = class {
3923
- #credential;
3924
- #transport;
3925
- constructor(options) {
3926
- this.#credential = options.credential;
3927
- this.#transport = new ManagementHttpTransport(options);
3928
- }
3929
- /** Creates a future-expiring ownership-scoped key.
3930
- * @param accessToken - Credential required by the frozen contract.
3931
- * @param input - Key name, expiry, and ownership.
3932
- * @returns One-time key material.
3933
- */
3934
- async create(accessToken, input) {
3935
- this.#authorize(accessToken);
3936
- return parseKeyMaterial(
3937
- await this.#transport.json({
3938
- body: {
3939
- ...input.allowedModels === void 0 ? {} : { allowed_models: input.allowedModels },
3940
- ...input.description === void 0 ? {} : { description: input.description },
3941
- expires_at: input.expiresAt,
3942
- ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3943
- name: input.name,
3944
- ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3945
- owner_type: input.ownerType,
3946
- ...input.projectId === null ? {} : { project_id: input.projectId }
3947
- },
3948
- method: "POST",
3949
- path: "api-keys"
3950
- })
3951
- );
3952
- }
3953
- /** Treats a successful empty response as confirmation of permanent removal.
3954
- * @param accessToken - Credential required by the frozen contract.
3955
- * @param id - Key identifier.
3956
- */
3957
- async delete(accessToken, id) {
3958
- this.#authorize(accessToken);
3959
- await this.#transport.empty({
3960
- method: "DELETE",
3961
- path: `api-keys/${encodeURIComponent(id)}`
3962
- });
3963
- }
3964
- /** Gets a safe key DTO.
3965
- * @param accessToken - Credential required by the frozen contract.
3966
- * @param id - Key identifier.
3967
- * @returns The secret-free key DTO.
3968
- */
3969
- async get(accessToken, id) {
3970
- this.#authorize(accessToken);
3971
- return parseApiKey(
3972
- await this.#transport.json({
3973
- method: "GET",
3974
- path: `api-keys/${encodeURIComponent(id)}`
3975
- })
3976
- );
3977
- }
3978
- /** Lists safe key DTOs.
3979
- * @param accessToken - Credential required by the frozen contract.
3980
- * @returns The parsed key collection.
3981
- */
3982
- async list(accessToken) {
3983
- this.#authorize(accessToken);
3984
- return parseCollection(
3985
- await this.#transport.json({ method: "GET", path: "api-keys" }),
3565
+ };
3566
+ return {
3567
+ create: async (accessToken, input) => parseKeyMaterial(
3568
+ await call(
3569
+ accessToken,
3570
+ (client) => client.POST("/api/v1/api-keys", {
3571
+ body: {
3572
+ ...input.allowedModels === void 0 ? {} : { allowed_models: [...input.allowedModels] },
3573
+ budget_currency: "EUR",
3574
+ ...input.description === void 0 ? {} : { description: input.description },
3575
+ expires_at: input.expiresAt,
3576
+ ...input.maxBudgetAmount === void 0 ? {} : { max_budget_amount: input.maxBudgetAmount },
3577
+ name: input.name,
3578
+ ...input.ownerId === null ? {} : { owner_user_id: input.ownerId },
3579
+ owner_type: input.ownerType,
3580
+ ...input.projectId === null ? {} : { project_id: input.projectId }
3581
+ }
3582
+ })
3583
+ )
3584
+ ),
3585
+ delete: async (accessToken, id) => {
3586
+ await call(
3587
+ accessToken,
3588
+ (client) => client.DELETE("/api/v1/api-keys/{api_key_id}", {
3589
+ params: { path: { api_key_id: id } }
3590
+ })
3591
+ );
3592
+ },
3593
+ get: async (accessToken, id) => parseApiKey(
3594
+ await call(
3595
+ accessToken,
3596
+ (client) => client.GET("/api/v1/api-keys/{api_key_id}", {
3597
+ params: { path: { api_key_id: id } }
3598
+ })
3599
+ )
3600
+ ),
3601
+ list: async (accessToken) => parseCollection(
3602
+ await call(accessToken, (client) => client.GET("/api/v1/api-keys", {})),
3986
3603
  parseApiKey
3987
- );
3988
- }
3989
- /** Lists organizations visible to the authenticated management subject.
3990
- * @param accessToken - Credential required by the frozen contract.
3991
- * @returns The parsed organization collection.
3992
- */
3993
- async listOrganizations(accessToken) {
3994
- this.#authorize(accessToken);
3995
- return parseCollection(
3996
- await this.#transport.json({ method: "GET", path: "orgs" }),
3604
+ ),
3605
+ listOrganizations: async (accessToken) => parseCollection(
3606
+ await call(accessToken, (client) => client.GET("/api/v1/orgs", {})),
3997
3607
  parseOrganization
3998
- );
3999
- }
4000
- /** Lists projects visible within an organisation filter.
4001
- * @param accessToken - Credential required by the frozen contract.
4002
- * @param organisationId - Required backend organisation filter.
4003
- * @returns The parsed project collection.
4004
- */
4005
- async listProjects(accessToken, organisationId) {
4006
- this.#authorize(accessToken);
4007
- if (organisationId.trim().length === 0) {
4008
- throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
4009
- statusCode: 400
4010
- });
4011
- }
4012
- const query = new URLSearchParams({
4013
- member_user_id: parseManagementSubject(accessToken),
4014
- org_id: organisationId
4015
- });
4016
- return parseCollection(
4017
- await this.#transport.json({
4018
- method: "GET",
4019
- path: `projects?${query.toString()}`
4020
- }),
4021
- parseProject
4022
- );
4023
- }
4024
- /** Regenerates one-time key material while preserving expiry when omitted.
4025
- * @param accessToken - Credential required by the frozen contract.
4026
- * @param id - Key identifier.
4027
- * @param expiresAt - Optional replacement expiry.
4028
- * @returns Regenerated one-time key material.
4029
- */
4030
- async regenerate(accessToken, id, expiresAt) {
4031
- this.#authorize(accessToken);
4032
- return parseKeyMaterial(
4033
- await this.#transport.json({
4034
- body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
4035
- method: "POST",
4036
- path: `api-keys/${encodeURIComponent(id)}/secrets`
4037
- })
4038
- );
4039
- }
4040
- /** Updates mutable key metadata.
4041
- * @param accessToken - Credential required by the frozen contract.
4042
- * @param id - Key identifier.
4043
- * @param input - Optional name and expiry replacements.
4044
- * @returns The updated safe key DTO.
4045
- */
4046
- async update(accessToken, id, input) {
4047
- this.#authorize(accessToken);
4048
- return parseApiKey(
4049
- await this.#transport.json({
4050
- body: {
4051
- ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
4052
- ...input.name === void 0 ? {} : { name: input.name }
4053
- },
4054
- method: "PATCH",
4055
- path: `api-keys/${encodeURIComponent(id)}`
4056
- })
4057
- );
4058
- }
4059
- #authorize(accessToken) {
4060
- if (accessToken.value !== this.#credential.value) {
4061
- throw new ManagementError("MANAGEMENT_UNAUTHORIZED", {
4062
- statusCode: 401
4063
- });
4064
- }
4065
- }
4066
- };
4067
-
4068
- // src/lazy-management-keys/lazy-management-keys.ts
4069
- var lazyManagementKeys = (options) => {
4070
- const client = (accessToken) => new HttpManagementKeys({
4071
- baseUrl: options.apiBaseUrl,
4072
- credential: accessToken,
4073
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
4074
- });
4075
- return {
4076
- create: async (accessToken, input) => client(accessToken).create(accessToken, input),
4077
- delete: async (accessToken, id) => client(accessToken).delete(accessToken, id),
4078
- get: async (accessToken, id) => client(accessToken).get(accessToken, id),
4079
- list: async (accessToken) => client(accessToken).list(accessToken),
4080
- listOrganizations: async (accessToken) => client(accessToken).listOrganizations(accessToken),
4081
- listProjects: async (accessToken, organisationId) => client(accessToken).listProjects(accessToken, organisationId),
4082
- regenerate: async (accessToken, id, expiresAt) => client(accessToken).regenerate(accessToken, id, expiresAt),
4083
- update: async (accessToken, id, input) => client(accessToken).update(accessToken, id, input)
3608
+ ),
3609
+ listProjects: async (accessToken, organisationId) => {
3610
+ if (organisationId.trim().length === 0) {
3611
+ throw new ManagementError("MANAGEMENT_ORGANISATION_ID_REQUIRED", {
3612
+ statusCode: 400
3613
+ });
3614
+ }
3615
+ return parseCollection(
3616
+ await call(
3617
+ accessToken,
3618
+ (client) => client.GET("/api/v1/projects", {
3619
+ params: {
3620
+ query: {
3621
+ member_user_id: parseManagementSubject(accessToken),
3622
+ org_id: organisationId
3623
+ }
3624
+ }
3625
+ })
3626
+ ),
3627
+ parseProject
3628
+ );
3629
+ },
3630
+ regenerate: async (accessToken, id, expiresAt) => parseKeyMaterial(
3631
+ await call(
3632
+ accessToken,
3633
+ (client) => client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3634
+ body: expiresAt === void 0 ? {} : { expires_at: expiresAt },
3635
+ params: { path: { api_key_id: id } }
3636
+ })
3637
+ )
3638
+ ),
3639
+ update: async (accessToken, id, input) => parseApiKey(
3640
+ await call(
3641
+ accessToken,
3642
+ (client) => client.PATCH("/api/v1/api-keys/{api_key_id}", {
3643
+ body: {
3644
+ budget_currency: "EUR",
3645
+ ...input.expiresAt === void 0 ? {} : { expires_at: input.expiresAt },
3646
+ ...input.name === void 0 ? {} : { name: input.name }
3647
+ },
3648
+ params: { path: { api_key_id: id } }
3649
+ })
3650
+ )
3651
+ )
4084
3652
  };
4085
3653
  };
4086
3654
 
@@ -4096,7 +3664,7 @@ var buildProductionRuntimeOptions = (input) => ({
4096
3664
  timeoutMs: LOGIN_BUDGET_MS
4097
3665
  },
4098
3666
  management: {
4099
- client: () => lazyManagementKeys({ apiBaseUrl: input.apiBaseUrl })
3667
+ client: () => sdkManagementKeys({ apiBaseUrl: input.apiBaseUrl })
4100
3668
  },
4101
3669
  ...input.tokenStore === void 0 ? {} : { tokenStore: input.tokenStore }
4102
3670
  });
@@ -4120,97 +3688,10 @@ var createHostAuthBridge = () => {
4120
3688
  };
4121
3689
  };
4122
3690
 
4123
- // src/auth/authorization-url-stash/loopback-origin/loopback-origin.ts
4124
- var loopbackOrigin = (url) => {
4125
- const redirect = url.searchParams.get("redirect_uri");
4126
- if (redirect === null) return void 0;
4127
- let parsed;
4128
- try {
4129
- parsed = new URL(redirect);
4130
- } catch {
4131
- return void 0;
4132
- }
4133
- return parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" ? parsed.origin : void 0;
4134
- };
4135
-
4136
- // src/auth/authorization-url-stash/authorization-url-stash.ts
4137
- var FALLBACK_URL = "https://route33.ai";
4138
- var SIGN_IN_INSTRUCTIONS = "Open the Route 33 sign-in link \u2014 your browser will finish at a confirmation page.";
4139
- var FINISHING_INSTRUCTIONS = "Finishing Route 33 setup\u2026";
4140
- var URL_WAIT_BUDGET_MS = 3e4;
4141
- var LISTENER_PROBE_TIMEOUT_MS = 750;
4142
- var createAuthorizationUrlStash = (options = {}) => {
4143
- let latest;
4144
- let waiters = [];
4145
- const browserRunner = (url) => {
4146
- latest = url;
4147
- const publish = waiters;
4148
- waiters = [];
4149
- for (const resolve2 of publish) resolve2(url);
4150
- return Promise.resolve();
4151
- };
4152
- const usableCandidate = async (url) => {
4153
- const origin = loopbackOrigin(url);
4154
- if (origin === void 0) return url;
4155
- const controller = new AbortController();
4156
- const timer = setTimeout(() => {
4157
- controller.abort();
4158
- }, options.listenerProbeTimeoutMs ?? LISTENER_PROBE_TIMEOUT_MS);
4159
- try {
4160
- const response = await (options.fetchImpl ?? fetch)(`${origin}/`, {
4161
- signal: controller.signal
4162
- });
4163
- return response.status >= 200 ? url : void 0;
4164
- } catch {
4165
- return void 0;
4166
- } finally {
4167
- clearTimeout(timer);
4168
- }
4169
- };
4170
- const urlForConnect = async (callback) => {
4171
- let decide;
4172
- const decided = new Promise((resolve2) => {
4173
- decide = resolve2;
4174
- });
4175
- const settle = (decision) => {
4176
- clearTimeout(timer);
4177
- decide(decision);
4178
- };
4179
- const timer = setTimeout(() => {
4180
- settle({ instructions: SIGN_IN_INSTRUCTIONS, url: FALLBACK_URL });
4181
- }, options.urlWaitBudgetMs ?? URL_WAIT_BUDGET_MS);
4182
- void Promise.resolve(callback).catch(() => void 0).then(() => {
4183
- settle({ instructions: FINISHING_INSTRUCTIONS, url: FALLBACK_URL });
4184
- });
4185
- const serve = (url) => {
4186
- settle({ instructions: SIGN_IN_INSTRUCTIONS, url: url.toString() });
4187
- };
4188
- const awaitPublish = () => {
4189
- const publish = new Promise((resolve2) => {
4190
- waiters.push(resolve2);
4191
- });
4192
- void publish.then(serve);
4193
- };
4194
- const candidate = latest;
4195
- if (candidate === void 0) {
4196
- awaitPublish();
4197
- } else {
4198
- void usableCandidate(candidate).then((usable) => {
4199
- if (usable !== void 0) {
4200
- serve(usable);
4201
- } else if (latest !== void 0 && latest !== candidate) {
4202
- serve(latest);
4203
- } else {
4204
- awaitPublish();
4205
- }
4206
- });
4207
- }
4208
- return decided;
4209
- };
4210
- return { browserRunner, urlForConnect };
4211
- };
4212
-
4213
3691
  // src/v1-entry/route33-auth-hook/route33-auth-hook.ts
3692
+ import {
3693
+ createAuthorizationUrlStash
3694
+ } from "@r-33/auth-browser";
4214
3695
  var createRoute33AuthHook = (deps) => ({
4215
3696
  loader: async (auth) => {
4216
3697
  deps.bridge.hydrate(await auth());
@@ -4410,6 +3891,7 @@ var contractFixtures = {
4410
3891
  var fixtureToWire = (value) => structuredClone(value);
4411
3892
 
4412
3893
  // src/contract/fixtures/parse-contract-fixtures/parse-contract-fixtures.ts
3894
+ import { parseTokenSet } from "@r-33/auth-browser";
4413
3895
  var parseContractFixtures = (fixtures) => ({
4414
3896
  apiKey: parseApiKey(fixtureToWire(fixtures.apiKey)),
4415
3897
  keyMaterial: parseKeyMaterial(fixtureToWire(fixtures.keyMaterial)),
@@ -4421,10 +3903,10 @@ var parseContractFixtures = (fixtures) => ({
4421
3903
  var clientId = readEnvClientId() ?? DEFAULT_ROUTE33_CLIENT_ID;
4422
3904
  var issuerUrl = readEnvAuthIssuer() ?? DEFAULT_AUTH_ISSUER_URL;
4423
3905
  var authBridge = createHostAuthBridge();
4424
- var startNativeLogin = (browserRunner) => loginFlow({
3906
+ var startNativeLogin = (browserRunner) => route33Login({
4425
3907
  browserRunner,
4426
3908
  clientId,
4427
- session: createAuthSession({ clientId, issuerUrl }),
3909
+ session: createAuthSession2({ clientId, issuerUrl }),
4428
3910
  timeoutMs: LOGIN_BUDGET_MS
4429
3911
  });
4430
3912
  var route33Plugin = createRoute33Plugin({
@@ -4478,14 +3960,13 @@ var Route33Plugin = async (input) => {
4478
3960
  };
4479
3961
  export {
4480
3962
  AttributionPromptError,
4481
- AuthError,
3963
+ CALLBACK_PAGE_COPY,
4482
3964
  ContractParseError,
4483
3965
  DEFAULT_GATEWAY_KEY_RENEWAL_RATIO,
4484
3966
  DEFAULT_GATEWAY_KEY_TTL_MS,
4485
3967
  FileSecretStore,
4486
3968
  GatewayApiKey,
4487
3969
  HostStorageSecretStore,
4488
- HttpManagementKeys,
4489
3970
  KeyLeaseError,
4490
3971
  LeaseState,
4491
3972
  ManagementError,
@@ -4495,26 +3976,19 @@ export {
4495
3976
  Route33Plugin,
4496
3977
  Route33Runtime,
4497
3978
  TRUSTED_PARTY_COPY,
4498
- buildAuthorizeUrl,
4499
3979
  changeAttribution,
4500
3980
  clearAttribution,
4501
3981
  contractFixtures,
4502
3982
  controlOrphans,
4503
3983
  createAttributionPrompt,
4504
- createAuthLoopbackCallback,
4505
- createAuthSession,
4506
3984
  createLeaseInstallationFactory,
4507
- createPkceVerifierAndChallenge,
4508
3985
  createRoute33Plugin,
4509
3986
  deriveScopeId,
4510
3987
  detectWorktreeRoot,
4511
- exchangeCodeAndParse,
4512
3988
  fixtureToWire,
4513
3989
  inspectSession,
4514
3990
  leaseForAttribution,
4515
- loginFlow,
4516
3991
  mintKey,
4517
- openBrowserAndCapture,
4518
3992
  parseApiKey,
4519
3993
  parseAttribution,
4520
3994
  parseCatalogResult,
@@ -4526,12 +4000,9 @@ export {
4526
4000
  parseManagementSubject,
4527
4001
  parseOrganization,
4528
4002
  parseProject,
4529
- parseTokenSet,
4530
- pkceChallenge,
4531
4003
  readAttribution,
4532
4004
  readLegacyKey,
4533
4005
  recoverLeaseState,
4534
- refreshSession,
4535
4006
  removeLegacyKey,
4536
4007
  renewKey,
4537
4008
  resetAttribution,
@@ -4541,5 +4012,7 @@ export {
4541
4012
  resolveSeamValue,
4542
4013
  reusableLease,
4543
4014
  rotateNow,
4015
+ route33Login,
4016
+ sdkManagementKeys,
4544
4017
  writeAttribution
4545
4018
  };