diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 2e883efa6c..a1fc20442a 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -ab02cdcdd4b936e8f1c905fc70df182d1a58e5bb +a403f3ce12fd150dd649098e61562eda1e6a4d81 diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 683b7323b7..2c2482c488 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -9182,13 +9182,21 @@ paths: type: string supports_client_credentials: type: boolean + supports_authorization_code: + type: boolean + description: The instance entry declares the authorization-code grant, so users can sign in with their own account when has_shared_credentials is also true. has_shared_credentials: type: boolean - description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. Whether client credentials are shared is get_connect's client_credentials_configured. + description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. + shares_client_credentials: + type: boolean + description: Users may connect as the instance entry's own app with its shared client credentials, with no sign-in. required: - name - supports_client_credentials + - supports_authorization_code - has_shared_credentials + - shares_client_credentials /oauth/get_connect/{client}: get: diff --git a/backend/windmill-api/src/oauth2_oss.rs b/backend/windmill-api/src/oauth2_oss.rs index 845c989f9a..6f7a2c6daa 100644 --- a/backend/windmill-api/src/oauth2_oss.rs +++ b/backend/windmill-api/src/oauth2_oss.rs @@ -115,7 +115,9 @@ async fn list_logins() -> error::JsonResult { struct OAuthConnectListItem { name: String, supports_client_credentials: bool, + supports_authorization_code: bool, has_shared_credentials: bool, + shares_client_credentials: bool, } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-oauth/src/lib.rs b/backend/windmill-oauth/src/lib.rs index e986fffa7d..524b72dfe5 100644 --- a/backend/windmill-oauth/src/lib.rs +++ b/backend/windmill-oauth/src/lib.rs @@ -74,9 +74,10 @@ pub struct ClientWithScopes { /// persist it on client-credentials accounts. pub token_url: String, /// Whether the instance entry carries shared credentials (non-empty id + - /// secret). Providers without them are bring-your-own only — the connect - /// dialog lists them under "Others", not "Instance-configured". + /// secret). Providers without them are bring-your-own only. pub has_shared_credentials: bool, + /// [`OAuthClient::shares_client_credentials`] resolved. + pub shares_client_credentials: bool, /// [`OAuthClient::pkce`] resolved; only the login flow reads it. pub pkce: bool, } diff --git a/frontend/src/lib/components/AppConnectDrawer.svelte b/frontend/src/lib/components/AppConnectDrawer.svelte index ca6cb05300..9e5f1a05b1 100644 --- a/frontend/src/lib/components/AppConnectDrawer.svelte +++ b/frontend/src/lib/components/AppConnectDrawer.svelte @@ -29,6 +29,8 @@ let disabled = $state(false) let isGoogleSignin = $state(false) let manual = $state(true) + let actionLabel: string | undefined = $state(undefined) + let canGoBack: boolean | undefined = $state(undefined) let appConnectInner: AppConnectInner | undefined = $state(undefined) @@ -96,6 +98,8 @@ bind:isGoogleSignin bind:disabled bind:manual + bind:actionLabel + bind:canGoBack on:close={drawer?.closeDrawer} on:refresh express={expressOAuthSetup} @@ -105,9 +109,7 @@ /> {#snippet actions()}
- - {#if step > 1 && !rtToLoad} + {#if canGoBack} @@ -121,13 +123,7 @@ {disabled} onClick={() => appConnectInner?.next()} > - {#if (step == 2 && !manual) || native} - Connect - {:else if step == 1} - Next - {:else} - Save - {/if} + {actionLabel ?? 'Next'} {/if}
diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index b584815a7f..1e879593e8 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -8,7 +8,6 @@ addResourceTypeDisplayName, isCustomResourceTypeName, resourceTypeDisplayName, - resourceTypeMatchRank, resourceTypeSearchText, setResourceTypeDisplayNames, sortResourceTypesByMatch @@ -26,6 +25,7 @@ import { createEventDispatcher, onDestroy, tick } from 'svelte' import Path from './Path.svelte' import { Badge, ListRow, RadioCard, Skeleton } from './common' + import Stepper from './common/stepper/Stepper.svelte' import { useListHighlight } from './common/listRow/listHighlight.svelte' import ApiConnectForm from './ApiConnectForm.svelte' import SearchItems from './SearchItems.svelte' @@ -47,7 +47,8 @@ byPopularity, hubResourceTypePicks, localResourceTypeCounts, - recordHubResourceTypePick + recordHubResourceTypePick, + type PopularityCounts } from './pickerPopularity' import Label from './Label.svelte' import ResourcePathHint from './ResourcePathHint.svelte' @@ -80,6 +81,10 @@ * popup through the trigger service's OAuth app, whose callback saves the connection. */ native?: NativeConnect + /** What the caller's primary button does on the current step. */ + actionLabel?: string + /** Whether the caller should offer Back on the current step. */ + canGoBack?: boolean } let { @@ -91,9 +96,21 @@ express = false, workspace = undefined, fillPath = undefined, - native = undefined + native = undefined, + actionLabel = $bindable(), + canGoBack = $bindable() }: Props = $props() + /** + * Steps: 1 resource type, 2 authentication method (skipped when only one is offered), + * 3 the method's inputs (a manual resource is saved here), 4 waiting on the OAuth + * exchange, 5 path and save of an OAuth resource. + */ + type ConnectMethod = 'auth_code' | 'auth_code_user' | 'cc_shared' | 'cc_byo' | 'manual' + let method: ConnectMethod | undefined = $state(undefined) + /** Opened on one resource type: the type list was never shown, so there is no going back to it. */ + let openedOnType = $state(false) + let effectiveWorkspace = $derived(workspace ?? $operatingWorkspace!) let isValid = $state(true) @@ -118,12 +135,16 @@ /** Per-provider instance-entry metadata, keyed by provider name. */ let connectsInfo: Record< string, - { supports_client_credentials: boolean; has_shared_credentials: boolean } + { + supports_client_credentials: boolean + supports_authorization_code: boolean + has_shared_credentials: boolean + shares_client_credentials: boolean + } > = $state({}) - /** An instance entry with shared credentials (admin id+secret): connect with - * no input. Shown under "Instance-configured"; bring-your-own-only providers - * (no shared creds) are shown under "Others" instead. */ + /** An instance entry with shared credentials (instance id+secret), which the browser + * sign-in needs. Bring-your-own-only entries (no shared creds) are not one. */ function isSharedConnect(key: string): boolean { return connectsInfo[key]?.has_shared_credentials ?? false } @@ -233,13 +254,6 @@ } } - function selectUserToken(user: boolean) { - if (user !== useUserToken) { - scopes = user ? (registryEntry()?.user_scopes ?? []) : instanceScopes - } - useUserToken = user - } - /** * Client credentials for resource-level OAuth */ @@ -331,39 +345,110 @@ * doesn't enter their own — the exchange runs server-side with those creds */ let ccInstanceConfigured = $state(false) - /** The user wants their own credentials (picked the provider from the "Others" - * section) — overrides the shared instance credentials for this connection */ - let ccBringYourOwn = $state(false) - /** Connect with the shared instance credentials (no form) rather than the * bring-your-own form */ - let useSharedInstanceCreds = $derived(ccInstanceConfigured && !ccBringYourOwn) + let useSharedInstanceCreds = $derived(method === 'cc_shared') - /** Connectable via client credentials only: registry-declared provider with - * no instance OAuth client, or instance provider without an authorize URL */ - let ccOnly = $derived.by( - () => - authCodeUnavailable || - (registryCcCapable() && connectClient != '' && !(connects?.includes(connectClient) ?? false)) - ) + /** The ways in this provider offers, read once `getScopesAndParams` has run. A browser + * sign-in the registry declares but the instance holds no client for is listed disabled, + * so the user learns it exists and who can turn it on. */ + let methodOptions = $derived.by(() => { + const signIn = isSharedConnect(connectClient) && !authCodeUnavailable + const opts: { method: ConnectMethod; disabled: boolean }[] = [] + if (signIn || (registryEntry()?.grant_types?.includes('authorization_code') ?? false)) { + opts.push({ method: 'auth_code', disabled: !signIn }) + if (registryEntry()?.user_scopes) { + opts.push({ method: 'auth_code_user', disabled: !signIn }) + } + } + if (ccInstanceConfigured) opts.push({ method: 'cc_shared', disabled: false }) + if (supportsClientCredentials) opts.push({ method: 'cc_byo', disabled: false }) + opts.push({ method: 'manual', disabled: false }) + return opts + }) + let enabledMethods = $derived(methodOptions.filter((o) => !o.disabled).map((o) => o.method)) + let methodStepShown = $derived(enabledMethods.length > 1) - /** The provider also has a browser sign-in, unavailable here only because the - * instance holds no OAuth client for it */ - let signInNeedsInstanceClient = $derived.by( - () => - (registryEntry()?.grant_types?.includes('authorization_code') ?? false) && - connectClient != '' && - !(connects?.includes(connectClient) ?? false) - ) + function methodCopy( + m: ConnectMethod, + disabled: boolean + ): { label: string; description: string; grant: string } { + const browser = disabled + ? `Needs an OAuth client for ${providerName} in the instance settings.` + : 'Opens a browser window to authorize.' + switch (m) { + case 'auth_code': + return registryEntry()?.user_scopes + ? { + label: 'Install the app (bot token)', + description: `${browser} Acts as the app's bot user, in the channels it is added to.`, + grant: 'Authorization code' + } + : { + label: `Log in with your ${providerName} account`, + description: `${browser} The connection acts as you.`, + grant: 'Authorization code' + } + case 'auth_code_user': + return { + label: `Log in with your ${providerName} account (user token)`, + description: `${browser} Acts as you, with access to what you can see: history, DMs and search.`, + grant: 'Authorization code' + } + case 'cc_shared': + return { + label: "Connect as this instance's app", + description: + 'Uses the app configured in the instance settings. No input needed. The connection acts as that app, not as you.', + grant: 'Client credentials' + } + case 'cc_byo': + return { + label: 'Connect as your own app', + description: `Enter the client ID and secret of an app registered in ${providerName}. The connection acts as that app, not as you.`, + grant: 'Client credentials' + } + case 'manual': + return { + label: 'Enter credentials manually', + description: "Fill in the resource's fields yourself, such as an API key or a token.", + grant: '' + } + } + } + + function selectMethod(m: ConnectMethod) { + // Re-picking the current method after Back keeps the scopes the user edited. + if (m === method) return + method = m + manual = m === 'manual' + useClientCredentials = m === 'cc_shared' || m === 'cc_byo' + useUserToken = m === 'auth_code_user' + // Each grant starts from its own defaults: most providers reject authorization-code + // scopes in a 2-legged request, and Slack's user token takes `user_scope`. + scopes = useClientCredentials + ? defaultCcScopes() + : useUserToken + ? (registryEntry()?.user_scopes ?? []) + : instanceScopes + } + + function backTarget(s: number): number { + return s >= 4 ? 3 : s == 3 ? (methodStepShown ? 2 : 1) : s == 2 ? 1 : 0 + } + function canBackFrom(s: number): boolean { + const t = backTarget(s) + return !native && !express && t > 0 && (t > 1 || !openedOnType) + } /** Clear CC inputs and scopes so a previous selection never leaks into a new one */ function resetClientCredentialsState() { + method = undefined supportsClientCredentials = false useClientCredentials = false useUserToken = false authCodeUnavailable = false ccInstanceConfigured = false - ccBringYourOwn = false clientId = '' clientSecret = '' ccInstance = '' @@ -385,62 +470,21 @@ return entry ? (entry.cc_scopes ?? []) : instanceScopes } - function enableClientCredentials() { - manual = false - supportsClientCredentials = true - if (!useClientCredentials) { - // Switching into client-credentials: default to the CC scopes (never the - // authorization-code scopes — most providers reject member/consent scopes - // in a 2-legged request). Only reset on the transition so edits made while - // already in CC mode are preserved. - scopes = defaultCcScopes() - } - useClientCredentials = true + /** Only an instance OAuth client is a `_sandbox` alias of its parent type; a resource + * type's own name may end in `_sandbox` too. */ + function typeOfKey(key: string): string { + return connects?.includes(key) ? stripSandboxSuffix(key) : key } - /** Switch to the browser sign-in (authorization-code) grant, restoring its - * default scopes when coming from the client-credentials grant. */ - function selectAuthCodeGrant() { - if (useClientCredentials) { - scopes = instanceScopes - } - useClientCredentials = false - } - - /** Static registry declares client-credentials support for `key`. */ - function isCcCapable(key: string): boolean { - return registryCcCapableFor(key) - } - - /** Step-1 "Others" selection: CC-capable resource types open the client- - * credentials form with the user's own credentials — even when the instance - * has shared ones (the "Instance-configured OAuth APIs" section is the entry - * point for those). Every other type opens the raw manual form. */ - function connectOauth(key: string) { - manual = false + function selectType(key: string) { connectClient = key - resourceType = stripSandboxSuffix(key) + resourceType = typeOfKey(key) + // The path form names it after the type, so one generated for another type must go. + path = '' resetClientCredentialsState() next() } - function selectFromOthers(key: string) { - connectClient = key - resourceType = key - resetClientCredentialsState() - // Registry CC providers and instance-configured providers that declare the - // client-credentials grant (incl. custom providers set up with only a token - // URL and no shared creds) open the bring-your-own form. Everything else is - // a manual resource. - if (isCcCapable(key) || (connectsInfo[key]?.supports_client_credentials ?? false)) { - ccBringYourOwn = true - enableClientCredentials() - } else { - manual = true - } - next() - } - let pathError = $state('') export async function open(rt?: string) { @@ -448,9 +492,10 @@ resourceType = rt ?? '' manual = false path = '' - step = 4 + step = 5 return } + openedOnType = !!rt if (!rt) { loadResourceTypes() loadPopularity() @@ -464,38 +509,32 @@ wsSpecific = false const rawRt = rt ?? '' connectClient = rawRt - resourceType = stripSandboxSuffix(rawRt) valueToken = undefined resetClientCredentialsState() await loadConnects() - const inConnects = connects?.includes(connectClient) ?? false - // Registry-declared client-credentials providers are connectable even - // without an instance OAuth client - manual = !inConnects && !(rt && registryCcCapable()) - if (manual && express) { - dispatch('error', 'Express OAuth setup is not available for non OAuth resource types') - return - } - if (!inConnects && !manual && express) { - // Client-credentials connections need interactive credential entry - dispatch('error', 'Express OAuth setup is not available for client credentials providers') - return - } - if (!inConnects && !manual) { - enableClientCredentials() - } - if (rt) { - if (!manual && express) { - await getScopesAndParams() - if (authCodeUnavailable) { - // No popup flow to drive express setup with - dispatch('error', 'Express OAuth setup is not available for client credentials providers') - return - } - step = 2 + resourceType = typeOfKey(rawRt) + if (express) { + // Express drives the browser sign-in with no input, so it needs the instance's client. + if (!(connects?.includes(connectClient) ?? false)) { + dispatch( + 'error', + registryCcCapable() + ? 'Express OAuth setup is not available for client credentials providers' + : 'Express OAuth setup is not available for non OAuth resource types' + ) + return } + await getScopesAndParams() + if (authCodeUnavailable) { + dispatch('error', 'Express OAuth setup is not available for client credentials providers') + return + } + selectMethod('auth_code') + step = 3 + next() + } else if (rt) { next() } } @@ -503,18 +542,27 @@ /** * Orders the browse list: the types this workspace already has resources of lead, ranked * among themselves by the hub's pick counts, then everything else on the same counts. - * `byPopularity` carries the full rule. Both signals are fetched, so the rows render - * alphabetically and re-sort when this lands. + * `byPopularity` carries the full rule. The list waits on it, so it renders once and in + * order rather than re-sorting under the pointer; the hub is the slow signal, so it gets + * `HUB_PICKS_WAIT_MS` and is left out past that, never holding the list. */ let popularity: (a: string, b: string) => number = $state(alphabetical) + let popularityReady = $state(false) + const HUB_PICKS_WAIT_MS = 1500 async function loadPopularity() { - if (!effectiveWorkspace) return - const [hub, local] = await Promise.all([ - hubResourceTypePicks(effectiveWorkspace), - localResourceTypeCounts(effectiveWorkspace) - ]) - popularity = byPopularity(hub, local) + if (effectiveWorkspace) { + const none: PopularityCounts = {} + const [hub, local] = await Promise.all([ + Promise.race([ + hubResourceTypePicks(effectiveWorkspace).catch(() => none), + new Promise((r) => setTimeout(() => r(none), HUB_PICKS_WAIT_MS)) + ]), + localResourceTypeCounts(effectiveWorkspace).catch(() => none) + ]) + popularity = byPopularity(hub, local) + } + popularityReady = true } async function loadConnects() { @@ -534,13 +582,15 @@ } // Google's terms require its own button on the control that starts the sign-in, which is - // the step-2 Connect: step 1 only picks a type, and a manual step 2 saves a resource - // without ever reaching Google. Every registry provider that signs in through Google's - // authorize endpoint counts; `google` itself is a login provider, not a registry entry. + // the step-3 Connect of a browser sign-in: the earlier steps only pick, and a manual or + // client-credentials step 3 never reaches Google's sign-in. Every registry provider that + // signs in through Google's authorize endpoint counts; `google` itself is a login + // provider, not a registry entry. run(() => { isGoogleSignin = - (step == 2 || (!!native && step == 4)) && + (step == 3 || (!!native && step == 5)) && !manual && + !useClientCredentials && (resourceType == 'google' || (registryEntryFor(resourceType)?.auth_url?.startsWith('https://accounts.google.com/') ?? false)) @@ -549,7 +599,8 @@ run(() => { disabled = (step == 1 && resourceType == '') || - (step == 2 && + (step == 2 && !method) || + (step == 3 && (manual ? value == '' && args && @@ -563,9 +614,15 @@ (clientId.trim() == '' || clientSecret.trim() == '' || (!!ccInstanceMeta && ccInstance.trim() == '')))) || - step == 3 || - (step == 4 && (pathError != '' || (!!native && !path))) || - !isValid + step == 4 || + (step == 5 && (pathError != '' || (!!native && !path))) || + // The manual form's own validity: it must not hold Next once the form is left. + (step == 3 && manual && !isValid) + }) + + run(() => { + canGoBack = canBackFrom(step) + actionLabel = native || (step == 3 && !manual) ? 'Connect' : step <= 2 ? 'Next' : 'Save' }) export async function loadResourceTypes() { @@ -601,10 +658,6 @@ }) .catch(() => {}) - // "Others" lists every resource type — including instance-configured OAuth - // providers — so any of them can also be connected with the user's own - // credentials or manually, not only via the shared instance setup (same as - // the authorization-code behavior). connectsManual = availableRts.map( (x) => ({ @@ -684,7 +737,7 @@ console.log('Processing oauth popup data') if (data.type === 'error') { sendUserToast(data.error, true) - step = 2 + step = 3 } else if (data.type === 'success') { connectClient = data.resource_type resourceType = stripSandboxSuffix(connectClient) @@ -692,7 +745,7 @@ valueToken = data.res Object.assign(args, data.res.resource_fields ?? {}) fillGeneratedDescription() - step = 4 + step = 5 // `fillPath` decides the path as surely as express does, so neither stops here. if (fillPath || express) { path = fillPath ?? `u/${$userStore?.username}/${defaultName}_${new Date().getTime()}` @@ -701,13 +754,11 @@ } } + /** Reads what the provider offers; `selectMethod` then sets the grant and its scopes. */ async function getScopesAndParams() { - useUserToken = false if (!connects?.includes(connectClient)) { - // No instance OAuth client (registry-declared CC-only provider): - // defaults come from the static registry instead. + // No instance OAuth client: defaults come from the static registry instead. instanceScopes = registryEntry()?.scopes ?? [] - scopes = useClientCredentials ? defaultCcScopes() : instanceScopes extra_params = [] supportsClientCredentials = registryCcCapable() return @@ -728,14 +779,6 @@ // Custom provider configured with only a token URL: no popup flow possible authCodeUnavailable = supportsClientCredentials && !(connect.grant_types?.includes('authorization_code') ?? true) - if (authCodeUnavailable) { - useClientCredentials = true - } - // Default scopes to the active grant: client-credentials uses the registry's - // cc_scopes (auth-code scopes are invalid in a 2-legged request), every other - // path keeps the instance entry's scopes. Applies to shared instance creds, - // not just bring-your-own. Switching grants resets to these defaults. - scopes = useClientCredentials ? defaultCcScopes() : instanceScopes } async function getResourceTypeInfo() { @@ -762,30 +805,28 @@ } export async function next() { if (native) { - step = 3 + step = 4 try { await native.connect(path) dispatch('close') } catch { - step = 4 + step = 5 } return } if (step == 1) { linkedSecrets = [] - // Both branches: the OAuth one fills `resourceFields` into the same map, and fields - // typed into another type's form before Back would otherwise ride along. + // The OAuth path fills `resourceFields` into the same map, and fields typed into + // another type's form before Back would otherwise ride along. args = {} - if (manual) { - getResourceTypeInfo() - } else { - getResourceTypeInfo() - // Awaited: the popup is built from `scopes`, so advancing before this - // resolves sends the user to an authorize url with no scope at all. - await getScopesAndParams() - } - step += 1 - } else if (step == 2 && !manual) { + getResourceTypeInfo() + // Awaited: the methods offered, and the scopes the popup is built from, come from it. + await getScopesAndParams() + selectMethod(enabledMethods[0]) + step = methodStepShown ? 2 : 3 + } else if (step == 2) { + step = 3 + } else if (step == 3 && !manual) { if (useClientCredentials) { /** * Client credentials flow: Direct API call to backend @@ -844,7 +885,7 @@ grant_type: 'client_credentials' // Mark this token as client_credentials } fillGeneratedDescription() - step = 4 + step = 5 if (fillPath || express) { path = fillPath ?? `u/${$userStore?.username}/${defaultName}_${new Date().getTime()}` next() @@ -878,7 +919,7 @@ } } else { if (!path) { - if (step == 2) return + if (step == 3) return throw Error('Path is not set') } // Check if variable paths already exist @@ -958,7 +999,8 @@ if (connectTemplate?.resource_mapping) { const instanceKey = connectTemplate.extra_params_key ?? 'instance' let instanceValue = extra_params.find(([key, _]) => key === instanceKey)?.[1] ?? '' - if (ccInstance.trim()) { + // Only the bring-your-own exchange used it: one typed before switching method is stale. + if (method === 'cc_byo' && ccInstance.trim()) { const stripSuffix = connectTemplate.strip_suffix as string | undefined let v = ccInstance .trim() @@ -1129,12 +1171,9 @@ } } - export async function back() { - if (step == 4) { - step -= 2 - } else if (step > 1) { - step -= 1 - } + export function back() { + if (!canBackFrom(step)) return + step = backTarget(step) if (step == 1) { loadConnects() loadResourceTypes() @@ -1144,9 +1183,18 @@ } } + /** Stepper index of each step: waiting on the exchange still reads as "Connect". */ + let stepIndex = $derived(step <= 3 ? step - 1 : step == 4 ? 2 : 3) + const STEP_OF_INDEX = [1, 2, 3, 5] + + function goToStep(index: number) { + const target = STEP_OF_INDEX[index] + if ((target == 2 && !methodStepShown) || (target == 1 && openedOnType)) return + while (step > target && canBackFrom(step)) back() + } + const dispatch = createEventDispatcher<{ error: string; refresh: string; close: void }>() - let filteredConnects: { key: string }[] = $state([]) let filteredConnectsManual: { key: string; img?: string; instructions: string[] }[] = $state([]) let searching = $derived(filter.trim() !== '') @@ -1173,70 +1221,55 @@ popularity(stripSandboxSuffix(a.key), stripSandboxSuffix(b.key)) || a.key.localeCompare(b.key) )) - let rankedConnects = $derived(rank(filteredConnects)) let rankedConnectsManual = $derived( rank(filteredConnectsManual) as typeof filteredConnectsManual | undefined ) - // Browsing, the "Others" list leads with the native database types. Searching, that - // grouping would outrank the search itself — `ms_sql_server` sorting under `mysql` on - // "sql" — so the ranked order stands on its own. - let manualOrderedKeys = $derived( - !searching - ? [ - ...(rankedConnectsManual ?? []) - .filter((x) => nativeLanguagesCategory.includes(x.key)) - .map((x) => x.key), - ...(rankedConnectsManual ?? []) - .filter((x) => !nativeLanguagesCategory.includes(x.key)) - .map((x) => x.key) - ] - : (rankedConnectsManual ?? []).map((x) => x.key) + /** One row per provider: every resource type, plus the instance OAuth clients no type is + * named after (a `_sandbox` client, a custom provider). How to connect is picked after. */ + let typeItems = $derived.by(() => { + const types = connectsManual + const clients: string[] | undefined = connects + if (!types || !clients) return undefined + return [ + ...types, + ...clients + .filter((k) => isSharedConnect(k) && !types.some((x) => x.key == k)) + .map((key) => ({ key, instructions: [] as string[] })) + ] + }) + + // Browsing, the list leads with the workspace's custom types, then the providers the + // instance has an OAuth client for, then the native database types. Searching, that + // grouping would outrank the search itself (`ms_sql_server` sorting under `mysql` on "sql"), + // so the ranked order stands on its own. + const browseGroup = (key: string) => + customResourceTypes.has(key) + ? 0 + : isSharedConnect(key) + ? 1 + : nativeLanguagesCategory.includes(key) + ? 2 + : 3 + let navItems = $derived( + (searching + ? (rankedConnectsManual ?? []) + : [...(rankedConnectsManual ?? [])].sort((a, b) => browseGroup(a.key) - browseGroup(b.key)) + ).map((x) => x.key) ) - let customKeys = $derived(manualOrderedKeys.filter((key) => customResourceTypes.has(key))) - let otherKeys = $derived(manualOrderedKeys.filter((key) => !customResourceTypes.has(key))) - - // Every row in the order it is rendered, so arrow keys walk the sections as one list. - // A provider appears in more than one, so rows are addressed by index, not by name. - let navItems = $derived([ - ...customKeys.map((key) => ({ key, oauth: false })), - ...(rankedConnects ?? []).map((x) => ({ key: x.key, oauth: true })), - ...otherKeys.map((key) => ({ key, oauth: false })) - ]) - // Both lists start undefined and render skeletons; "nothing found" only means something - // once they have landed. - let listsLoaded = $derived(rankedConnectsManual !== undefined && rankedConnects !== undefined) + // The list starts undefined and renders skeletons; "nothing found" only means something + // once it has landed. + let listsLoaded = $derived(rankedConnectsManual !== undefined && popularityReady) const rowDomId = (index: number) => `resource-type-row-${index}` - const oauthRowOffset = $derived(customKeys.length) - const otherRowOffset = $derived(customKeys.length + (rankedConnects?.length ?? 0)) - - // Sections are rendered in a fixed order, so the best match is not necessarily the first - // row: rank the rows against the query to find it. - function bestMatchIndex(): number { - let best = navItems.length > 0 ? 0 : -1 - let bestRank = Infinity - navItems.forEach((item, index) => { - const rank = resourceTypeMatchRank(item.key, resourceTypeDescriptions[item.key], filter) - if (rank < bestRank) { - bestRank = rank - best = index - } - }) - return best - } - const highlight = useListHighlight({ count: () => navItems.length, rowId: rowDomId, - // Sections are rendered in a fixed order, so the best match is not necessarily the - // first row; Enter should still take the top hit. - restingIndex: () => (searching ? bestMatchIndex() : -1), + restingIndex: () => (searching && navItems.length > 0 ? 0 : -1), onActivate: (index) => { - const item = navItems[index] - if (!item) return - item.oauth ? connectOauth(item.key) : selectFromOthers(item.key) + const key = navItems[index] + if (key) selectType(key) }, activateEnterFrom: [SEARCH_INPUT_ID] }) @@ -1250,20 +1283,28 @@ {#if !express} ({ - key - })) - : undefined} - bind:filteredItems={filteredConnects} - f={(x) => resourceTypeSearchText(x.key, resourceTypeDescriptions[x.key])} - /> - resourceTypeSearchText(x.key, resourceTypeDescriptions[x.key])} /> + + {#snippet wizardSteps()} + {#if !native && methodStepShown} +
+ goToStep(e.detail.index)} + /> +
+ {/if} + {/snippet} {#if step == 1} highlight.hovered(index)} - onClick={() => (oauth ? connectOauth(key) : selectFromOthers(key))} + onClick={() => selectType(key)} /> {/snippet} @@ -1329,70 +1374,21 @@ {:else} - -
- {#if customKeys.length > 0} -
- {@render sectionHeading('Custom resource types', customKeys.length)} -
- {#each customKeys as key, i} - {@render resourceButton(key, i, false)} - {/each} -
-
- {/if} + {#if !searching && connectsManual && connectsManual?.length < 10} +
+ Resource types have not been synced with the hub +
+ {/if} - {#if !searching || (rankedConnects?.length ?? 0) > 0} -
- {@render sectionHeading( - 'Instance-configured OAuth APIs', - rankedConnects?.length ?? 0 - )} -
- {#if rankedConnects} - {#each rankedConnects as { key }, i} - {@render resourceButton(key, oauthRowOffset + i, true)} - {/each} - {:else} - {#each new Array(3) as _} - - {/each} - {/if} -
- {#if !searching && connects && connects.filter(isSharedConnect).length == 0} -
No OAuth APIs have been set up on this instance. To add OAuth APIs, first sync - the resource types with the hub, then add OAuth configuration. See documentation -
- {/if} -
- {/if} - - {#if !searching || otherKeys.length > 0} -
- {@render sectionHeading('Others', otherKeys.length)} - - {#if !searching && connectsManual && connectsManual?.length < 10} -
- Resource types have not been synced with the hub -
- {/if} - -
- {#if rankedConnectsManual} - {#each otherKeys as key, i} - {@render resourceButton(key, otherRowOffset + i, false)} - {/each} - {:else} - {#each new Array(9) as _} - - {/each} - {/if} -
-
+
+ {#if listsLoaded} + {#each navItems as key, i} + {@render resourceButton(key, i)} + {/each} + {:else} + {#each new Array(9) as _} + + {/each} {/if}
{/if} @@ -1408,7 +1404,30 @@ />
- {:else if step == 2 && manual} + {:else if step == 2} + {@render wizardSteps()} +
+

How do you want to connect?

+ {#each methodOptions as opt (opt.method)} + {@const copy = methodCopy(opt.method, opt.disabled)} + {#snippet methodBadge()} + {copy.grant} + {#if opt.disabled} + Instance setup needed + {/if} + {/snippet} + selectMethod(opt.method)} + disabled={opt.disabled} + badge={copy.grant || opt.disabled ? methodBadge : undefined} + /> + {/each} +
+ {:else if step == 3 && manual} + {@render wizardSteps()}
{#if !emptyString(resourceTypeInfo?.description)} @@ -1418,7 +1437,7 @@ @@ -1488,14 +1507,6 @@
{/if} - {#if registryCcCapable()} - - {/if} {#if resourceTypeAlternative} - - {#if useClientCredentials && !useSharedInstanceCreds} - - - - {#if ccInstanceMeta} - - {:else} - - {/if} - - {/if} - - {/if} - - {#if registryEntry()?.user_scopes && !useClientCredentials} -
-

Connect as

-
- selectUserToken(false)} - /> - selectUserToken(true)} - /> -
-
+ {/if}
@@ -1705,13 +1626,15 @@
{/if} - {:else if step == 3 && !manual && !express} + {:else if step == 4 && !manual && !express} + {@render wizardSteps()} {#if useClientCredentials} Connecting with client credentials... {:else} Finish connection in popup window {/if} {:else} + {@render wizardSteps()}