Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@bloomreach/spa-sdk

Package Overview
Dependencies
Maintainers
34
Versions
87
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bloomreach/spa-sdk

Bloomreach SPA SDK

  • 17.0.2-react18.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
10K
increased by112.61%
Maintainers
34
Weekly downloads
 
Created
Source

Bloomreach SPA SDK

Bloomreach SPA SDK provides simplified headless integration with Bloomreach Experience Manager for JavaScript-based applications. This library interacts with the Page Model API and exposes a simplified and framework-agnostic interface over the page model.

Features

  • Page Model API Client
  • Page Model Javascript implementation
  • URL Generator
  • Integration with Bloomreach Experience Manager Preview

Get Started

Installation

To get the SDK into your project with NPM:

npm install @bloomreach/spa-sdk

And with Yarn:

yarn add @bloomreach/spa-sdk

Usage

The following code snippet requests a related page model and shows the page's title.

import axios from "axios";
import { initialize } from "@bloomreach/spa-sdk";

async function showPage(path) {
  const page = await initialize({
    // The path to request from the Page Model API, should include query
    // parameters if those are present in the url
    path,
    // The location of the Page Model API of the brX channel
    endpoint: "http://localhost:8080/delivery/site/v1/channels/brxsaas/pages",
    // The httpClient used to make requests
    httpClient: axios,
  });

  document.querySelector("#title").innerText = page.getTitle();
}

showPage(`${window.location.pathname}${window.location.search}`);

Relevance Integration

(not applicable to Content SaaS)

The SDK provides basic Express middleware for seamless integration with the Relevance Module.

import express from "express";
import { relevance } from "@bloomreach/spa-sdk/lib/express";

const app = express();

app.use(relevance);

The middleware can be customized using the withOptions method.

app.use(relevance.withOptions({ name: "_visitor", maxAge: 24 * 60 * 60 }));

Rendering HTML content safely

The SPA SDK provides an API, Page.sanitize(html), which sanitizes HTML content using the sanitize-html library, to render the HTML content safely.

For example, in a React example, you may sanitize and render the HTML content which came from the backend like the following example:

{/* Suppose the content.value below contains HTML markups string. */}
<div>
   {content && <div dangerouslySetInnerHTML={{ __html: page.rewriteLinks(page.sanitize(content.value)) }} />}
</div>

The same principle may apply in other frameworks. e.g, v-html in Vue.js or [innerHTML] in Angular.

License

Published under Apache 2.0 license.

Reference

Configuration

The initialize function supports several options you may use to customize page initialization.

Commonly used options
debug
The option enabling debug mode.

