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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@procore/cdn-translations

v0.3.1

Published

Library that provides a solution to pull translations from CDN

Maintainers

dancingshelldancingshelljustinmwattsjustinmwattsantonyayoubantonyayoubrysmithprocorerysmithprocorerobbiegprocorerobbiegprocorejadamsssjadamsssjeremy.bouzigardjeremy.bouzigardjgentesjgentesfaraz.haniffaraz.haniftimdohertytimdohertyajaykumar-procoreajaykumar-procoreb.bookoutb.bookoutjalyngjalyngchadryderchadryderhtaelhtaelrefaiepcnrefaiepcnjames.lawsonjames.lawsonvinayakaprabhuvinayakaprabhudavidshuredavidshurejames.clearyjames.clearyjl4everjl4everandersonbispoprocoreandersonbispoprocoredev-account-admindev-account-adminbrockpcorbrockpcorrowan.ibrahimrowan.ibrahimsseanwangsseanwangramysaid2ramysaid2vinaya-procorevinaya-procorelalovar-procorelalovar-procorebhargavrndbhargavrndihor.diachenko_procoreihor.diachenko_procorefarismmkfarismmkgideon-procoregideon-procoredannyporrellodannyporrelloalanprocorealanprocorechance.eakin.procorechance.eakin.procorestevenliprocorestevenliprocorejavio-procorejavio-procorekani-procorekani-procoreenyagaenyagadanny.oudanny.oumessanjahmessanjahdavid-christensen-procoredavid-christensen-procoreshradha.khardshradha.khardwinson.chuwinson.chueyvettesoueyvettesoulzhou888lzhou888jnhoang1jnhoang1nickprocorenickprocoreneil.mckeemanneil.mckeemanpam-whisenhuntpam-whisenhuntjgee67jgee67youssefameryoussefamermike-arndt-procoremike-arndt-procorebob.laskowskibob.laskowskicagmzcagmzmariah_delaneymariah_delaneylukenispellukenispelfabriciobdfabriciobdbikash.sahoobikash.sahoobbreyel921bbreyel921kimhin267kimhin267andy.mayerandy.mayerphil.custerphil.custerelijah.procoreelijah.procorejuliana.hernandezjuliana.hernandezjudy-lu-pcjudy-lu-pcprocore-it-supportprocore-it-supportandrewburke-pcandrewburke-pcjkleintechjkleintechrachel.arkebauerrachel.arkebauerprocore-npm-botprocore-npm-botgrafffffffgrafffffffyoyis3000yoyis3000james.dabbs-procorejames.dabbs-procorelaurenbrandsteinprocorelaurenbrandsteinprocorescottbieser-procorescottbieser-procoreamir-iskanderamir-iskanderzach.mckenzie.procorezach.mckenzie.procoreamyprocoreamyprocoreshayonj_procoreshayonj_procoreheplayskeysheplayskeysmike.southmike.souththomasoboylethomasoboyledischordedischordederek-carter-procorederek-carter-procoredlgasserdlgassercfprocorecfprocoreevan.waitsevan.waitsjeremy-marcusjeremy-marcusjmejia-fsljmejia-fslersgonzaloersgonzalotimofeeetimofeeestephan-procorestephan-procorealeclarsenprocorealeclarsenprocoresarah.freitassarah.freitasyihai.zweifelyihai.zweifeljay-rajanjay-rajanjacky-leijacky-leiapcarroll_procoreapcarroll_procoreprocore_halzyprocore_halzymehrdad-panahandehmehrdad-panahandehpeter.jinpeter.jinuddhavjoglekaruddhavjoglekarbrookyboy009brookyboy009denzylbalramdenzylbalramchangprocorechangprocoreallenanle.procoreallenanle.procoredevin.cunningham.procoredevin.cunningham.procoreari-procoreari-procorenoor.alinoor.alihgouhierprocorehgouhierprocorecyrille.baicyrille.baibrad.uranibrad.uranidmccraw-procoredmccraw-procorepatrick.lardinpatrick.lardinabhijit.patwardhanabhijit.patwardhanmatt.harris0223matt.harris0223alan.bresanialan.bresanijesse.olsenjesse.olsendtorres-procoredtorres-procoredineshkumar.jayakdineshkumar.jayakjason-kayejason-kayeyadhu.prakashyadhu.prakashleandro-procleandro-procandrew.wheelerandrew.wheelersherylnapigkitsherylnapigkitlydiaharalydiaharakahliholmeskahliholmessateesh-kadiyala-procoresateesh-kadiyala-procoreepalinprocoreepalinprocoredennis.heckmandennis.heckmanjamie-dugan-procorejamie-dugan-procoreviktoriia_azarovskaviktoriia_azarovskadaniel.ferreira-contractordaniel.ferreira-contractorwillpankonienwillpankonienladavargaladavargasteven.hinklesteven.hinkletxin1txin1chris.berberchris.berberetokarevetokarevritchleeritchleekarina.mendez-contractorkarina.mendez-contractorworldofsatyakiworldofsatyakigreg.sparksgreg.sparkskyle.williamskyle.williamskuldeepsingh4556kuldeepsingh4556jeremy.lundjeremy.lundbrocktillotsonprocorebrocktillotsonprocorestajicsstajicsryanfuentesprocoreryanfuentesprocoretyler.wasden.procoretyler.wasden.procorefabiomelo513fabiomelo513cody_schindler_procorecody_schindler_procoreamit.gurav-contractoramit.gurav-contractoryoasyo25yoasyo25kalyani.gosavikalyani.gosavihectorthielehectorthieleandersontr15andersontr15vishal-procorevishal-procoreomar.wagdyomar.wagdyyogevfine1yogevfine1charan_procorecharan_procorescorgiat-procorescorgiat-procorembartlett413mbartlett413attachiattachiahmed.ghorabahmed.ghorabvaromirvaromiralyelashram_procorealyelashram_procoreilya.dryha-contractorilya.dryha-contractorevan.cerwonka.procoreevan.cerwonka.procorevsobol-cvsobol-cdmitri_wmdmitri_wmkellikearnskellikearnsrichard.bunnrichard.bunnchaitra-m-15chaitra-m-15conner-procoreconner-procoremishaelowoyemimishaelowoyemipeterknifpeterknifaleh.haurylenia-contractoraleh.haurylenia-contractormiguel.garcia-procoremiguel.garcia-procorecodyrobertsprocorecodyrobertsprocorea.elbadaweia.elbadaweilnspatz914lnspatz914melch-procoremelch-procoremustafa-abdelrahmanmustafa-abdelrahmanatoaimaatoaimajasaswinijasaswiniadarsh.gautamadarsh.gautamamin.jaipuriamin.jaipurimax.helmetagmax.helmetags_kudryks_kudrykhyogmanhyogmankyle.liukyle.liudavidkangprodavidkangprostevenkang3stevenkang3cbathgatecbathgatevictorbendeck-pcvictorbendeck-pcsarah.herediasarah.herediamoaz-ashrafmoaz-ashrafaly-el-kerdanyaly-el-kerdanyprocore-oss-userprocore-oss-userabhishekkumar123abhishekkumar123stephanie.breretonstephanie.breretonsaurasumprocoresaurasumprocoremona.khairbekmona.khairbekelewando-procoreelewando-procorejyang-procorejyang-procoretedyangtedyangdeiabdeiabjgreene_procorejgreene_procoreasamayasamaykenny.foisykenny.foisyganesh.raghupathyganesh.raghupathyrajatmenhdirattarajatmenhdirattayzhou2024yzhou2024dlameter-procoredlameter-procoredecha-sansondecha-sansonkylepietzkylepietzconnie-feng-procoreconnie-feng-procoreroger-procoreroger-procorematheusprocorematheusprocorefernandocamilottifernandocamilottisimona.iancusimona.iancujacksonleach-procorejacksonleach-procoreg2mitchellg2mitchelltatsiana.cliftontatsiana.cliftonphunguyen-pcorphunguyen-pcorpmfrawleypmfrawleybrian.smith1brian.smith1scottsternscottsternneil1023neil1023srichaitanya.peddintisrichaitanya.peddintijake-pitkinjake-pitkinerikthoresonerikthoresonlhuang325lhuang325abhijit-procoreabhijit-procorerodayna.ehabrodayna.ehabfairchildfairchildmustafa-u-abdelrahmanmustafa-u-abdelrahmanaberkowitzaberkowitzpwhisenhunt-procorepwhisenhunt-procoremariia.solodovnikmariia.solodovniknigeld-procorenigeld-procoresamad.viranisamad.viranibohdan-horai-procorebohdan-horai-procoremathenes_procoremathenes_procorevinoth.kuppusamyvinoth.kuppusamyzayterzayteralan.facchini-contractoralan.facchini-contractorcassianomatos-procorecassianomatos-procoreamitk030amitk030sflang-procoresflang-procoretracy.ottotracy.ottodaniel-pierre-procoredaniel-pierre-procoreglidenorglidenorashish.sharma2024ashish.sharma2024gaurav.sharma.procoregaurav.sharma.procoreandres-mendez-procoreandres-mendez-procoreroobo-romeskiroobo-romeskikylemartinez-procorekylemartinez-procoresean.spearman.procoresean.spearman.procoregturkadzegturkadzejeffgiaquintojeffgiaquintoezrasimeloffezrasimeloffbill-wagnerbill-wagnerkellen.stewartkellen.stewartrodrigo.dejuanarodrigo.dejuanasaranahal2saranahal2andrew.isaacandrew.isaacagamaleldinagamaleldinmostafaeltazymostafaeltazymagdyyxxmagdyyxxandreszorrilla-procoreandreszorrilla-procoremohitsharma97mohitsharma97tejeshwartejeshwarswati.jadhavswati.jadhavsquidbeakssquidbeakssubham.panigrahisubham.panigrahideepak.kumartsdeepak.kumartsbagnaram-procorebagnaram-procoremahesh-s96mahesh-s96mohamed.adelmohamed.adelrana.eltayarrana.eltayarmahmoud-sharsharmahmoud-sharsharsyamphanindrasyamphanindraveroniaosamaveroniaosamaimanselimimanselimhelmy162-procorehelmy162-procorepclemonspclemonssamuelvelez8383samuelvelez8383vinitdeshkar-procorevinitdeshkar-procoremariam_mazenmariam_mazenmina-elnagarmina-elnagardaniel_andrewsdaniel_andrewsmohanad-aymanmohanad-aymanarsenii.derkach-procorearsenii.derkach-procorestepanvanzuriakprocorestepanvanzuriakprocorend-procorend-procoremarwansalem-prcmarwansalem-prcyoussefothmanyoussefothmanandrii.datsenko-contractorandrii.datsenko-contractor

