| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import type {InitialParamKeys} from './platform'; |
| 9 | |
| 10 | import {logger} from './logger'; |
| 11 | |
| 12 | const INITIAL_PARAMS_LOCAL_STORAGE_KEY = 'ISLInitialParams'; |
| 13 | |
| 14 | declare global { |
| 15 | interface Window { |
| 16 | relativeDateNowOverride?: number; |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Extract parameters from URL, then remove from URL to be cleaner (and hide sensitive tokens) |
| 22 | */ |
| 23 | export function computeInitialParams(isBrowserPlatform: boolean): Map<InitialParamKeys, string> { |
| 24 | let initialParams: Map<InitialParamKeys, string> | undefined; |
| 25 | if (typeof window === 'undefined') { |
| 26 | return new Map(); |
| 27 | } |
| 28 | if (window.location.search) { |
| 29 | initialParams = new Map([...new URLSearchParams(window.location.search).entries()]); |
| 30 | logger.log('Loaded initial params from URL: ', initialParams); |
| 31 | if (isBrowserPlatform) { |
| 32 | // Save params to local storage so reloading the page keeps the same URL parameters |
| 33 | // Note: this assumes if search parameters are provided, ALL relevant search parameters are provided at the same time. |
| 34 | // This way initial parameters stored in local storage is always consistent. |
| 35 | try { |
| 36 | localStorage.setItem( |
| 37 | INITIAL_PARAMS_LOCAL_STORAGE_KEY, |
| 38 | JSON.stringify([...initialParams.entries()].filter(([k]) => k !== 'sessionId')), |
| 39 | ); |
| 40 | } catch (error) { |
| 41 | logger.log('Failed to save initial params to local storage', error); |
| 42 | } |
| 43 | window.history.replaceState({}, document.title, window.location.pathname); |
| 44 | logger.log('Saved initial params to local storage'); |
| 45 | } |
| 46 | } |
| 47 | // if parameters not passed in the URL, load previously seen values from localStorage. |
| 48 | if (!initialParams) { |
| 49 | try { |
| 50 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 51 | initialParams = new Map(JSON.parse(localStorage.getItem(INITIAL_PARAMS_LOCAL_STORAGE_KEY)!)); |
| 52 | logger.log('Loaded initial params from local storage: ', initialParams); |
| 53 | } catch (error) { |
| 54 | logger.log('Failed to load initial params from local storage', error); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // relative date's "now" override is stored separate in window for easier access |
| 59 | const nowOverride = initialParams?.get('now'); |
| 60 | if (nowOverride) { |
| 61 | try { |
| 62 | window.relativeDateNowOverride = parseInt(nowOverride); |
| 63 | } catch (error) { |
| 64 | logger.error('relative date "now" override in the wrong format', error); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | return initialParams ?? new Map(); |
| 69 | } |
| 70 | |