@dbx-tools/appkit 0.11.2 → 0.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,426 @@
1
+ /**
2
+ * AppKit workspace clients backed by the dbx-tools authentication lifecycle.
3
+ *
4
+ * AppKit 0.106 does not forward workspace IDs or custom transports to its
5
+ * modular SDK clients. This module scopes dynamic auth and workspace-ID
6
+ * headers to one client with AsyncLocalStorage, while a single fetch hook
7
+ * applies them only to matching requests made inside that client's calls.
8
+ *
9
+ * @module
10
+ */
11
+
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+
14
+ import {
15
+ createWorkspaceClient as createNativeWorkspaceClient,
16
+ ServiceContext,
17
+ type WorkspaceClient,
18
+ type WorkspaceClientOptions as NativeWorkspaceClientOptions,
19
+ } from "@databricks/appkit";
20
+ import {
21
+ createAuthClient,
22
+ DEFAULT_ACCESS_TOKEN_HEADER,
23
+ listProfiles,
24
+ type AuthClient,
25
+ type DatabricksAuthOptions,
26
+ WORKSPACE_ID_HEADER,
27
+ } from "@dbx-tools/auth";
28
+
29
+ interface WorkspaceCallContext {
30
+ origin(): Promise<string>;
31
+ headers(): Promise<Readonly<Record<string, string>>>;
32
+ }
33
+
34
+ interface WorkspaceFetchState {
35
+ readonly fetch: typeof globalThis.fetch;
36
+ wrapper: typeof globalThis.fetch;
37
+ readonly storage: AsyncLocalStorage<WorkspaceCallContext>;
38
+ readonly proxies: WeakMap<object, object>;
39
+ callerContextPatched: boolean;
40
+ }
41
+
42
+ const WORKSPACE_FETCH_STATE = Symbol.for("@dbx-tools/appkit.workspace-fetch-context");
43
+
44
+ type GlobalWithWorkspaceFetchState = typeof globalThis & {
45
+ [WORKSPACE_FETCH_STATE]?: WorkspaceFetchState;
46
+ };
47
+
48
+ interface ExistingClientContextOptions {
49
+ workspaceId?: string | Promise<string>;
50
+ }
51
+
52
+ /** Auth options plus AppKit's per-client user-agent metadata. */
53
+ export interface WorkspaceClientOptions extends DatabricksAuthOptions {
54
+ /** AppKit product and user-agent metadata. */
55
+ clientOptions?: NativeWorkspaceClientOptions["clientOptions"];
56
+ }
57
+
58
+ /**
59
+ * Create a client-scoped AppKit workspace client.
60
+ *
61
+ * Auth options and `AuthClient` inputs create a native AppKit client whose
62
+ * authorization is refreshed from `@dbx-tools/auth` for every request. An
63
+ * existing native client keeps its own authentication and gains only the
64
+ * configured workspace-ID header. Calling this function again with either the
65
+ * original client or its returned proxy returns the same proxy.
66
+ *
67
+ * The proxy scopes raw calls, modular SDK accessors, deferred waiter methods,
68
+ * and async iteration with `AsyncLocalStorage`. One process-wide fetch wrapper
69
+ * reads that scope. It delegates to the fetch implementation that was already
70
+ * installed, changes only authorization and workspace-ID headers for the
71
+ * matching client origin, and leaves unrelated requests and headers intact.
72
+ * A fetch wrapper installed later is not replaced; libraries that chain the
73
+ * current fetch implementation therefore compose with this compatibility
74
+ * layer in either installation order.
75
+ */
76
+ export function createWorkspaceClient(options?: WorkspaceClientOptions): Promise<WorkspaceClient>;
77
+ /** Create an AppKit client from an already-resolved dynamic auth client. */
78
+ export function createWorkspaceClient(auth: AuthClient): Promise<WorkspaceClient>;
79
+ /** Preserve an existing AppKit client's auth while adding client-scoped workspace-ID handling. */
80
+ export function createWorkspaceClient(client: WorkspaceClient): WorkspaceClient;
81
+ export function createWorkspaceClient(
82
+ source: WorkspaceClientOptions | AuthClient | WorkspaceClient = {},
83
+ ): WorkspaceClient | Promise<WorkspaceClient> {
84
+ if (isWorkspaceClient(source)) return wrapExistingWorkspaceClient(source);
85
+ return createAuthenticatedWorkspaceClient(source);
86
+ }
87
+
88
+ async function createAuthenticatedWorkspaceClient(
89
+ source: WorkspaceClientOptions | AuthClient,
90
+ ): Promise<WorkspaceClient> {
91
+ const auth = isAuthClient(source) ? source : await createAuthClient(source);
92
+ const clientOptions = isAuthClient(source) ? undefined : source.clientOptions;
93
+ const headers = await auth.headers();
94
+ const authorization = headerValue(headers, DEFAULT_ACCESS_TOKEN_HEADER);
95
+ if (!authorization) throw new Error("Databricks authentication did not return authorization");
96
+ const profile = isAuthClient(source) ? auth.profile : (source.profile ?? auth.profile);
97
+ const client = createNativeWorkspaceClient({
98
+ host: auth.host,
99
+ ...(profile ? { profile } : {}),
100
+ token: bearerToken(authorization),
101
+ ...(clientOptions ? { clientOptions } : {}),
102
+ });
103
+ const origin = workspaceOrigin(auth.host);
104
+ return wrapWorkspaceClient(client, {
105
+ origin: () => Promise.resolve(origin),
106
+ headers: () => auth.headers(),
107
+ });
108
+ }
109
+
110
+ function wrapExistingWorkspaceClient(
111
+ client: WorkspaceClient,
112
+ options: ExistingClientContextOptions = {},
113
+ ): WorkspaceClient {
114
+ const state = workspaceFetchState();
115
+ const existing = state.proxies.get(client);
116
+ if (existing) return existing as WorkspaceClient;
117
+
118
+ const origin = memoizedAsync(async () => workspaceOrigin(await client.getHost()));
119
+ const workspaceId = memoizedAsync(async () => {
120
+ if (options.workspaceId !== undefined) return options.workspaceId;
121
+ return configuredWorkspaceId(await origin());
122
+ });
123
+ return wrapWorkspaceClient(client, {
124
+ origin,
125
+ async headers() {
126
+ const resolved = await workspaceId();
127
+ const headers: Record<string, string> = {};
128
+ if (resolved) headers[WORKSPACE_ID_HEADER] = resolved;
129
+ return headers;
130
+ },
131
+ });
132
+ }
133
+
134
+ function wrapWorkspaceClient(
135
+ client: WorkspaceClient,
136
+ context: WorkspaceCallContext,
137
+ ): WorkspaceClient {
138
+ const state = workspaceFetchState();
139
+ return proxyCallSurface(state, client, context) as WorkspaceClient;
140
+ }
141
+
142
+ function workspaceFetchState(): WorkspaceFetchState {
143
+ const target = globalThis as GlobalWithWorkspaceFetchState;
144
+ const existing = target[WORKSPACE_FETCH_STATE];
145
+ if (existing) {
146
+ installCallerContextPatch(existing);
147
+ return existing;
148
+ }
149
+
150
+ const storage = new AsyncLocalStorage<WorkspaceCallContext>();
151
+ const state = {
152
+ fetch: globalThis.fetch,
153
+ storage,
154
+ proxies: new WeakMap<object, object>(),
155
+ callerContextPatched: false,
156
+ } as WorkspaceFetchState;
157
+ state.wrapper = (input, init) => authenticatedFetch(state, input, init);
158
+ target[WORKSPACE_FETCH_STATE] = state;
159
+ globalThis.fetch = state.wrapper;
160
+ installCallerContextPatch(state);
161
+ return state;
162
+ }
163
+
164
+ async function authenticatedFetch(
165
+ state: WorkspaceFetchState,
166
+ input: Parameters<typeof globalThis.fetch>[0],
167
+ init?: Parameters<typeof globalThis.fetch>[1],
168
+ ): Promise<Response> {
169
+ const context = state.storage.getStore();
170
+ if (!context) return state.fetch(input, init);
171
+
172
+ const request = new Request(input, init);
173
+ if (workspaceOrigin(request.url) !== (await context.origin())) {
174
+ return state.fetch(input, init);
175
+ }
176
+
177
+ const headers = new Headers(request.headers);
178
+ let changed = false;
179
+ for (const [name, value] of Object.entries(await context.headers())) {
180
+ if (headers.get(name) !== value) {
181
+ headers.set(name, value);
182
+ changed = true;
183
+ }
184
+ }
185
+ return changed ? state.fetch(new Request(request, { headers })) : state.fetch(input, init);
186
+ }
187
+
188
+ function proxyCallSurface(
189
+ state: WorkspaceFetchState,
190
+ target: object,
191
+ context: WorkspaceCallContext,
192
+ ): object {
193
+ const existing = state.proxies.get(target);
194
+ if (existing) return existing;
195
+
196
+ const methods = new Map<PropertyKey, Function>();
197
+ const proxy = new Proxy(target, {
198
+ get(current, property) {
199
+ const value = Reflect.get(current, property, current);
200
+ if (typeof value === "function") {
201
+ const existingMethod = methods.get(property);
202
+ if (existingMethod) return existingMethod;
203
+ const method =
204
+ property === "authenticate"
205
+ ? async (...args: unknown[]) => {
206
+ await state.storage.run(context, () => Reflect.apply(value, current, args));
207
+ const headers = args[0];
208
+ if (!(headers instanceof Headers)) return;
209
+ for (const [name, headerValue] of Object.entries(await context.headers())) {
210
+ headers.set(name, headerValue);
211
+ }
212
+ }
213
+ : (...args: unknown[]) =>
214
+ state.storage.run(context, () =>
215
+ wrapCallResult(state, context, Reflect.apply(value, current, args)),
216
+ );
217
+ methods.set(property, method);
218
+ return method;
219
+ }
220
+ return isProxyableObject(value) ? proxyCallSurface(state, value, context) : value;
221
+ },
222
+ });
223
+ state.proxies.set(target, proxy);
224
+ state.proxies.set(proxy, proxy);
225
+ return proxy;
226
+ }
227
+
228
+ function wrapCallResult(
229
+ state: WorkspaceFetchState,
230
+ context: WorkspaceCallContext,
231
+ value: unknown,
232
+ ): unknown {
233
+ if (isAsyncIterable(value)) return proxyAsyncIterable(state, value, context);
234
+ if (isPromiseLike(value)) {
235
+ return value.then((resolved) => wrapCallResult(state, context, resolved));
236
+ }
237
+ return isCallSurface(value) ? proxyCallSurface(state, value, context) : value;
238
+ }
239
+
240
+ function proxyAsyncIterable(
241
+ state: WorkspaceFetchState,
242
+ iterator: AsyncIterable<unknown>,
243
+ context: WorkspaceCallContext,
244
+ ): AsyncIterable<unknown> {
245
+ const existing = state.proxies.get(iterator);
246
+ if (existing) return existing as AsyncIterable<unknown>;
247
+
248
+ let proxy: AsyncIterable<unknown>;
249
+ proxy = new Proxy(iterator, {
250
+ get(current, property) {
251
+ const value = Reflect.get(current, property, current);
252
+ if (property === Symbol.asyncIterator && typeof value === "function") {
253
+ return (...args: unknown[]) => {
254
+ const resolved = state.storage.run(context, () => Reflect.apply(value, current, args));
255
+ return resolved === current
256
+ ? proxy
257
+ : proxyAsyncIterable(state, resolved as AsyncIterable<unknown>, context);
258
+ };
259
+ }
260
+ if (
261
+ (property === "next" || property === "return" || property === "throw") &&
262
+ typeof value === "function"
263
+ ) {
264
+ return (...args: unknown[]) =>
265
+ state.storage.run(context, () => Reflect.apply(value, current, args));
266
+ }
267
+ if (property === "then" && typeof value === "function") {
268
+ return (onFulfilled: unknown, onRejected: unknown) =>
269
+ state.storage.run(context, () =>
270
+ Reflect.apply(value, current, [
271
+ (resolved: unknown) => {
272
+ const wrapped = wrapCallResult(state, context, resolved);
273
+ return typeof onFulfilled === "function"
274
+ ? Reflect.apply(onFulfilled, undefined, [wrapped])
275
+ : wrapped;
276
+ },
277
+ onRejected,
278
+ ]),
279
+ );
280
+ }
281
+ if (typeof value === "function") {
282
+ return (...args: unknown[]) =>
283
+ state.storage.run(context, () => Reflect.apply(value, current, args));
284
+ }
285
+ return value;
286
+ },
287
+ });
288
+ state.proxies.set(iterator, proxy);
289
+ state.proxies.set(proxy, proxy);
290
+ return proxy;
291
+ }
292
+
293
+ /**
294
+ * Wrap the caller-context factory that is installed at first use.
295
+ *
296
+ * The captured factory is always invoked first, so a compatibility patch that
297
+ * was already present remains the owner of caller construction. If another
298
+ * library replaces the factory later, this module does not replace it again.
299
+ */
300
+ function installCallerContextPatch(state: WorkspaceFetchState): void {
301
+ if (state.callerContextPatched) return;
302
+ const createCallerContext = ServiceContext.createCallerContext;
303
+ ServiceContext.createCallerContext = function patchedCreateCallerContext(...args) {
304
+ const caller = Reflect.apply(createCallerContext, ServiceContext, args);
305
+ const client = wrapExistingWorkspaceClient(caller.client, {
306
+ workspaceId: caller.workspaceId,
307
+ });
308
+ if (client === caller.client) return caller;
309
+ return Object.freeze({ ...caller, client });
310
+ };
311
+ state.callerContextPatched = true;
312
+ }
313
+
314
+ function configuredWorkspaceId(origin: string): string | undefined {
315
+ const workspaceIds = new Set<string>();
316
+ const environmentHost = process.env.DATABRICKS_HOST;
317
+ if (
318
+ environmentHost &&
319
+ process.env.DATABRICKS_WORKSPACE_ID &&
320
+ workspaceOrigin(environmentHost) === origin
321
+ ) {
322
+ workspaceIds.add(process.env.DATABRICKS_WORKSPACE_ID);
323
+ }
324
+ for (const profile of listProfiles()) {
325
+ if (profile.host && profile.workspaceId && workspaceOrigin(profile.host) === origin) {
326
+ workspaceIds.add(profile.workspaceId);
327
+ }
328
+ }
329
+ if (workspaceIds.size > 1) {
330
+ throw new Error(`Multiple Databricks workspace IDs are configured for ${origin}`);
331
+ }
332
+ return workspaceIds.values().next().value;
333
+ }
334
+
335
+ function memoizedAsync<T>(operation: () => T | Promise<T>): () => Promise<Awaited<T>> {
336
+ let pending: Promise<Awaited<T>> | undefined;
337
+ return () => {
338
+ pending ??= Promise.resolve(operation()).catch((error) => {
339
+ pending = undefined;
340
+ throw error;
341
+ });
342
+ return pending;
343
+ };
344
+ }
345
+
346
+ function workspaceOrigin(host: string): string {
347
+ const normalized = /^https?:\/\//i.test(host) ? host : `https://${host}`;
348
+ return new URL(normalized).origin;
349
+ }
350
+
351
+ function headerValue(headers: Readonly<Record<string, string>>, name: string): string | undefined {
352
+ const expected = name.toLowerCase();
353
+ return Object.entries(headers).find(([key]) => key.toLowerCase() === expected)?.[1];
354
+ }
355
+
356
+ function isAuthClient(value: AuthClient | DatabricksAuthOptions): value is AuthClient {
357
+ return (
358
+ typeof value === "object" &&
359
+ value !== null &&
360
+ "headers" in value &&
361
+ typeof value.headers === "function" &&
362
+ "host" in value &&
363
+ typeof value.host === "string"
364
+ );
365
+ }
366
+
367
+ function isWorkspaceClient(
368
+ value: WorkspaceClientOptions | AuthClient | WorkspaceClient,
369
+ ): value is WorkspaceClient {
370
+ return (
371
+ typeof value === "object" &&
372
+ value !== null &&
373
+ "getHost" in value &&
374
+ typeof value.getHost === "function" &&
375
+ "authenticate" in value &&
376
+ typeof value.authenticate === "function" &&
377
+ "request" in value &&
378
+ typeof value.request === "function"
379
+ );
380
+ }
381
+
382
+ function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
383
+ return (
384
+ (typeof value === "object" || typeof value === "function") &&
385
+ value !== null &&
386
+ "then" in value &&
387
+ typeof value.then === "function"
388
+ );
389
+ }
390
+
391
+ function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
392
+ return (
393
+ typeof value === "object" &&
394
+ value !== null &&
395
+ Symbol.asyncIterator in value &&
396
+ typeof value[Symbol.asyncIterator] === "function"
397
+ );
398
+ }
399
+
400
+ function isCallSurface(value: unknown): value is object {
401
+ if (!isProxyableObject(value)) return false;
402
+ let owner: object | null = value;
403
+ while (owner && owner !== Object.prototype) {
404
+ for (const property of Reflect.ownKeys(owner)) {
405
+ if (property === "constructor") continue;
406
+ if (typeof Reflect.getOwnPropertyDescriptor(owner, property)?.value === "function")
407
+ return true;
408
+ }
409
+ owner = Reflect.getPrototypeOf(owner);
410
+ }
411
+ return false;
412
+ }
413
+
414
+ function isProxyableObject(value: unknown): value is object {
415
+ return (
416
+ typeof value === "object" &&
417
+ value !== null &&
418
+ Object.prototype.toString.call(value) === "[object Object]"
419
+ );
420
+ }
421
+
422
+ function bearerToken(authorization: string): string {
423
+ const match = /^Bearer\s+(.+)$/i.exec(authorization);
424
+ if (!match?.[1]) throw new Error("Databricks authentication did not return a bearer token");
425
+ return match[1];
426
+ }