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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@comher.de/watchtime-api

v1.0.0

Published

A TypeScript library to track children's watch time using a DynamoDB backend

Downloads

7

Readme

WatchTimeLib

A TypeScript library designed to track children's watch time using a DynamoDB-based backend service. This library offers functionality to publish events, manage watch activities, and retrieve watch activities while respecting daily boundaries and handling open-ended activities.


Features

  • Retrieve the version of the backend API.
  • Publish events with optional timestamps.
  • Publish watch activities with a start time and duration (creates start and end events).
  • Retrieve watch activities within a specified time range, with support for daily boundaries and open-ended activities.
  • Configure the service URL via environment variables.
  • Customize the "day break" hour to define when a new "activity day" begins (e.g., reset at 2 AM).

Installation

To install the watchtime-lib library, run the following command in your terminal:

npm install watchtime-lib

This will add the library to your project's dependencies.


Setup

Before using the library, complete the following setup steps:

1. Environment Variable Configuration

The library relies on an environment variable WATCHTIME_API_URL to connect to the backend service. Follow these steps:

  • Set the Environment Variable:

    • Define WATCHTIME_API_URL in your environment (e.g., via a .env file or your build system's configuration).
    • Example: WATCHTIME_API_URL=https://your-backend-url.
    • If not set, the library defaults to http://localhost:3000.
  • Framework-Specific Notes:

    • Create React App: Use REACT_APP_WATCHTIME_API_URL (e.g., add REACT_APP_WATCHTIME_API_URL=https://your-backend-url to your .env file).
    • Vite or Webpack: Use WATCHTIME_API_URL directly in your .env file and ensure your build tool injects it.

2. Build-Time Configuration

Ensure your build tool properly injects environment variables:

  • For Create React App, variables must be prefixed with REACT_APP_.
  • For Vite, add the .env file at the root and use import.meta.env.WATCHTIME_API_URL.
  • For Webpack, configure the DefinePlugin or use a similar method to expose the variable.

Verify the variable is available in your application before initializing the library.


Usage

Below are detailed examples of how to use the library's core features.

1. Initialize the Library

Import and initialize the WatchTimeTracker class. You can provide the API URL explicitly or rely on the environment variable.

import { WatchTimeTracker } from "watchtime-lib";

// Initialize with the API URL (falls back to http://localhost:3000 if not provided)
const tracker = new WatchTimeTracker(process.env.WATCHTIME_API_URL || "http://localhost:3000");

2. Get the API Version

Check the version of the backend service to ensure compatibility.

tracker.getVersion()
  .then(version => {
    console.log(`API Version: ${version}`);
  })
  .catch(error => {
    console.error("Error fetching API version:", error);
  });

3. Publish an Event

Publish a single event for a user and content type. Timestamps are optional and default to the current time if omitted.

tracker.publishEvent("child1", "video", "2025-02-28T10:00:00Z")
  .then(event => {
    console.log("Event published:", event);
  })
  .catch(error => {
    console.error("Error publishing event:", error);
  });
  • Parameters:
    • userId: String (required, e.g., "child1")
    • contentType: String (required, e.g., "video")
    • timestamp: Optional ISO 8601 string (e.g., "2025-02-28T10:00:00Z")

4. Publish a Watch Activity

Publish a complete watch activity by providing a start time and duration. This creates two events: one for the start and one for the end.

tracker.publishWatchActivity("child1", "video", "2025-02-28T10:00:00Z", 3600000) // 1 hour
  .then(events => {
    console.log("Activity published:", events);
  })
  .catch(error => {
    console.error("Error publishing activity:", error);
  });
  • Parameters:
    • userId: String (required)
    • contentType: String (required)
    • startTime: ISO 8601 string (required)
    • duration: Number (milliseconds, required)

5. Get Watch Activities

Retrieve a list of watch activities for a user and content type within a time range. The library handles daily boundaries and open-ended activities automatically.

tracker.getWatchActivities(
  "child1",
  "video",
  "2025-02-28T00:00:00Z",
  "2025-02-28T23:59:59Z",
  2 // Optional: reset activities at 2 AM UTC
)
  .then(activities => {
    console.log("Activities:", activities);
  })
  .catch(error => {
    console.error("Error retrieving activities:", error);
  });
  • Parameters:

    • userId: String (required)
    • contentType: String (required)
    • startTime: ISO 8601 string (required)
    • endTime: ISO 8601 string (required)
    • dayBreakHour: Number (optional, default is 0 for midnight UTC)
  • Behavior:

    • Activities are paired as start and end events.
    • Open-ended activities (no end event) are closed at the end of the "activity day" if within the queried range.
    • The "activity day" resets at the specified dayBreakHour.

Advanced Usage

Custom Day Break Hour

Customize when an "activity day" resets by setting the dayBreakHour. For example, use 2 for 2 AM UTC.

tracker.getWatchActivities(
  "child1",
  "video",
  "2025-02-28T00:00:00Z",
  "2025-03-01T00:00:00Z",
  2 // Reset at 2 AM UTC
)
  .then(activities => {
    console.log("Activities with custom day break:", activities);
  });

Error Handling

The library includes input validation and throws descriptive errors for invalid usage.

try {
  await tracker.publishEvent("", "video"); // Throws error
} catch (error) {
  console.error(error.message); // "userId must be a non-empty string"
}

Configuration

Setting the API URL

Configure the backend service URL via the WATCHTIME_API_URL environment variable:

  • Example .env File:
    WATCHTIME_API_URL=https://your-backend-url
  • Default: If unset, the library uses http://localhost:3000.

Ensure this is set before initializing the library in your application.


Building and Publishing

To build and publish the watchtime-lib library to npm from your local setup (e.g., after running the setup script), follow these detailed steps:

Prerequisites

  1. Install Node.js and npm:

    • Ensure Node.js is installed on your Mac. You can check by running:
      node -v
      npm -v
    • If not installed, download and install it from nodejs.org or use Homebrew:
      brew install node
  2. Navigate to the Project Directory:

    • After running the setup script, change into the project directory:
      cd watchtime-lib
  3. Install Dependencies:

    • The package.json specifies TypeScript as a dev dependency. Install it by running:
      npm install
    • This creates a node_modules directory and installs TypeScript (~4.9.5 as specified).

Build the Library

  1. Compile the TypeScript Code:
    • Build the library into JavaScript files in the dist directory:
      npm run build
    • This runs the tsc command defined in package.json, generating dist/index.js, dist/index.d.ts, and other compiled files.

Publish to npm

  1. Set Up an npm Account:

    • If you don’t have an npm account, create one at npmjs.com.
    • Log in to npm from your terminal:
      npm login
    • Enter your username, password, and email when prompted.
  2. Update Package Name (Optional):

    • The default name in package.json is "watchtime-lib". Check if it’s available on npm:
      npm info watchtime-lib
    • If it’s taken, edit package.json to use a unique name (e.g., "@yourusername/watchtime-lib") before proceeding:
      "name": "@yourusername/watchtime-lib"
  3. Publish the Library:

    • Publish the package to npm:
      npm publish --access public
    • The --access public flag is required for scoped packages (e.g., @yourusername/watchtime-lib). For unscoped packages, you can omit it if it’s your first publish or configure it as public in package.json:
      "publishConfig": {
        "access": "public"
      }
  4. Verify Publication:

    • Check npm to ensure your library is live:
      npm info watchtime-lib
    • Or visit https://www.npmjs.com/package/watchtime-lib (or your custom package name).

Post-Publishing

  1. Version Updates (Optional):
    • To update the library later, increment the version in package.json (e.g., from "1.0.0" to "1.0.1"), rebuild, and republish:
      npm run build
      npm publish --access public

Notes

  • Timestamps: Use ISO 8601 format (e.g., 2025-02-28T10:00:00Z) for all timestamps.
  • Activity Days: Activities are grouped by "activity days," resetting at the dayBreakHour (default is midnight UTC).
  • Open-Ended Activities: Activities without an end event are closed at the end of their "activity day" if within the query range; otherwise, they remain open.

This README.md provides everything you need to set up, use, and publish the watchtime-lib library effectively. Happy coding!