Keywords

Readme

CDN Translations

A React-based internationalization system that manages translations through a centralized service and CDN. This package provides hooks and utilities for requesting, serving, and managing translations in a distributed system.

Architecture

The package follows a pub/sub architecture using the I18nSystem for communication between components. The main components are:

  1. Translation Requesters (useRequestTranslations)

    • Components that need translations use the useRequestTranslations hook
    • Handles translation lifecycle (pending/resolved/rejected)
    • Implements timeout handling and cleanup
    • Supports both file-based and folder-based translation structures
  2. Translation Preloader (usePreloadTranslations)

    • Proactively loads translations for better performance
    • Works alongside the main translation request system
    • Helps reduce perceived loading time
  3. MFE Translation Orchestrator (useMFETranslations)

    • Main entry point for Micro-Frontend applications
    • Coordinates between saving and loading translations
    • Provides backward compatibility with traditional translation loading
    • Manages CDN feature flag integration
  4. Direct CDN Access (getTranslationsFromCDN)

    • Utility function for directly fetching translations from CDN
    • Bypasses the React hook system for non-React contexts
    • Implements proper error handling and caching
  5. Translation Cache System

    • browser-based caching for resolved translations
    • Implements request tracking to handle concurrent requests
  6. Event System

    • Implements a robust pub/sub system using SystemEvents
    • Handles translation resolution and rejection events
    • Provides cleanup mechanisms for event subscriptions
    • Uses unique identifiers for event tracking

