### Quick Start: Background Authorization and Token Exchange Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/oidc-client/README.md A minimal example demonstrating background authorization, token exchange using the authorization code, and retrieving user information. Includes cleanup steps for logout and token revocation. ```javascript import { oidc } from '@forgerock/oidc-client'; // Initialize the client const oidcClient = await oidc({ config }); // Start authorization in the background const authResponse = await oidcClient.authorize.background(); // Get tokens const tokens = await oidcClient.token.exchange(authResponse.code, authResponse.state); // Get user information const user = await oidcClient.user.info(); // Clean up: logout and revoke tokens await oidcClient.user.logout(); ``` -------------------------------- ### Install Device Client Package Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Install the necessary dependencies for using the deviceClient. ```bash npm install @forgerock/device-client --save ``` -------------------------------- ### Install and Initialize DaVinci and FIDO Clients Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/src/lib/fido/README.md Install the davinci-client package and import/initialize the davinci and fido clients for use. ```bash npm install @forgerock/davinci-client --save ``` ```typescript import { davinci, fido } from '@forgerock/davinci-client'; const davinciClient = await davinci({ config }); const fidoApi = fido(); ``` -------------------------------- ### Start and Next Journey (Legacy SDK) Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Demonstrates the legacy approach to starting a journey and iterating through steps using FRAuth.start() and FRAuth.next(). ```typescript import { FRAuth, StepType } from '@forgerock/javascript-sdk'; // Start a journey let step = await FRAuth.start({ tree: 'Login' }); while (step.type === StepType.Step) { // ... handle callbacks ... step = await FRAuth.next(step, { tree: 'Login' }); } if (step.type === StepType.LoginSuccess) { const token = step.getSessionToken(); } ``` -------------------------------- ### start() Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Starts the data collection process for Ping Protect. Recommended to call as early as possible in the application lifecycle. ```APIDOC ## start() ### Description Initiates the data collection and profiling process for Ping Protect. ### Method `protectApi.start()` ### Returns An object that may contain an 'error' property if initialization fails. ### Example ```javascript const result = await protectApi.start(); if (result?.error) { console.error(`Error initializing Protect: ${result.error}`); } ``` ``` -------------------------------- ### Install OIDC Client Package Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/oidc-client/README.md Install the OIDC client library using your preferred package manager. ```bash pnpm add @forgerock/oidc-client # or npm install @forgerock/oidc-client # or yarn add @forgerock/oidc-client ``` -------------------------------- ### Install @forgerock/journey-client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Install the journey client using your preferred package manager. ```bash pnpm add @forgerock/journey-client # or npm install @forgerock/journey-client # or yarn add @forgerock/journey-client ``` -------------------------------- ### Install OIDC SDK Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/oidc/README.md Install the OIDC module using npm. ```bash npm install @forgerock/sdk-oidc ``` -------------------------------- ### Install SDK Types Package Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-types/README.md Install the SDK types package using npm, pnpm, or yarn. ```bash npm install @forgerock/sdk-types # or pnpm add @forgerock/sdk-types # or yarn add @forgerock/sdk-types ``` -------------------------------- ### Install SDK Logger Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/logger/README.md Install the SDK logger package using npm. ```bash npm install @forgerock/sdk-logger ``` -------------------------------- ### Install and Import DaVinci Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Instructions on how to install the DaVinci Client via npm and import the `davinci` module into your project. ```APIDOC ## Install ```sh npm install @forgerock/davinci-client ``` ## Import ```ts import { davinci } from '@forgerock/davinci-client'; ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/e2e/mock-api-v2/README.md Installs project dependencies using pnpm. ```sh pnpm install ``` -------------------------------- ### Quick Start: Authenticate User with Journey Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Initialize the client with a wellknown discovery URL and then start an authentication journey. Handle callbacks in a loop until the journey completes with success or failure. ```typescript import { journey, callbackType } from '@forgerock/journey-client'; async function authenticateUser() { // Initialize the client with wellknown discovery try { const client = await journey({ config: { serverConfig: { wellknown: 'https://am.example.com/am/oauth2/alpha/.well-known/openid-configuration', }, }, }); // Start the authentication journey let step = await client.start({ journey: 'Login' }); // Handle callbacks in a loop until success or failure while (step?.type === 'Step') { const nameCallbacks = step.getCallbacksOfType(callbackType.NameCallback); for (const cb of nameCallbacks) { cb.setName('demo'); } const passwordCallbacks = step.getCallbacksOfType(callbackType.PasswordCallback); for (const cb of passwordCallbacks) { cb.setPassword('password'); } step = await client.next(step); } // Check the final result if (step?.type === 'LoginSuccess') { console.log('Login successful!', step.getSessionToken()); } else if (step?.type === 'LoginFailure') { console.error('Login failed:', step.payload.message); } } catch (error) { console.error('Failed to initialize client:', error); } } ``` -------------------------------- ### Run Server Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/e2e/mock-api-v2/README.md Starts the mock API server on port 9443. ```sh pnpm serve ``` -------------------------------- ### Install SDK Request Middleware Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/sdk-request-middleware/README.md Install the SDK request middleware package using npm. ```bash npm install @forgerock/sdk-request-middleware ``` -------------------------------- ### Install ForgeRock Storage Package Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/storage/README.md Install the storage package using npm or yarn. ```bash npm install @forgerock/storage # or yarn add @forgerock/storage ``` -------------------------------- ### PUSH Management Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Example of retrieving and deleting PUSH devices using the deviceClient API. Ensure query parameters are correctly defined. ```typescript const pushQuery: PushDeviceQuery = { /* your query parameters */ }; const getResponse = await apiClient.push.get(pushQuery); console.log('Push Devices:', getResponse); const deletePushQuery: DeleteDeviceQuery = { /* your delete query */ }; const deleteResponse = await apiClient.push.delete(deletePushQuery); console.log('Deleted Push Device:', deleteResponse); ``` -------------------------------- ### Start Flow Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Initiates a new authentication flow with optional query parameters. ```APIDOC ## start ### Description Initiates a new authentication flow with optional query parameters. ### Signature ```typescript start: (options?: StartOptions | undefined) => Promise; ``` ``` -------------------------------- ### Install DaVinci Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Install the DaVinci Client package using npm. This is the first step to integrate DaVinci flows into your application. ```sh npm install @forgerock/davinci-client ``` -------------------------------- ### Install Ping Protect and Journey Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Install the necessary modules for integrating Ping Protect with a client application using npm or pnpm. ```bash npm install @forgerock/journey-client @forgerock/protect ``` ```bash pnpm install @forgerock/journey-client @forgerock/protect ``` -------------------------------- ### StartParam Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/api-report/journey-client.types.api.md Parameters required to start a user journey. ```APIDOC ## Interface: StartParam ### Description Defines the parameters necessary to initiate a user journey. ### Properties - **journey**: string - The ID of the journey to start. - **query?**: Record - Optional query parameters to include when starting the journey. ``` -------------------------------- ### Start a DaVinci Flow Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Explains how to initiate a DaVinci flow by calling the `start` method on the configured DaVinci Client. It also details the structure of the returned `node` object and how to handle different node statuses. ```APIDOC ## Start Flow ```ts let node = await davinciClient.start(); ``` ## Node Object Structure ```ts interface NodeState { cache: { key: string; }; client: { action: string; description?: string; name?: string; collectors?: (SingleValueCollector | ActionCollector)[]; status: string; }; error: null | { code: string | number; message?: string; status: string; }; httpStatus: number; server: { id?: string; interactionId?: string; interactionToken?: string; eventName?: string; session?: string; status: string; }; status: string; } ``` ## Handling Node Status ```ts let node = await davinciClient.start(); switch (node.status) { case 'continue': // Handle continue node break; case 'success': // Handle success node break; case 'error': // Handle error node break; default: // Handle failure type // Handle failure node break; } ``` ``` -------------------------------- ### OATH Management Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Example of retrieving and deleting OATH devices using the deviceClient API. Ensure query parameters are correctly defined. ```typescript const oathQuery: RetrieveOathQuery = { /* your query parameters */ }; const getResponse = await apiClient.oath.get(oathQuery); console.log('Oath Devices:', getResponse); const deleteOathQuery: RetrieveOathQuery & { device: OathDevice } = { /* your delete query */ }; const deleteResponse = await apiClient.oath.delete(deleteOathQuery); console.log('Deleted Oath Device:', deleteResponse); ``` -------------------------------- ### Start a Specific Flow Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Starts a specific authentication flow identified by an action. ```APIDOC ## flow ### Description Starts a specific authentication flow identified by an action. ### Signature ```typescript flow: (action: DaVinciAction) => InitFlow; ``` ``` -------------------------------- ### Start and Next Journey (New SDK) Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Illustrates the new method for initiating a journey and advancing through its steps using the journeyClient.start() and journeyClient.next(). ```typescript import { journey } from '@forgerock/journey-client'; const journeyClient = await journey({ config: { serverConfig: { wellknown: 'https://am.example.com/am/oauth2/alpha/.well-known/openid-configuration', }, }, }); let result = await journeyClient.start({ journey: 'Login' }); while (result.type === 'Step') { // ... handle callbacks ... result = await journeyClient.next(result); } if ('error' in result) { console.error('Journey error:', result); } else if (result.type === 'LoginSuccess') { const token = result.getSessionToken(); } ``` -------------------------------- ### Start a DaVinci Flow Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Initiate a DaVinci flow by calling the `start` method on the configured DaVinci client. This returns an initial node object representing the flow's current state. ```ts let node = await davinciClient.start(); ``` -------------------------------- ### Login Flow: Legacy vs. New SDK Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/MIGRATION.md Compares the legacy FRAuth.start() flow with the new journey client's start() method for initiating authentication. ```typescript import { FRAuth, StepType } from '@forgerock/javascript-sdk'; Config.set({ serverConfig: { baseUrl: 'https://am.example.com/am' }, realmPath: 'alpha', tree: 'Login', }); let step = await FRAuth.start(); while (step.type === StepType.Step) { // ... handle callbacks ... step = await FRAuth.next(step); } if (step.type === StepType.LoginSuccess) { console.log('Session token:', step.getSessionToken()); } ``` ```typescript import { journey } from '@forgerock/journey-client'; const journeyClient = await journey({ config: { serverConfig: { wellknown: 'https://am.example.com/am/oauth2/alpha/.well-known/openid-configuration', }, }, }); let result = await journeyClient.start({ journey: 'Login' }); while (result.type === 'Step') { // ... handle callbacks ... result = await journeyClient.next(result); } if ('error' in result) { console.error('Journey error:', result); } else if (result.type === 'LoginSuccess') { console.log('Session token:', result.getSessionToken()); } ``` -------------------------------- ### Start and Next Journey Operations Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Illustrates the difference in starting and progressing through a journey between the legacy `FRAuth` and the new `journeyClient`. ```APIDOC ## Before/After: Start and Next ### Legacy SDK ```typescript import { FRAuth, StepType } from '@forgerock/javascript-sdk'; // Start a journey let step = await FRAuth.start({ tree: 'Login' }); while (step.type === StepType.Step) { // ... handle callbacks ... step = await FRAuth.next(step, { tree: 'Login' }); } if (step.type === StepType.LoginSuccess) { const token = step.getSessionToken(); } ``` ### New SDK (journeyClient) ```typescript import { journey } from '@forgerock/journey-client'; const journeyClient = await journey({ config: { serverConfig: { wellknown: 'https://am.example.com/am/oauth2/alpha/.well-known/openid-configuration', }, }, }); let result = await journeyClient.start({ journey: 'Login' }); while (result.type === 'Step') { // ... handle callbacks ... result = await journeyClient.next(result); } if ('error' in result) { console.error('Journey error:', result); } else if (result.type === 'LoginSuccess') { const token = result.getSessionToken(); } ``` ``` -------------------------------- ### Protect Module Initialization and Usage Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Demonstrates how to initialize the Ping Protect module and use its core methods for starting risk evaluations and retrieving collected data. ```APIDOC ## Protect Module Initialization ### Description Initializes the Ping Protect module with configuration options and returns an API object for interacting with Protect features. ### Method `protect(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - Configuration options for Protect. - **envId** (string) - Required - The environment ID for PingOne Protect. ### Request Example ```javascript import { protect } from '@forgerock/protect'; const protectApi = protect({ envId: 'YOUR_ENV_ID' }); ``` ## Start Risk Evaluation ### Description Starts the risk evaluation process, initiating data collection for Ping Protect. This method should be called early in the application startup or when a `PingOneProtectInitializeCallback` is received. ### Method `start()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript await protectApi.start(); ``` ### Response #### Success Response Returns an object indicating success or an error. #### Response Example ```json { "success": true } ``` ## Get Collected Data ### Description Retrieves the data collected by the Ping Protect module, which is then packaged for server-side evaluation. This method is typically called when a `PingOneProtectEvaluationCallback` is encountered. ### Method `getData()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript const data = await protectApi.getData(); ``` ### Response #### Success Response Returns the collected data, typically as a string or an object containing data and potential errors. #### Response Example ```json { "collectedData": "..." } ``` ## Pause Behavioral Data Collection ### Description Pauses the collection of behavioral data by the Ping Protect module. ### Method `pauseBehavioralData()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript protectApi.pauseBehavioralData(); ``` ## Resume Behavioral Data Collection ### Description Resumes the collection of behavioral data by the Ping Protect module. ### Method `resumeBehavioralData()` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript protectApi.resumeBehavioralData(); ``` ``` -------------------------------- ### Create and Use localStorage Storage API Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/storage/README.md Initialize a storage API for localStorage and demonstrate setting, getting, and removing tokens. ```typescript import { createStorage, type CustomStorageConfig } from '@forgerock/storage'; // Example using localStorage const storageApi = createStorage({ type: 'localStorage', name: 'MyStorage', prefix: 'myPrefix', }); async function manageTokens() { // Set a token await storageApi.set('someTokenValue'); // Get a token const token = await storageApi.get(); console.log(token); // Output: 'someTokenValue' // Remove a token await storageApi.remove(); // Verify removal const removedToken = await storageApi.get(); console.log(removedToken); // Output: null } ``` -------------------------------- ### Get Tokens: Legacy vs. New SDK Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/MIGRATION.md Illustrates how to obtain tokens, including options for forced renewal, using both SDK versions. ```typescript TokenManager.getTokens({ forceRenew: true }) ``` ```typescript await oidcClient.token.get({ forceRenew: true, backgroundRenew: true }) ``` -------------------------------- ### New Callback Handling Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Example of callback handling with the new SDK, using the callbackType object and a different step type. ```typescript import { callbackType } from '@forgerock/journey-client' import type { NameCallback } from '@forgerock/journey-client/types' if (result.type === 'Step') { const nameCb = result.getCallbackOfType(callbackType.NameCallback); nameCb.setName('demo'); } ``` -------------------------------- ### Start Authentication Journey Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Initiate a new authentication journey by providing the journey or tree name. Optional query parameters can be included. ```typescript const step = await client.start({ journey: 'Login', // Required: Journey/tree name query: { locale: 'en' }, // Optional: Query parameters }); ``` -------------------------------- ### FIDO Registration Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/src/lib/fido/README.md Handles FidoRegistrationCollector by registering a public key credential using the fido API and updating the collector. ```typescript if (collector.type === 'FidoRegistrationCollector') { const credentialOptions = collector.output.config.publicKeyCredentialCreationOptions; const publicKeyCredential = await fidoApi.register(credentialOptions); if ('error' in publicKeyCredential) { // Handle error } else { // Update the FidoRegistrationCollector with the credential const updater = davinciClient.update(collector); updater(publicKeyCredential); } } ``` -------------------------------- ### Get Current User Info: Legacy vs. New SDK Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/MIGRATION.md Demonstrates how to retrieve current user information using both the legacy UserManager and the new oidcClient. ```typescript UserManager.getCurrentUser() ``` ```typescript await oidcClient.user.info() ``` -------------------------------- ### client.start(options?) Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Initiates a new authentication journey on the server. This method begins the authentication flow and returns the first step of the journey. ```APIDOC ## client.start(options?) ### Description Initiates a new authentication journey. This method starts the authentication process and returns the initial step of the journey. ### Parameters - **options** (object) - Optional - Options for starting the journey. - **journey** (string) - Required - The name of the journey or authentication tree to start. - **query** (object) - Optional - Query parameters to include in the request. ### Returns `Promise` - A promise that resolves to the first step of the journey, a login success object, a login failure object, or undefined. ### Example ```typescript // Assuming 'client' is an initialized JourneyClient instance try { const step = await client.start({ journey: 'Login', // Specify the journey name query: { locale: 'en' }, // Optional query parameters }); if (step?.type === 'Step') { console.log('Started journey, received first step.'); // Process callbacks in the step } else if (step?.type === 'LoginSuccess') { console.log('Login successful immediately:', step.getSessionToken()); } else if (step?.type === 'LoginFailure') { console.error('Login failed immediately:', step.payload.message); } } catch (error) { console.error('Failed to start journey:', error); } ``` ``` -------------------------------- ### Get Installed Fonts Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/api-report/journey-client.device.api.md Retrieves a string listing the fonts installed on the user's system. This can be used for fingerprinting. ```typescript device.getInstalledFonts() ``` -------------------------------- ### Legacy Callback Handling Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Example of how to handle callbacks using the legacy SDK's CallbackType enum and FRStep. ```typescript import { CallbackType, FRStep } from '@forgerock/javascript-sdk' import type { FRCallback } from '@forgerock/javascript-sdk' if (step.type === 'Step') { const nameCb = step.getCallbackOfType(CallbackType.NameCallback); nameCb.setName('demo'); } ``` -------------------------------- ### Get Browser Plugins Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/api-report/journey-client.device.api.md Retrieves a string representing the names of installed browser plugins. This can be useful for fingerprinting or feature detection. ```typescript device.getBrowserPluginsNames() ``` -------------------------------- ### Get Device Profile Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Instantiate Device with optional configuration and call getProfile with location and metadata to retrieve device profile data. ```javascript new FRDevice(config?).getProfile({ location, metadata }) ``` ```javascript new Device(config?).getProfile({ location, metadata }) ``` -------------------------------- ### Get Davinci Server Information Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Retrieves the current status and details of the Davinci server interaction. The returned object varies based on the server status (start, continue, error, success, failure). ```typescript getServer: () => { status: "start"; } | { _links?: Links; id?: string; interactionId?: string; interactionToken?: string; href?: string; eventName?: string; status: "continue"; } | { _links?: Links; eventName?: string; id?: string; interactionId?: string; interactionToken?: string; status: "error"; } | { _links?: Links; eventName?: string; id?: string; interactionId?: string; interactionToken?: string; href?: string; session?: string; status: "success"; } | { _links?: Links; eventName?: string; href?: string; id?: string; interactionId?: string; interactionToken?: string; status: "failure"; } | null; ``` -------------------------------- ### Get Davinci Client Information Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Retrieves the current status and details of the Davinci client. The returned object varies based on the client's status (start, continue, error, success, failure). ```typescript getClient: () => { status: "start"; } | { action: string; collectors: Collectors[]; description?: string; name?: string; status: "continue"; } | { action: string; collectors: Collectors[]; description?: string; name?: string; status: "error"; } | { authorization?: { code?: string; state?: string; }; status: "success"; } | { status: "failure"; } | null; ``` -------------------------------- ### Render Choice Callback Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/e2e/journey-app/components/README.md Demonstrates how to use a specific component, `choiceComponent`, to render a choice callback. Ensure the container element and callback object are properly initialized before use. ```typescript import { choiceComponent } from './components/index.js'; // Render a choice callback choiceComponent(containerDiv, choiceCallback, 0); ``` -------------------------------- ### Submit Step and Get Next Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Use `client.next` to submit the current step and retrieve the subsequent one. Optional query parameters can be provided. ```typescript const nextStep = await client.next(step, { query: { noSession: 'true' }, // Optional: Query parameters }); ``` -------------------------------- ### Action-Based Middleware Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-effects/sdk-request-middleware/README.md Illustrates how to create middleware that conditionally modifies requests based on action types and adds authorization tokens from action payloads. ```typescript import { initQuery } from '@forgerock/sdk-request-middleware'; const authMiddleware = [ (req, action, next) => { // Apply different logic based on action type switch (action.type) { case 'DAVINCI_START': req.url.searchParams.set(...params); break; case 'DAVINCI_NEXT' req.url.searchParams.set(...params); break; } // Add authorization token from action payload if available if (action.payload?.token) { req.headers.set('Authorization', `Bearer ${action.payload.token}`); } next(); }, ]; // Use the middleware with specific action type const response = await initQuery(fetchArgs, 'start') .applyMiddleware(authMiddleware) .applyQuery(queryCallback); ``` -------------------------------- ### Create and Configure DaVinci Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Demonstrates how to create and configure a DaVinci Client instance with essential properties like `clientId` and `wellknown`. Includes examples for basic and multiple client configurations, along with the full configuration interface. ```APIDOC ## Basic Configuration ```ts import { davinci } from '@forgerock/davinci'; const davinciClient = await davinci({ config: { clientId: 'YOUR_CLIENT_ID', serverConfig: { wellknown: 'YOUR_WELLKNOWN_URL' } } }); ``` ## Multiple Clients ```ts import { davinci } from '@forgerock/davinci'; const firstDavinciClient = await davinci(/** config 1 **/); const secondDavinciClient = await davinci(/** config 2 **/ ``` ## Full Configuration Interface ```ts interface DaVinciConfig { clientId: string; // required responseType?: string; // optional; default value: 'code' scope?: string; // optional; default value: 'openid' serverConfig: { timeout?: number; // optional; default value: ?? (NOT IMPLEMENTED) wellknown: string; // required }; } ``` ``` -------------------------------- ### Initialize Device Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.types.api.md Instantiate the device client with configuration options. This is the entry point for all device-related operations. ```typescript import { ConfigOptions } from '@forgerock/javascript-sdk'; const config: ConfigOptions = { /* ... your configuration ... */ }; const deviceClient = deviceClient(config); ``` -------------------------------- ### Protect Initialization (Recommended) Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Initialize the Ping Protect module with essential configuration options. It's recommended to call this early in your application's startup process to maximize data collection. ```APIDOC ## protect() ### Description Initializes the Ping Protect module with configuration options. ### Method `protect(config)` ### Parameters #### Configuration Options - **envId** (string) - Required - The environment ID for Protect. - **behavioralDataCollection** (boolean) - Optional - Enables or disables behavioral data collection. - **universalDeviceIdentification** (boolean) - Optional - Enables or disables universal device identification. ### Returns An object containing methods for interacting with Protect. ### Example ```javascript import { protect } from '@forgerock/protect'; // Call early in your application startup const protectApi = protect({ envId: '12345' }); await protectApi.start(); ``` ``` -------------------------------- ### getServer Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Retrieves the current server status and associated data. The return type varies based on the status ('start', 'continue', 'error', 'success', 'failure'). ```APIDOC ## getServer ### Description Retrieves the current server status and associated data. The return type varies based on the status. ### Returns - **{ status: "start"; }** - Indicates the server is starting. - **{ _links?: Links; id?: string; interactionId?: string; interactionToken?: string; href?: string; eventName?: string; status: "continue"; }** - Indicates the server is continuing, providing links, IDs, tokens, href, and event name. - **{ _links?: Links; eventName?: string; id?: string; interactionId?: string; interactionToken?: string; status: "error"; }** - Indicates an error state, providing links, IDs, tokens, and event name. - **{ _links?: Links; eventName?: string; id?: string; interactionId?: string; interactionToken?: string; href?: string; session?: string; status: "success"; }** - Indicates a successful operation, providing links, IDs, tokens, href, event name, and session. - **{ _links?: Links; eventName?: string; href?: string; id?: string; interactionId?: string; interactionToken?: string; status: "failure"; }** - Indicates a failure state, providing links, IDs, tokens, href, and event name. - **null** - If no server information is available. ``` -------------------------------- ### TermsAndConditionsCallback Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/api-report/journey-client.api.md Represents a callback for displaying and accepting terms and conditions. It provides methods to get terms, version, creation date, and to set the acceptance status. ```APIDOC ## TermsAndConditionsCallback ### Description Handles the display and acceptance of terms and conditions. ### Methods - `getCreateDate(): Date | null` - Retrieves the creation date of the terms. - `getTerms(): string` - Retrieves the content of the terms and conditions. - `getVersion(): string` - Retrieves the version of the terms and conditions. - `setAccepted(accepted?: boolean): void` - Sets the acceptance status of the terms. ``` -------------------------------- ### Device Client Initialization Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.types.api.md Initializes the Device Client with configuration options. ```APIDOC ## deviceClient ### Description Initializes the Device Client with the provided configuration options. ### Parameters #### Path Parameters - **config** (ConfigOptions) - Required - Configuration options for the device client. ### Returns - DeviceClient - An instance of the Device Client. ``` -------------------------------- ### Handle Errors on Protect API `start` Method Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Check the result of the `protectApi.start()` call for an error object. This allows for custom error handling, such as returning a message to the user. ```javascript const result = await protectApi.start(); if (result?.error) { console.error(`Error initializing Protect: ${result.error}`); } ``` -------------------------------- ### Configure Device Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Initialize the deviceClient with configuration options including server URL and realm path. ```typescript import { deviceClient } from '@forgerock/device-client'; import type { ConfigOptions } from '@forgerock/device-client/types'; const config: ConfigOptions = { serverConfig: { baseUrl: 'https://api.example.com', }, realmPath: '/your-realm-path', }; const apiClient = deviceClient(config); ``` -------------------------------- ### Configure SDK: Legacy vs. New Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Compares the global configuration setup for the legacy SDK with the client-specific configuration in the new SDK. The new SDK uses a shared config object for multiple clients. ```typescript import { Config } from '@forgerock/javascript-sdk'; Config.set({ clientId: 'my-app', redirectUri: `${window.location.origin}/callback`, scope: 'openid profile', serverConfig: { baseUrl: 'https://am.example.com/am', timeout: 5000, }, realmPath: 'alpha', tree: 'Login', }); ``` ```typescript import { journey } from '@forgerock/journey-client'; import { oidc } from '@forgerock/oidc-client'; // Shared config — both clients can use the same base config const config = { serverConfig: { wellknown: 'https://am.example.com/am/oauth2/alpha/.well-known/openid-configuration', }, clientId: 'my-app', redirectUri: `${window.location.origin}/callback`, scope: 'openid profile', }; // Journey client accepts but ignores clientId, redirectUri, scope (warns in console) const journeyClient = await journey({ config }); // OIDC client requires clientId, redirectUri, scope const oidcClient = await oidc({ config }); ``` -------------------------------- ### Start a Davinci Flow Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.types.api.md Initiates a new Davinci flow, optionally with custom query parameters. This method returns the initial state of the flow, which could be a start, continue, success, or failure node. ```APIDOC ## start ### Description Starts a new Davinci flow. ### Parameters #### options - **options** (StartOptions) - Optional - Options to configure the start of the flow, including query parameters. ### Returns - **Promise** - A promise that resolves to the initial node state of the flow. ``` -------------------------------- ### Build Project Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/e2e/mock-api-v2/README.md Builds the project using pnpm. ```sh pnpm build ``` -------------------------------- ### Get All Collectors Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Retrieves a list of all available collectors. ```typescript getCollectors: () => Collectors[]; ``` -------------------------------- ### Add a Changeset Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/contributing_docs/releases.md Run this command to initiate the creation of a changeset. Follow the interactive prompts to define the type of release (e.g., patch, minor, major). ```bash pnpm changeset ``` -------------------------------- ### Get Error Collectors Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Retrieves a list of collectors that encountered errors. ```typescript getErrorCollectors: () => CollectorErrors[]; ``` -------------------------------- ### Build Journey Client Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Build the journey client package using the pnpm nx build command. ```bash pnpm nx build @forgerock/journey-client ``` -------------------------------- ### WebAuthn Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Provides methods to get, update, and delete WebAuthn devices. ```APIDOC ## WebAuthn Management ### Description Methods for managing WebAuthn devices, including retrieval, updates, and deletion. ### Methods - `get(query: WebAuthnQuery)`: Retrieves WebAuthn devices based on the provided query. - `update(query: WebAuthnQuery & { device: WebAuthnDevice })`: Updates an existing WebAuthn device. - `delete(query: WebAuthnQuery & { device: WebAuthnDevice | UpdatedWebAuthnDevice })`: Deletes a WebAuthn device. ``` -------------------------------- ### Push Device Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.api.md Provides methods to get and delete Push devices. ```APIDOC ## Push Device Management ### Description Methods for managing Push devices, including retrieving a list of registered Push devices and deleting a specific Push device. ### Methods #### Get Push Devices ##### Description Retrieves a list of registered Push devices for the authenticated user. ##### Method `get(query: PushDeviceQuery)` ##### Parameters - **query** (PushDeviceQuery) - An object containing query parameters for retrieving Push devices. ##### Returns - `Promise` - A promise that resolves to an array of PushDevice objects or an error object. #### Delete Push Device ##### Description Deletes a specific Push device for the authenticated user. ##### Method `delete(query: DeleteDeviceQuery)` ##### Parameters - **query** (DeleteDeviceQuery) - An object containing query parameters and the Push device details to delete. ##### Returns - `Promise` - A promise that resolves to null on success or an error object. ``` -------------------------------- ### Oath Device Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.api.md Provides methods to get and delete Oath devices. ```APIDOC ## Oath Device Management ### Description Methods for managing Oath devices, including retrieving a list of registered Oath devices and deleting a specific Oath device. ### Methods #### Get Oath Devices ##### Description Retrieves a list of registered Oath devices for the authenticated user. ##### Method `get(query: RetrieveOathQuery)` ##### Parameters - **query** (RetrieveOathQuery) - An object containing query parameters for retrieving Oath devices. ##### Returns - `Promise` - A promise that resolves to an array of OathDevice objects or an error object. #### Delete Oath Device ##### Description Deletes a specific Oath device for the authenticated user. ##### Method `delete(query: RetrieveOathQuery & { device: OathDevice })` ##### Parameters - **query** (RetrieveOathQuery & { device: OathDevice }) - An object containing query parameters and the OathDevice object to delete. ##### Returns - `Promise` - A promise that resolves to null on success or an error object. ``` -------------------------------- ### Build SDK Types Package Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/sdk-types/README.md Build the SDK types package using the nx build command. ```bash nx build sdk-types ``` -------------------------------- ### Device Profiling Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Provides methods to get, update, and delete device profiles. ```APIDOC ## Device Profiling Management ### Description Methods for managing device profiles, including retrieval, updates, and deletion. ### Methods - `get(query: GetProfileDevices)`: Retrieves device profiles based on the provided query. - `update(query: ProfileDevicesQuery)`: Updates an existing device profile. - `delete(query: ProfileDevicesQuery)`: Deletes a device profile. ``` -------------------------------- ### Bound Devices Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/README.md Provides methods to get, update, and delete bound devices. ```APIDOC ## Bound Devices Management ### Description Methods for managing bound devices, including retrieval, updates, and deletion. ### Methods - `get(query: GetBoundDevicesQuery)`: Retrieves bound devices based on the provided query. - `update(query: BoundDeviceQuery)`: Updates an existing bound device. - `delete(query: BoundDeviceQuery)`: Deletes a bound device. ``` -------------------------------- ### Profile Device Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.api.md Provides methods to get, update, and delete profile devices. ```APIDOC ## Profile Device Management ### Description Methods for managing profile devices, including retrieving a list of profile devices, updating an existing profile device, and deleting a specific profile device. ### Methods #### Get Profile Devices ##### Description Retrieves a list of profile devices associated with the user. ##### Method `get(query: GetProfileDevices)` ##### Parameters - **query** (GetProfileDevices) - An object containing query parameters for retrieving profile devices. ##### Returns - `Promise` - A promise that resolves to an array of ProfileDevice objects or an error object. #### Update Profile Device ##### Description Updates an existing profile device. ##### Method `update(query: ProfileDevicesQuery)` ##### Parameters - **query** (ProfileDevicesQuery) - An object containing query parameters and the updated profile device details. ##### Returns - `Promise` - A promise that resolves to the updated ProfileDevice object or an error object. #### Delete Profile Device ##### Description Deletes a specific profile device. ##### Method `delete(query: ProfileDevicesQuery)` ##### Parameters - **query** (ProfileDevicesQuery) - An object containing query parameters and the profile device details to delete. ##### Returns - `Promise` - A promise that resolves to null on success or an error object. ``` -------------------------------- ### Bound Device Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.api.md Provides methods to get, delete, and update bound devices. ```APIDOC ## Bound Device Management ### Description Methods for managing bound devices, including retrieving a list of bound devices, deleting a specific bound device, and updating an existing bound device. ### Methods #### Get Bound Devices ##### Description Retrieves a list of bound devices associated with the user. ##### Method `get(query: GetBoundDevicesQuery)` ##### Parameters - **query** (GetBoundDevicesQuery) - An object containing query parameters for retrieving bound devices. ##### Returns - `Promise` - A promise that resolves to an array of Device objects or an error object. #### Delete Bound Device ##### Description Deletes a specific bound device. ##### Method `delete(query: BoundDeviceQuery)` ##### Parameters - **query** (BoundDeviceQuery) - An object containing query parameters and the bound device details to delete. ##### Returns - `Promise` - A promise that resolves to null on success or an error object. #### Update Bound Device ##### Description Updates an existing bound device. ##### Method `update(query: BoundDeviceQuery)` ##### Parameters - **query** (BoundDeviceQuery) - An object containing query parameters and the updated bound device details. ##### Returns - `Promise` - A promise that resolves to the updated Device object or an error object. ``` -------------------------------- ### Initialize Ping Protect SDK with Server Configuration Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/protect/README.md Initialize the Protect module and begin collecting data when a ProtectCollector is received from the server. Optionally uses configuration options from the flow. ```javascript const collectors = davinciClient.getCollectors(); collectors.forEach((collector) => { if (collector.type === 'ProtectCollector') { // Optionally use configuration options from the flow to initialize the protect module const config = collector.output.config; // Initialize the Protect module and begin collecting data const protectApi = protect({ envId: '12345', behavioralDataCollection: config.behavioralDataCollection, universalDeviceIdentification: config.universalDeviceIdentification, }); await protectApi.start(); } ... }); ``` -------------------------------- ### WebAuthn Device Management Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/device-client/api-report/device-client.api.md Provides methods to get, update, and delete WebAuthn devices. ```APIDOC ## WebAuthn Device Management ### Description Methods for managing WebAuthn devices, including retrieving, updating, and deleting registered WebAuthn devices. ### Methods #### Get WebAuthn Devices ##### Description Retrieves a list of registered WebAuthn devices for the authenticated user. ##### Method `get(query: WebAuthnQuery)` ##### Parameters - **query** (WebAuthnQuery) - An object containing query parameters for retrieving WebAuthn devices. ##### Returns - `Promise` - A promise that resolves to an array of WebAuthnDevice objects or an error object. #### Update WebAuthn Device ##### Description Updates an existing WebAuthn device. ##### Method `update(query: WebAuthnQuery & { device: WebAuthnDevice })` ##### Parameters - **query** (WebAuthnQuery & { device: WebAuthnDevice }) - An object containing query parameters and the updated WebAuthnDevice object. ##### Returns - `Promise` - A promise that resolves to the updated WebAuthnDevice object or an error object. #### Delete WebAuthn Device ##### Description Deletes a specific WebAuthn device. ##### Method `delete(query: WebAuthnQuery & { device: WebAuthnDevice | UpdatedWebAuthnDevice })` ##### Parameters - **query** (WebAuthnQuery & { device: WebAuthnDevice | UpdatedWebAuthnDevice }) - An object containing query parameters and the WebAuthn device to delete. ##### Returns - `Promise` - A promise that resolves to null on success or an error object. ``` -------------------------------- ### Redirect and Resume Operations Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md Demonstrates how to initiate a redirect for external authentication and resume the journey upon callback using both legacy and new SDKs. ```APIDOC ## Before/After: Redirect and Resume ### Legacy SDK ```typescript import { FRAuth } from '@forgerock/javascript-sdk'; // Redirect to AM for social login / external IdP FRAuth.redirect(step); // On callback page, resume the journey const result = await FRAuth.resume(window.location.href); ``` ### New SDK (journeyClient) ```typescript // Redirect to AM for social login / external IdP await journeyClient.redirect(step); // On callback page, resume the journey const result = await journeyClient.resume(window.location.href); ``` ``` -------------------------------- ### Render SubmitCollector Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Maps over collectors to identify and render SubmitCollectors, which are used for form submission. ```javascript const collectors = davinci.collectors(); collectors.map((collector) => { if (collector.type === 'SubmitCollector') { renderSubmitCollector( collector, // This is the only argument you will need to pass ); } }); ``` -------------------------------- ### Get WebAuthn Step Type Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/interface_mapping.md The `getWebAuthnStepType` method now accepts a `JourneyStep` type instead of `FRStep`. ```typescript WebAuthn.getWebAuthnStepType(step: JourneyStep): WebAuthnStepType ``` -------------------------------- ### client.next(step, options?) Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/journey-client/README.md Submits the current step in a journey and retrieves the next step. Options can include query parameters. ```APIDOC ## client.next(step, options?) ### Description Submits the current step and retrieves the next one. ### Parameters #### Path Parameters - **step** (object) - Required - The current journey step. - **options** (object) - Optional - Configuration options, potentially including query parameters. ### Request Example ```typescript const nextStep = await client.next(step, { query: { noSession: 'true' }, // Optional: Query parameters }); ``` ### Response - **Promise** - A promise that resolves to the next journey step, a login success object, a login failure object, or undefined. ``` -------------------------------- ### Render TextCollector Example Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/README.md Iterates through collectors and renders TextCollector types, passing the collector and its update method. ```javascript const collectors = davinci.collectors(); collectors.map((collector) => { if (collector.type === 'TextCollector') { renderTextCollector(collector, davinci.update(collector)); } }); ``` -------------------------------- ### Davinci Client Initialization Source: https://github.com/forgerock/ping-javascript-sdk/blob/main/packages/davinci-client/api-report/davinci-client.api.md Initializes the Davinci client with configuration and optional middleware or logger settings. ```APIDOC ## davinci ### Description Initializes the Davinci client with configuration and optional middleware or logger settings. ### Signature ```typescript davinci(input: { config: DaVinciConfig; requestMiddleware?: RequestMiddleware[]; logger?: { level: LogLevel; custom?: CustomLogger; }; }): Promise<{ subscribe: (listener: () => void) => Unsubscribe; externalIdp: () => (() => Promise); flow: (action: DaVinciAction) => InitFlow; next: (args?: DaVinciRequest) => Promise; resume: (input: { continueToken: string; }) => Promise; start: (options?: StartOptions | undefined) => Promise; update: (collector: T) => Updater; validate: (collector: SingleValueCollectors | ObjectValueCollectors | MultiValueCollectors | AutoCollectors) => Validator; }>; ``` ```