:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): add a currency filter to liquid (#120330)
Harley Alexander1b99f1539721
diff --git a/frontend/src/lib/utils/liquid.test.ts b/frontend/src/lib/utils/liquid.test.tsindex c53330cad2bb..420a960a60c8 100644--- a/frontend/src/lib/utils/liquid.test.ts+++ b/frontend/src/lib/utils/liquid.test.ts@@ -20,6 +20,10 @@ describe('LiquidRenderer', () => {expect(LiquidRenderer.resolves(expression, context)).toBe(expected)})+ it('formats money with the currency filter, like the worker does at send time', () => {+ expect(LiquidRenderer.render('{{ amount | currency: "USD" }}', { amount: 1234.5 })).toBe('$1,234.50')+ })+it('treats an unparseable expression as unresolved rather than throwing', () => {expect(LiquidRenderer.resolves('person.properties[', context)).toBe(false)})diff --git a/frontend/src/lib/utils/liquid.ts b/frontend/src/lib/utils/liquid.tsindex 95323b0674e0..844c1509bec3 100644--- a/frontend/src/lib/utils/liquid.ts+++ b/frontend/src/lib/utils/liquid.ts@@ -3,6 +3,108 @@ import { Liquid, Output, Template } from 'liquidjs'const LIQUID_REGEX = /\{\{(.*?)\}\}|{%(.*?)%}/g+// Copy of the currency filter in nodejs/src/cdp/utils/liquid.ts, so previews format money the way sends do.+const REGION_CURRENCIES: Record<string, string> = {+ US: 'USD',+ GB: 'GBP',+ CA: 'CAD',+ AU: 'AUD',+ NZ: 'NZD',+ IN: 'INR',+ JP: 'JPY',+ CH: 'CHF',+ SE: 'SEK',+ NO: 'NOK',+ DK: 'DKK',+ PL: 'PLN',+ BR: 'BRL',+ MX: 'MXN',+ ...Object.fromEntries(+ ['AT', 'BE', 'DE', 'ES', 'FI', 'FR', 'GR', 'IE', 'IT', 'LU', 'NL', 'PT'].map((region) => [region, 'EUR'])+ ),+}++// The languages a locale argument may name, with the region a bare language implies.+const LANGUAGE_REGIONS: Record<string, string> = {+ en: 'US',+ fr: 'FR',+ de: 'DE',+ es: 'ES',+ it: 'IT',+ nl: 'NL',+ pt: 'PT',+ fi: 'FI',+ sv: 'SE',+ da: 'DK',+ nb: 'NO',+ no: 'NO',+ pl: 'PL',+ ja: 'JP',+}+const LOCALE_ARGUMENT = /^([a-z]{2})(?:[-_]([a-z]{2}))?$/i+const CURRENCY_CODE = /^[a-z]{3}$/i++// Customer.io's `currency` takes `locale, code` (`"en", "EUR"`) or a locale alone (`"en-GB"`), and+// templates also pass a bare ISO code (`"USD"`), so all three forms resolve to a locale and a code.+// Arguments are checked against fixed patterns and tables, never parsed with Intl.Locale: a filter+// call runs to completion before the render deadline is checked, and exotic locale tags are slow to parse.+const resolveCurrencyFormat = (first: unknown, second: unknown): [string, string] | null => {+ if (first === undefined) {+ return ['en-US', 'USD']+ }+ if (typeof first !== 'string' || (second !== undefined && typeof second !== 'string')) {+ return null+ }+ if (second === undefined && CURRENCY_CODE.test(first)) {+ return ['en-US', first.toUpperCase()]+ }+ const locale = LOCALE_ARGUMENT.exec(first)+ const language = locale?.[1].toLowerCase()+ if (!locale || !language || !LANGUAGE_REGIONS[language]) {+ return null+ }+ const region = (locale[2] ?? LANGUAGE_REGIONS[language]).toUpperCase()+ const code =+ second === undefined ? REGION_CURRENCIES[region] : CURRENCY_CODE.test(second) ? second.toUpperCase() : null+ return code ? [`${language}-${region}`, code] : null+}++// Building a formatter costs far more than using one, so templates that repeat their arguments reuse it.+// Cleared when full, so tenant-chosen arguments can't grow it without bound.+const CURRENCY_FORMATTER_CACHE_LIMIT = 256+const currencyFormatters = new Map<string, Intl.NumberFormat | null>()++const currencyFormatter = (first: unknown, second: unknown): Intl.NumberFormat | null => {+ const format = resolveCurrencyFormat(first, second)+ if (!format) {+ return null+ }+ const key = format.join(' ')+ let formatter = currencyFormatters.get(key)+ if (formatter === undefined) {+ try {+ formatter = new Intl.NumberFormat(format[0], { style: 'currency', currency: format[1] })+ } catch {+ formatter = null+ }+ if (currencyFormatters.size >= CURRENCY_FORMATTER_CACHE_LIMIT) {+ currencyFormatters.clear()+ }+ currencyFormatters.set(key, formatter)+ }+ return formatter+}++// A value that isn't a number, or arguments that don't resolve, pass through unchanged, so a bad value+// stays visible instead of turning into "$0.00".+const formatCurrency = (value: unknown, first?: unknown, second?: unknown): unknown => {+ const amount = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN+ if (!Number.isFinite(amount)) {+ return value+ }+ return currencyFormatter(first, second)?.format(amount) ?? value+}+// NOTE: This should be moved to common package but currently is a copy of nodejs/src/cdp/utils/liquid.tsexport class LiquidRenderer {private static _liquid: Liquid | null = null@@ -15,6 +117,7 @@ export class LiquidRenderer {// partial loading, so user-controlled templates can't read local files via include/render/layout.templates: {},})+ this._liquid.registerFilter('currency', formatCurrency)}return this._liquid}diff --git a/nodejs/src/cdp/utils/liquid.test.ts b/nodejs/src/cdp/utils/liquid.test.tsindex 4c846b03795a..05ef8f8e8d32 100644--- a/nodejs/src/cdp/utils/liquid.test.ts+++ b/nodejs/src/cdp/utils/liquid.test.ts@@ -111,6 +111,24 @@ describe('LiquidRenderer', () => {const result = LiquidRenderer.renderWithHogFunctionGlobals(template, globals)expect(result).toMatch(/^\d{8}$/)})++ it.each([+ ['{{ 1234.5 | currency: "USD" }}', '$1,234.50'],+ ['{{ "500" | currency }}', '$500.00'],+ ['{{ -20 | currency: "USD" }}', '-$20.00'],+ ['{{ 1234.5 | currency: "EUR" }}', '€1,234.50'],+ ['{{ 1234.5 | currency: "en-GB" }}', '£1,234.50'],+ ['{{ 1234.5 | currency: "en", "EUR" }}', '€1,234.50'],+ ['{{ 1234.5 | currency: "de-DE" }}', '1.234,50 €'],+ ['{{ 10 | currency: "zz-QQ" }}', '10'],+ ['{{ 10 | currency: "qxy-QQ", "USD" }}', '10'],+ ['{{ 10 | currency: "en-us" }}', '$10.00'],+ ['{{ missing | default: "ERROR" | currency: "USD" }}', 'ERROR'],+ ['{{ missing | currency: "USD" }}', ''],+ ['{{ 10 | currency: "not-a-code" }}', '10'],+ ])('formats %s with the currency filter', (template, expected) => {+ expect(LiquidRenderer.renderWithHogFunctionGlobals(template, globals)).toBe(expected)+ })})describe('HTML decoding', () => {diff --git a/nodejs/src/cdp/utils/liquid.ts b/nodejs/src/cdp/utils/liquid.tsindex 7eea32080a10..44f3c87d76ba 100644--- a/nodejs/src/cdp/utils/liquid.ts+++ b/nodejs/src/cdp/utils/liquid.ts@@ -84,6 +84,108 @@ const decodeLiquidTags = (template: string): string => {return out + template.slice(cursor)}+// The currency a locale implies when a template names only a locale, as in `currency: "en-GB"`.+const REGION_CURRENCIES: Record<string, string> = {+ US: 'USD',+ GB: 'GBP',+ CA: 'CAD',+ AU: 'AUD',+ NZ: 'NZD',+ IN: 'INR',+ JP: 'JPY',+ CH: 'CHF',+ SE: 'SEK',+ NO: 'NOK',+ DK: 'DKK',+ PL: 'PLN',+ BR: 'BRL',+ MX: 'MXN',+ ...Object.fromEntries(+ ['AT', 'BE', 'DE', 'ES', 'FI', 'FR', 'GR', 'IE', 'IT', 'LU', 'NL', 'PT'].map((region) => [region, 'EUR'])+ ),+}++// The languages a locale argument may name, with the region a bare language implies.+const LANGUAGE_REGIONS: Record<string, string> = {+ en: 'US',+ fr: 'FR',+ de: 'DE',+ es: 'ES',+ it: 'IT',+ nl: 'NL',+ pt: 'PT',+ fi: 'FI',+ sv: 'SE',+ da: 'DK',+ nb: 'NO',+ no: 'NO',+ pl: 'PL',+ ja: 'JP',+}+const LOCALE_ARGUMENT = /^([a-z]{2})(?:[-_]([a-z]{2}))?$/i+const CURRENCY_CODE = /^[a-z]{3}$/i++// Customer.io's `currency` takes `locale, code` (`"en", "EUR"`) or a locale alone (`"en-GB"`), and+// templates also pass a bare ISO code (`"USD"`), so all three forms resolve to a locale and a code.+// Arguments are checked against fixed patterns and tables, never parsed with Intl.Locale: a filter+// call runs to completion before the render deadline is checked, and exotic locale tags are slow to parse.+const resolveCurrencyFormat = (first: unknown, second: unknown): [string, string] | null => {+ if (first === undefined) {+ return ['en-US', 'USD']+ }+ if (typeof first !== 'string' || (second !== undefined && typeof second !== 'string')) {+ return null+ }+ if (second === undefined && CURRENCY_CODE.test(first)) {+ return ['en-US', first.toUpperCase()]+ }+ const locale = LOCALE_ARGUMENT.exec(first)+ const language = locale?.[1].toLowerCase()+ if (!locale || !language || !LANGUAGE_REGIONS[language]) {+ return null+ }+ const region = (locale[2] ?? LANGUAGE_REGIONS[language]).toUpperCase()+ const code =+ second === undefined ? REGION_CURRENCIES[region] : CURRENCY_CODE.test(second) ? second.toUpperCase() : null+ return code ? [`${language}-${region}`, code] : null+}++// Building a formatter costs far more than using one, so templates that repeat their arguments reuse it.+// Cleared when full, so tenant-chosen arguments can't grow it without bound.+const CURRENCY_FORMATTER_CACHE_LIMIT = 256+const currencyFormatters = new Map<string, Intl.NumberFormat | null>()++const currencyFormatter = (first: unknown, second: unknown): Intl.NumberFormat | null => {+ const format = resolveCurrencyFormat(first, second)+ if (!format) {+ return null+ }+ const key = format.join(' ')+ let formatter = currencyFormatters.get(key)+ if (formatter === undefined) {+ try {+ formatter = new Intl.NumberFormat(format[0], { style: 'currency', currency: format[1] })+ } catch {+ formatter = null+ }+ if (currencyFormatters.size >= CURRENCY_FORMATTER_CACHE_LIMIT) {+ currencyFormatters.clear()+ }+ currencyFormatters.set(key, formatter)+ }+ return formatter+}++// A value that isn't a number, or arguments that don't resolve, pass through unchanged, so a bad value+// stays visible instead of turning into "$0.00".+const formatCurrency = (value: unknown, first?: unknown, second?: unknown): unknown => {+ const amount = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN+ if (!Number.isFinite(amount)) {+ return value+ }+ return currencyFormatter(first, second)?.format(amount) ?? value+}+const createLiquid = (outputEscape: 'escape' | undefined): Liquid => {const liquid = new Liquid({outputEscape,@@ -99,6 +201,7 @@ const createLiquid = (outputEscape: 'escape' | undefined): Liquid => {throw new Error(`liquid filter ${name} is not supported`)})}+ liquid.registerFilter('currency', formatCurrency)return liquid}