import { getUrlOrigin } from '@osd/std' ; import { resolve } from 'url' ; import { IBasePath } from '../../http' ; import { App , ParsedAppUrl } from '../types' ; /**
 * Parse given URL and return the associated app id and path if any app matches, or undefined if none do.
 * Input can either be:
 *
 * - an absolute path containing the basePath,
 *   e.g `/base-path/app/my-app/some-path`
 *
 * - an absolute URL matching the `origin` of the OpenSearch Dashboards instance (as seen by the browser),
 *   e.g `https://opensearch-dashboards:8080/base-path/app/my-app/some-path`
 *
 * - a path relative to the provided `currentUrl`.
 *   e.g with `currentUrl` being `https://opensearch-dashboards:8080/base-path/app/current-app/some-path`
 *   `../other-app/other-path` will be converted to `/base-path/app/other-app/other-path`
 */ export const parseAppUrl = ( url , basePath , apps , currentUrl = window . location . href ) : ParsedAppUrl | undefined => { const currentOrigin = getUrlOrigin ( currentUrl ) ; if ( ! currentOrigin ) { throw new Error ( 'when manually provided, currentUrl must be valid url with an origin' ) ; } const currentPath = currentUrl . substring ( currentOrigin . length ) ; if ( url . startsWith ( currentOrigin ) ) { url = url . substring ( currentOrigin . length ) ; } if ( ! url . startsWith ( '/' ) ) { url = resolve ( currentPath , url ) ; } const basePathValue = basePath . get ( ) ; if ( basePathValue && ! url . startsWith ( basePathValue ) ) { return undefined ; } url = basePath . remove ( url ) ; if ( ! url . startsWith ( '/' ) ) { return undefined ; } for ( const app of apps . values ( ) ) { const appPath = app . appRoute || `/app/${ app . id }` ; if ( url . startsWith ( appPath ) ) { const path = url . substr ( appPath . length ) ; return { app : app . id , path : path . length ? path : undefined , } ; } } } ;