npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mathereconomics/sophi-paywall-params-builder

v1.0.0

Published

Utility package to construct query parameters for requests to MatherEconomic's Sophi Dynamic Paywall API

Downloads

6

Readme

Overview

sophi-paywall-params-builder facilitates creating request parameters for calls to Sophi Paywall API, which generates wall decisions.

Requirements

This lightweight package is suitable for JavaScript environments such as browsers, Node.js, or edge runtimes like Fastly Compute.

Usage

To create request parameters, pass in a set of user and content details along with a Bins object retrieved from Sophi's CDN. Use the resulting parameters to obtain a paywall decision via Sophi's API.

Diagram of usage overview

Code Example

The following code snippet demonstrates how to utilize the package in a JavaScript environment to fetch a paywall decision. It illustrates the process from importing the necessary functions to making an API call to retrieve the decision based on user and content data.

// Import from package
import { prepareRequestParams } from "@mathereconomics/sophi-paywall-params-builder"

// Fetch bin file
const bin = await fetch("https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json")
  .then(response => {
    if (response.status === 200) return response.json()
  })

// Create object with content and visitor data
const inputs = {
	"content.id": "123",
	"content.lastPublishedAt": "2024-04-26",
	"page.section": "arts",
	"page.url": "https://www.example.com/sports/nfl/draft-picks-announced/abc123/",
	"visitor.visit.referrer": "https://google.com",
	"visitor.type": "anonymous",
	"visitor.isReturning": false,
	"visitor.utcOffset": -500,
	"visitor.device.type": "mobile",
	"visitor.device.os": "iOS",
	"visitor.device.viewer": "chrome"
}

// Pass input data and bin file to parameter builder
const search = prepareRequestParams(inputs, bin)
console.log(search instanceof URLSearchParams) // true

// Create URL for decisions endpoint
const hostname = "www.example.com" // replace with your hostname
const url = new URL(`https://paywall.sophi.io/hosts/${hostname}/decisions/me`)
// Append search parameters returned by prepareRequestParams to the URL
url.search = search
// Fetch a decision from the endpoint
const decision = await fetch(url).then(r => r.json())

Code Logic

Here's a detailed step-by-step breakdown of what the code snippet is doing:

  1. Import the Function: The code imports prepareRequestParams from the package @mathereconomics/sophi-paywall-params-builder. This function is used to prepare the request parameters necessary for fetching a paywall decision.
  2. Fetch Bins File: The code asynchronously fetches a bin file from Sophi's Content Delivery Network (CDN) using the URL provided (https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json). It waits for the response, checks if the status is 200 (OK), and then converts the response to JSON format, which represents the bin data. Note: Different hosts (www.site1.com, www.site2.com) may be using different bins files; make sure the bins file is being fetched from the right URL.
  3. Create Data Object: An object named inputs is created, containing various pieces of information about the content and the visitor. This includes IDs, URLs, publication dates, visitor types, devices, and more. These inputs are necessary for making a context-aware decision.
  4. Pass Input Data to Parameter Builder: The inputs object and the bin data fetched from the CDN are passed to the prepareRequestParams function. This function uses the data to generate URL search parameters suitable for querying the paywall decision endpoint. The output from prepareRequestParams is an instance of URLSearchParams.
  5. Create URL for Paywall Decision Endpoint: A base URL for the paywall decision endpoint is constructed using a hostname (www.example.com). This should be replaced with the actual hostname of the site for which a decision is being generated. The search parameters created earlier are appended to the URL to complete the request URL.
  6. Fetch Paywall Decision: Finally, the complete URL is used to make a GET request to the paywall decision endpoint. The response is awaited and then converted to JSON, which should contain the decision about whether to display a paywall to the user.

In summary, this code snippet illustrates the end-to-end process of fetching necessary data, processing it to fit the requirements of an API, and then querying that API to make a decision based on the inputs provided.

Reference

In the reference section below, you'll find detailed documentation for the API, which may include descriptions of endpoints, parameters, and sample requests. This information is designed to assist developers in understanding and integrating the API effectively into their applications.

prepareRequestParams()

/**
 * @param   {Inputs} inputs - Object containing data on user and content - see below
 * @param   {Bin} bin - Object fetched from Sophi CDN - see below
 * @returns {URLSearchParams} - Instance of the JavaScript built-in interface
 * @throws  {ArgumentError | UnexpectedError} - See below
 */
function prepareRequestParams(inputs: Inputs, bin: Bin): URLSearchParams

Inputs

An Inputs object consists of the following properties:

| Key | Description | Type | Example | Documentation | |----------|----------|----------|----------|----------| | content.id | Content ID as provided by the CMS | string, required | "123" | API docs | | page.section | Top-level section under which the page is published | string | "arts" | API docs | | visitor.type | Logged-in status of user | one of: "anonymous", "registered" | "anonymous" | API docs | | visitor.isReturning | Flag indicating whether user has visited before | boolean | true | API docs | | visitor.device.type | Type of user's device | string | mobile | API docs | | visitor.device.os | Operating system of user's device | string | iOs | API docs | | visitor.device.viewer | User's browser | string | chrome | API docs | | content.lastPublishedAt | Date when the article was published | string | "2024-04-26" | more | | visitor.utcOffset | Integer representing offset versus UTC time | integer | -230 | more | | page.url | Full URL of the page user is visiting | string | "https://www.example.com/sports/nfl/draft-picks-announced/abc123/" | more | | page.referrer | Full URL of the page user is coming from | string | "https://google.com" | more |

Expanded Inputs

In the following section, we expand upon specific properties within the inputs object, providing additional context beyond what is presented in the table.

content.lastPublishedAt

Date of the article's original publication, not when the article was last updated, formatted as a string in YYYY-MM-DD.

Examples:

  • "2023-12-01"
  • "2019-02-02"

visitor.utcOffset

Offset from Coordinated Universal Time (UTC) expressed as a time zone difference. Values are three or four digit numbers in the format (-)HHMM or (-)HMM, where H is hours and M is minutes. Values may be negative.

Value must be one of: -1200, -1100, -1000, -930, -900, -800, -700, -600, -500, -400, -330, -300, -200, -100, 0, 100, 200, 300, 330, 400, 430, 500, 530, 545, 600, 630, 700, 800, 845, 900, 930, 1000, 1030, 1100, 1200, 1245, 1300, 1400

Examples:

  • -500 - offset of minus five hours from UTC, New York standard time
  • -330 - offset of minus three hours thirty minutes from UTC, St. John's standard time
  • 0 - offset in UTC time zone, London standard time
  • 900 - offset of plus nine hours in UTC time zone, Tokyo standard time

page.url

Full URL of the page that the user is visiting. Query string can be omitted.

Example:

  • https://www.news.com/section/article-title-slug/2023-12-01/articleId123

page.referrer

URL of the page that the user navigated from. Query string can be omitted.

Example:

  • https://www.facebook.com

Bins

A Bins object is the return value of the Response.json method called on the response to the Sophi CDN after fetching from the bin URL. Do not transform or modify this object before passing it to prepareRequestParams.

:::(Info) If you are working with multiple hosts, for example www.site1.com and www.site2.com, make sure you are fetching the right bins file for each host. The URLs of bins files for each host may be different. :::

const bin: Bin = await fetch("https://cdn.sophi.io/distributions/js/apps/abc123/paywall-bin.json").then(r => r.json())

Errors

  • ArgumentError - thrown if the format of the argument passed is incorrect
    • For example: new Error("ArgumentError: expected bin to be an object, got string")
  • UnexpectedError - thrown if preparing parameters fails
    • For example: new Error("UnexpectedError")