Core Features

Translation Request Flow

  1. A component requests translations using useRequestTranslations
  2. useSaveTranslations:
    • Checks for translations in nonStandardTranslations
    • Applies locale overrides
    • Sets up event subscriptions
    • Manages request timeouts
  3. useLoadTranslations:
    • Checks for translations in nonStandardTranslations
    • Applies locale overrides
    • Check if there is a similar request being fetched already
    • Request the translation file
  4. Translations are received through the event system
  5. The component's state is updated with the received translations

Caching System

  • We use browser caching. Our current caching duration is 1 hour as max age and we use the caching strategy of stale-while-revalidate for 24 hours so even if the file is stale it will be updated in the background.

Locale Management

  • Supports locale overrides through getOverrideLocale
  • Implements fallback list generation with duplicate prevention
  • Handles fallback scenarios when translations aren't available
  • Maintains translation state for different locales
  • Provides consistent fallback hierarchy

Usage

MFEs Hook

import { useMFETranslations } from '@procore/cdn-translations';
import en from './path/to/translations/en.json';
import enOwner from './path/to/translations/en-x-owner.json';
import enBudget from './path/to/translations/en-budget.json';

function MyComponent() {
  const { status, translations } = useMFETranslations(
    {
      type: 'file',
      absolute_file_path: (locale) => `path/to/translations/${locale}.json`,
      locale: 'es-ES',
    },
    {
      // non-standard translations
      en,
      'en-US-x-owner': enOwner,
      'en-budget': enBudget,
    },
    {
      oldTranslations: translations, // translations imported by traditional way
      enableCDN: boolean, // to determine to pull translations from CDN or using the traditional way
    }
  );

  // If you don't handle the pending state, strings will appear in English first,
  // then will appear in the requested language when the strings are available
  if (status === 'pending') return <Loading />;

  return <div>{translations.someKey}</div>;
}

Packages Hook

import { useRequestTranslations } from '@procore/cdn-translations';
import en from './path/to/translations/en.json';
import enOwner from './path/to/translations/en-x-owner.json';
import enBudget from './path/to/translations/en-budget.json';

function MyComponent() {
  const { status, translations } = useRequestTranslations(
    {
      type: 'file',
      absolute_file_path: (locale) => `path/to/translations/${locale}.json`,
      locale: 'es-ES',
    },
    {
      // non-standard translations
      en,
      'en-US-x-owner': enOwner,
      'en-budget': enBudget,
    },
    {
      oldTranslations: translations, // translations imported by traditional way
      enableCDN: boolean, // to determine to pull translations from CDN or using the traditional way
    }
  );

  // If you don't handle the pending state, strings will appear in English first,
  // then will appear in the requested language when the strings are available
  if (status === 'pending') return <Loading />;

  return <div>{translations.someKey}</div>;
}

Direct CDN Access

import { getTranslationsFromCDN } from '@procore/cdn-translations';

// For non-React contexts or direct CDN access
async function loadTranslationsDirectly() {
  const translations = await getTranslationsFromCDN(
    '/path/to/translations',
    'es-ES'
  );

  if (translations) {
    console.log('Translations loaded:', translations);
  } else {
    console.log('Failed to load translations');
  }
}

Folder-based Structure

import { useRequestTranslations } from '@procore/cdn-translations';
import enCommon from './path/to/translations/en/common.json';
import enError from './path/to/translations/en/error.json';

function MyComponent() {
  const { status, translations } = useRequestTranslations(
    {
      type: 'folder',
      absolute_file_path: (locale, file_name) =>
        `path/to/translations/${locale}/${file_name}.json`,
      locale: 'es-ES',
      file_name: 'common',
    },
    {
      // non-standard translations
      en: { ...enError, ...enCommon },
    },
    {
      oldTranslations: translations, // translations imported by traditional way
      enableCDN: boolean, // to determine to pull translations from CDN or using the traditional way
    }
  );

  // If you don't handle the pending state, strings will appear in English first,
  // then will appear in the requested language when the strings are available
  if (status === 'pending') return <Loading />;

  return <div>{translations.someKey}</div>;
}

Preloading Translations

import { usePreloadTranslations } from '@procore/cdn-translations';

function MyComponent() {
  // Preload translations for better performance
  usePreloadTranslations(
    {
      type: 'file',
      absolute_file_path: (locale) => `path/to/translations/${locale}.json`,
      locale: 'es-ES',
    },
    {}
  );

  // ... rest of component
}

Error Handling

The system handles various error cases:

  • Invalid translation data
  • Failed translation requests
  • Network errors and timeouts
  • JSON parsing errors
  • Aborted requests
  • Timeout scenarios (configurable via OVERDUE_TIMEOUT)
  • Invalid translation formats
  • Missing or invalid locale configurations

Each error case is properly logged and communicated back to the requesting component. The system implements robust error handling with try-catch blocks and ensures proper cleanup of resources.

Performance Considerations

  • Uses efficient event-based communication
  • Handles concurrent requests gracefully
  • Implements timeout mechanisms to prevent hanging requests
  • Minimizes network requests through caching
  • Supports preloading of translations
  • Implements request deduplication to prevent duplicate CDN calls
  • Uses browser caching with stale-while-revalidate strategy

Configuration

The package can be configured through the Configuration type:

type Configuration = {
  locale: string;
} & (
  | {
      type: 'file';
      absolute_file_path: (locale: string) => string;
    }
  | {
      type: 'folder';
      absolute_file_path: (locale: string, file_name: string) => string;
      file_name: string;
    }
);

Feature Flags

The package provides functionality to manage the CDN translation feature flag:

import {
  CDN_TRANSLATION_FEATURE_FLAG_KEY,
  isCDNFeatureFlagEnabled
} from '@procore/cdn-translations';

/**
 * The key used to check for the feature flag in LD.
 */
CDN_TRANSLATION_FEATURE_FLAG_KEY;

// * Checks if the CDN feature flag is enabled in the passed I18n
isCDNFeatureFlagEnabled(
  i18n: I18n | undefined,
  value?: boolean
)

// Retrieves the Launch Darkly app ID for the CDN translation feature flag based on the domain.
getCDNTranslationLDId(current_window_domain)

Constants

The package provides configurable constants:

  • OVERDUE_TIMEOUT: Timeout duration for translation requests (default: 5000ms)
  • REQUESTING_CACHE_THRESHOLD: Time threshold for request deduplication

Markdown Diagram

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#F2F2F2', 'primaryTextColor': '#333', 'lineColor': '#888', 'nodeBorder': '#555', 'mainBkg': '#FFFFFF'}}}%%
graph TD
    subgraph Component Layer
        A[React Component]
        B(useRequestTranslations Hook)
    end

    subgraph Translation Resolution Flow
        C{Check non-standard translations}
        C1{Check if locale need to be mapped}
        C2{Check non-standard translations}
        D{Check Browser Cache}
        F[Fetch from CDN]
    end

    subgraph Core System
        G["I18nSystem <br/>(Pub/Sub Event Bus)"]
        H(Browser Cache Storage)
        I[CDN Service]
    end

    subgraph State Update
        J[Update Component State]
    end

    %% --- Connections ---
    A -- calls --> B;
    B -- initiates --> C;

    C -- "No" --> C1;
    C -- "Yes, Publish event with translations" --> G;

    C1 -- "No" --> D;
    C1 -- "Yes" --> C2;

    C2 -- "No" -->  D;
    C2 -- "Yes, Publish event with translations" --> G;

    D -- "Not Found" --> F;
    D -- "Found" --> G;

    F -- "HTTP GET" --> I;
    I -- "Translation File" --> G;

    G -- "Publishes 'Resolved' Event" --> J;
    G -- "Caches translation" --> H;

    J -- "Triggers re-render" --> A;

    %% --- Styling ---
    style A fill:#e3f2fd,stroke:#333
    style B fill:#e0f7fa,stroke:#333
    style J fill:#dcedc8,stroke:#333
    style G fill:#fff9c4,stroke:#333
    style I fill:#ffecb3,stroke:#333
    style H fill:#fce4ec,stroke:#333