Required: no
Default: false
endpoint
Base URL of the Page Model API (e.g. http://localhost:8080/delivery/site/v1/channels/brxsaas/pages or http://localhost:8080/site/channel/resourceapi). This option is exclusive and should not be used together with options or cmsBaseUrl

Required: yes
Default: . none
httpClient
The HTTP client that will be used to fetch the page model. Signature is similar to Axios client.

Required: yes
Default: none
path
The path part of the URL, including a query string if present (e.g. /path/to/page?foo=1

Required: no
Default: ) / .
origin
The brXM origin to verify an integration with the Experience Manager. This option should be used when the brXM is accessible from a host other than the Page Model API. By default, the origin from the apiBaseUrl or endpoint parameters is used.

Required: no
Default: none
baseUrl
Base URL of the SPA (e.g. /account or //www.example.com). This option can only be used if endpoint is present.

Required: no
Default: ""
apiBaseUrl
Base URL of the Page Model API (e.g. http://localhost:8080/delivery/site/v1/channels/brxsaas/pages or http://localhost:8080/site/channel/resourceapi). This option will be ignored if options is present.

Required: no
Default: cmsBaseUrl + "/resourceapi"
spaBaseUrl
Base URL of the SPA (e.g. /account or //www.example.com). This option will be ignored if options is present.

Required: no
Default: ""
Extra options
apiVersion
Current API version. By default, the compatible with the current setup version will be chosen.

Required: no
Default: none
apiVersionHeader
API version header.

Required: "Accept-Version"
Default: none
authorizationHeader
Authorization header for the Page Model API.

Required: no
Default: "Authorization"
authorizationQueryParameter
The query string parameter used to pass authorization header value.

Required: no
Default: "token"
authorizationToken
Authorization token for the Page Model API. By default, the SDK will try to extract the token from the request query string using authorizationQueryParameter option.

Required: no
Default: none
serverId
Cluster node identifier. By default, the SDK will try to extract the value from the request query string using serverIdQueryParameter option.

Required: no
Default: none
serverIdHeader
Header identifying the current cluster node.

Required: no
Default: "Server-Id"
serverIdQueryParameter
The query string parameter used to pass a cluster node identifier.

Required: no
Default: "server-id"
window
A window object reference will be used to interact with brXM. It needs to be set when initialize is being called within an iframe or worker process.

Required: no
Default: window
Relevance options (PaaS-only)
visitor
An object holding information about the current visitor. The option takes precedence over request.visitor

Required: no
Default: . none
visitor.id
The current visitor identifier.

Required: yes
Default: none
visitor.header
An HTTP-header using to pass the visitor identifier to the Page Model API.

Required: yes
Default: none
request
Current user's request.

Required: yes
Default: none
request.connection
Current request remote connection containing the remote address. This option is used in the Relevance Module

Required: no
Default: . none
request.emit
Emits an event in the request scope. This option can be used in Node.js integration

Required: no
Default: . none
request.headers
An object holding request headers. It should contain a Cookie header if rendering is happening on the server-side in the UrlRewriter-based setup.

Required: no
Default: {}
request.path
The path part of the URL, including a query string if present (e.g. /path/to/page?foo=1). The option is deprecated in favor of path

Required: no
Default: . /
request.visitor
An object holding information about the current visitor.

Required: no
Default: none
These options are deprecated and will be removed in the next major release
cmsBaseUrl
Base URL of the site (e.g. http://localhost:8080/site or http://localhost:8080/site/channel). This option is exclusive and should not be used together with options or endpoint

Required: exclusive
Default: . none
options
The CMS URL options. This option is exclusive and should not be used together with cmsBaseUrl or endpoint. Use this property to enable the UrlRewriter-based setup.

Required: exclusive
Default: none
options.live
The CMS URL options for the live site.

Required: yes
Default: none
options.live.apiBaseUrl
Base URL of the Page Model API for the live site (e.g. http://localhost:8080/delivery/site/v1/channels/brxsaas/pages or http://localhost:8080/site/channel/resourceapi

Required: no
Default: ) options.live.cmsBaseUrl + "/resourceapi" .
options.live.cmsBaseUrl
Base URL of the live site (e.g. http://localhost:8080/site or http://localhost:8080/site/channel

Required: yes
Default: ) none .
options.live.spaBaseUrl
Base URL of the live SPA (e.g. /account or //www.example.com

Required: no
Default: ) "" .
options.preview
The CMS URL options for the preview site.

Required: yes
Default: none
options.preview.apiBaseUrl
Base URL of the Page Model API for the preview site (e.g. http://localhost:8080/site/_cmsinternal/resourceapi or http://localhost:8080/site/_cmsinternal/channel/resourceapi

Required: no
Default: ) options
.preview.cmsBaseUrl
+ "/resourceapi" .
options.preview.cmsBaseUrl
Base URL of the live site (e.g. http://localhost:8080/site/_cmsinternal or http://localhost:8080/site/_cmsinternal/channel

Required: yes
Default: ) none .
options.preview.spaBaseUrl
Base URL of the live SPA (e.g. /site/_cmsinternal?bloomreach-preview=true or /site/_cmsinternal/channel?bloomreach-preview=true). This path and query string parameters will be used to detect whether it is a preview mode or not.

Required: no
Default: ""
Functions
FunctionDescription
initialize(config, model?): Promise<Page>This function accepts a configuration object as an argument and returns a promisified JavaScript object representing the page model. In case, when the page model has already been fetched, you can pass this JSON blob as a second parameter.
destroy(page: Page): voidDestroys the integration with the SPA page object.
getContainerItemContent<T>(component: ContainerItem, page: Page): T | nullReturns the content object that belongs to the container item, or null if not found.
isPage(value): booleanChecks whether a value is a page.
isComponent(value): booleanChecks whether a value is a page component.
isContainer(value): booleanChecks whether a value is a page container.
isContainerItem(value): booleanChecks whether a value is a page container item.
isContent(value): booleanChecks whether a value is a content object.
isDocument(value): booleanChecks whether a value is a document object.
isImageSet(value): booleanChecks whether a value is an image set object.
isMenu(value): booleanChecks whether a value is a menu object.
isMeta(value): booleanChecks whether a value is a meta-data object.
isMetaComment(value): booleanChecks whether a value is a meta-data comment.
isPagination(value): booleanChecks whether a value is a pagination.
isLink(value): booleanChecks whether a value is a link.
isReference(value): booleanChecks whether a value is a content reference.
relevance(request: IncomingMessage, response: OutgoingMessage, next?: () => void): voidExpress middleware for seamless integration with the Relevance Module.
relevance.withOptions(options?: Options): HandlerCustomizes Express middleware for the Relevance Module integration.
Constants
ConstantDescription
META_POSITION_BEGINMeta-data following before a page component.
META_POSITION_ENDMeta-data following after a page component.
TYPE_CONTAINER_BOXA blocked container with blocked items.
TYPE_CONTAINER_INLINEA blocked container with inline items.
TYPE_CONTAINER_NO_MARKUPA container without surrounding markup.
TYPE_CONTAINER_ORDERED_LISTAn ordered list container.
TYPE_CONTAINER_UNORDERED_LISTAn unordered list container.
TYPE_CONTAINER_ITEM_UNDEFINEDA container item without mapping.
TYPE_LINK_EXTERNALLink to a page outside the current application.
TYPE_LINK_INTERNALLink to a page inside the current application.
TYPE_LINK_RESOURCELink to a CMS resource.
TYPE_MANAGE_MENU_BUTTONA manage menu button.
TYPE_MANAGE_CONTENT_BUTTONA manage content button.
Objects
Page

The Page class represents the brXM page to render. This is the main entry point to the page model.

MethodDescription
getButton(type: string, ...params: any[]): MetaCollectionGenerates a meta-data collection for the Experience Manager buttons.
getChannelParameters(): objectGets current channel parameters.
getComponent(...componentNames): Component | undefinedGets a component in the page (e.g. getComponent('main', 'right')). If componentNames is omitted, then the page root component will be returned.
getContent(reference: Reference | string): Content | T | undefinedGets a content item used on the page.
getDocument(): T | undefinedGets the page root document. This option is available only along with the Experience Pages feature.
getMeta(meta): MetaCollectionGenerates a meta-data collection from the provided meta model. The method is deprecated and will be removed in the next major release.
getTitle(): string | undefinedGets the title of the page, or undefined if not configured.
getUrl(link?: Link): stringGenerates a URL for a link object.
- If the link object type is internal, then it will prepend spaBaseUrl or baseUrl. In case when the link starts with the same path as in cmsBaseUrl, this part will be removed.
- If the link object type is unknown, then it will return undefined.
- If the link parameter is omitted, then the link to the current page will be returned.
- In other cases, the link will be returned as-is.
getUrl(path: string): stringGenerates an SPA URL for the path.
- If it is a relative path and cmsBaseUrl is present, then it will prepend spaBaseUrl.
- If it is an absolute path and cmsBaseUrl is present, then the behavior will be similar to internal link generation.
- If it is a relative path and endpoint is present, then it will resolve this link relative to the current page URL.
- If it is an absolute path and endpoint is present, then it will resolve this link relative to the baseUrl option.
getVersion(): string | undefinedReturns the Page Model version.
getVisitor(): Visitor | undefinedGets the current visitor information, or undefined if the Relevance Module is not enabled. The Visitor object consists of the following properties:
- id: string - the current visitor identifier;
- header: string - an HTTP-header using to pass the visitor identifier to the Page Model API.
getVisit(): Visit | undefinedGets the current visit information, or undefined if the Relevance Module is not enabled. The Visit object consists of the following properties:
- id: string - the current visit identifier;
- new: boolean - a flag showing that this is a new visit.
isPreview(): booleanReturns whether the page is in the preview mode.
rewriteLinks(content: string, type?: string): stringRewrite links to pages and resources in the HTML content. This method looks up for a tags with data-type and href attributes and img tags with src attribute. Links will be updated according to the configuration used to initialize the page. The type parameter is similar to mimeType parameter of the DOMParser.
sync(): voidSynchronizes the brXM integration state (UI elements positions).
toJSON(): objectA plain JavaScript object of the page model.
Component

The Component class corresponds to page nodes, and it may hold other components inside.

MethodDescription
getId(): stringReturns the component id.
getMeta(): MetaCollectionReturns the component meta-data collection.
getModels(): objectReturns the map of the component models.
getUrl(): string | undefinedReturns the link to the partial component model.
getName(): stringReturns the name of the component.
getParameters(): objectReturns the parameters of the component.
getProperties(): objectAlias for getParameters method.
getChildren(): Component[]Returns the direct children of the component.
getComponent(...componentNames: string[]): Component | undefinedLooks up for a nested component.
getComponentById(id: string): Component | undefinedLooks up for a nested component by its id.
Container

The Container class represents a page node that is actually present in the DOM but as an element surrounding its children. Container extends the Component class, and therefore, all the Component methods are applicable here.

MethodDescription
getType(): string | undefinedReturns the type of a container.
Container Item

The ContainerItem objects are usually visible on the page and interact with the user. Container Item extends the Component class, and therefore, all the Component methods are applicable here.

MethodDescription
getLabel(): string | undefinedReturns the label of a container item catalogue component.
getType(): string | undefinedReturns the type of a container item. The available types depend on which container items have been configured in the backend (e.g. "Banner").
isHidden(): booleanReturns whether the component should not render anything. Hiding components is only possible with the Relevance feature.
on(eventName: string, listener: Function): FunctionSubscribes for an event and returns the unsubscribe function.
off(eventName: string, listener: Function): voidUnsubscribes from an event.
getContentReference(): Reference | undefinedReturns a RFC-6901 JSON Pointer to the content of this container item.
getContent(page: Page): T | null;Returns the content of this component from the page that contains the content.
Content

The Content object holds document data that is used by the page components.

MethodDescription
getId(): stringReturns the content id.
getLocale(): string | undefinedReturns the content locale.
getMeta(): MetaCollectionReturns the content meta-data collection.
getName(): stringReturns the content name.
getData(): objectReturns the content data as it is returned in the Page Model API.
getUrl(): string | undefinedReturns the link to the content.
Document

The Document object holds document data that is used by the page components.

MethodDescription
getId(): stringReturns the document id.
getLocale(): string | undefinedReturns the document locale.
getMeta(): MetaCollectionReturns the document meta-data collection.
getName(): stringReturns the document name.
getData(): objectReturns the document data as it is returned in the Page Model API.
getUrl(): string | undefinedReturns the link to the content.
ImageSet

The ImageSet object holds images collection that is used by the page components.

MethodDescription
getDescription(): string undefined;Returns the image set description.
getDisplayName(): stringReturns the image set display name.
getId(): stringReturns the document id.
getFileName(): stringReturns the image set file name.
getId(): stringReturns the image set id.
getLocale(): string | undefinedReturns the image set locale.
getName(): stringReturns the image name.
getOriginal(): Image | undefinedReturns the original image.
getThumbnail(): Image | undefinedReturns the thumbnail.
Image

The Image object holds an image object that is used by the ImageSet object.

MethodDescription
getDisplayName(): stringReturns the image display name.
getFileName(): string | undefinedReturns the image file name.
getHeight(): numberReturns the image height.
getMimeType(): stringReturns the image mime-type.
getName(): stringReturns the image name.
getSize(): numberReturns the image size.
getUrl(): string | undefinedReturns the image link.
getWidth(): numberReturns the image width.
Menu

The Menu object holds the page menu data with all the menu items.

MethodDescription
getItems(): MenuItem[]Returns the menu items.
getMeta(): MetaCollectionReturns the menu meta-data collection.
getName(): stringReturns the menu name.
getSelected(): MenuItem | undefinedReturns the current menu item. The method is deprecated and will be removed in the next major release.
MenuItem

The MenuItem object holds a menu item that is used by the Menu object.

MethodDescription
getChildren(): MenuItem[]Returns the child items.
getDepth(): numberReturns the menu item depth level.
getLink(): Link | undefinedReturns the menu item link.
getName(): stringReturns the menu item name.
getParameters(): objectReturns the menu item parameters.
getUrl(): string | undefinedReturns the menu item url.
isExpanded(): booleanReturns whether the menu item is expanded.
isRepositoryBased(): booleanReturns whether the menu item is repository based.
isSelected(): booleanReturns whether the menu item is selected.
MetaCollection
MethodDescription
clear(): voidClears previously rendered meta-data objects.
render(head: HTMLElement, tail: HTMLElement): () => void;Renders meta-data objects on the page and returns the callback clearing rendered objects.
Meta

The Meta objects are being used by the brXM to page and its components.

MethodDescription
getData(): stringReturns the meta-data.
getPosition(): stringReturns the meta-data position relative to the related element.
Pagination

The Pagination object holds the pagination data with all the pagination items.

MethodDescription
getCurrent(): PaginationItemReturns the current page.
getFirst(): PaginationItemReturns the first page.
getItems(): Reference[]Returns the current page items.
getLast(): PaginationItemReturns the last page.
getNext(): PaginationItem | undefinedReturns the next page.
getOffset(): numberReturns the number of items before the current page.
getPages(): PaginationItem[]Returns currently listed pages.
getPrevious(): PaginationItem | undefinedReturns the previous page.
getSize(): numberReturns the number of items listed on the current page.
getTotal(): numberReturns the total number of items.
isEnabled(): booleanReturns whether the pagination is enabled.
PaginationItem

The PaginationItem object holds a pagination item that is used by the Pagination object.

MethodDescription
getNumber(): numberReturns the page number.
getUrl(): string | undefinedReturns the page URL.

Keywords

FAQs

Package last updated on 19 Oct 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc