Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build-lint-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@ jobs:
- name: Lint
run: yarn lint

- name: Test
run: yarn test

- name: Build
run: yarn build
5 changes: 5 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export default [
{ files: ["**/*.{js,mjs,cjs,ts}"] },
{ files: ["**/*.js"], languageOptions: { sourceType: "script" } },
{ languageOptions: { globals: globals.browser } },
// Test files and Vitest config run in Node, not the browser.
{
files: ["test/**/*.ts", "vitest.config.ts"],
languageOptions: { globals: { ...globals.node } },
},
{ ignores: ["dist/*", "node_modules/*", "src/polyfills/*"] },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
Expand Down
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
{
"name": "processout.js",
"version": "1.9.8",
"version": "1.9.9",
"description": "ProcessOut.js is a JavaScript library for ProcessOut's payment processing API.",
"scripts": {
"build:processout": "tsc -p src/processout && uglifyjs --compress --keep-fnames --ie8 dist/processout.js -o dist/processout.js",
"build:modal": "tsc -p src/modal && uglifyjs --compress --keep-fnames --ie8 dist/modal.js -o dist/modal.js",
"build:test": "yarn build:processout & yarn build:modal && yarn append-debug-mode && yarn append-version",
"build": "yarn build:processout & yarn build:modal && yarn append-version",
"verify": "yarn lint & yarn build",
"test": "vitest run",
"test:watch": "vitest",
"verify": "yarn lint & yarn build && yarn test",
Comment thread
roshan-gorasia-cko marked this conversation as resolved.
"lint": "eslint .",
"lint:fix": "eslint --fix .",
"format": "prettier --ignore-path .gitignore --write \"**/*.+(ts|json)\"",
Expand Down Expand Up @@ -35,7 +37,8 @@
"typescript": "^5.7.3",
"typescript-eslint": "^8.23.0",
"uglify-js": "3.8.0",
"vite": "^6.1.0"
"vite": "^6.1.0",
"vitest": "^3"
},
"lint-staged": {
"*.{ts,json}": "eslint --cache --fix --no-warn-ignored"
Expand Down
4 changes: 2 additions & 2 deletions src/apm/elements/phone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ module ProcessOut {
export const Phone = ({ dialing_codes, name, oninput, onblur, disabled, label, errored, className, value, id, ...props }: PhoneProps) => {
// Use StateManager for internal state management
const { state, setState } = useComponentState({
dialing_code: value && value.dialing_code || dialing_codes[0] && dialing_codes[0].value || '',
dialing_code: value && value.dialing_code || getDefaultDialingCode(dialing_codes),
number: value && value.value || '',
iso: ''
});

// Load libphonenumber and handle all state initialization in callback
ContextImpl.context.page.loadScript('libphonenumber', 'https://cdnjs.cloudflare.com/ajax/libs/google-libphonenumber/3.2.42/libphonenumber.min.js', () => {
let dialingCode = state.dialing_code || dialing_codes[0].value;
let dialingCode = state.dialing_code || getDefaultDialingCode(dialing_codes);
let phoneNumber = state.number || '';
let iso = state.iso;

Expand Down
32 changes: 32 additions & 0 deletions src/apm/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,38 @@ module ProcessOut {
return formatter.format(parseFloat(amount));
}

/**
* Extract the region subtag from the browser locale, e.g. "en-GB" -> "GB",
* "zh-Hant-TW" -> "TW". Returns "" when there is no region subtag (e.g. "en").
*/
export function getBrowserRegion(): string {
// `userLanguage` is a legacy IE-only property that isn't on the standard
// Navigator type, so widen the type just enough to read it as a fallback.
const nav = navigator as Navigator & { userLanguage?: string };
const locale: string = (nav.languages && nav.languages[0]) || nav.language || nav.userLanguage || '';
const parts = locale.split('-');
// Skip the language (and any script) subtag; the region is a 2-letter subtag.
for (let i = 1; i < parts.length; i++) {
if (/^[a-z]{2}$/i.test(parts[i])) {
return parts[i].toUpperCase();
}
}
return '';
}

/**
* Pick a default dialing code for the phone field. Prefers the code whose
* region matches the browser locale, falling back to the first available code.
*/
export function getDefaultDialingCode(dialing_codes: Array<{ region_code: string, value: string }>): string {
if (!dialing_codes || dialing_codes.length === 0) {
return '';
}
const region = getBrowserRegion();
const match = region && dialing_codes.filter(c => c.region_code && c.region_code.toUpperCase() === region)[0];
return (match || dialing_codes[0]).value;
Comment thread
roshan-gorasia-cko marked this conversation as resolved.
}

/**
* Simple hash function for content comparison (djb2 algorithm)
* @param str - String to hash
Expand Down
2 changes: 1 addition & 1 deletion src/apm/views/NextSteps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ module ProcessOut {
break;
case 'phone':
acc[param.key] = {
dialing_code: param.dialing_codes[0].value,
dialing_code: getDefaultDialingCode(param.dialing_codes),
value: '',
}
break;
Expand Down
88 changes: 88 additions & 0 deletions test/apm/locale.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest"
import { loadApmUtils, FakeNavigator } from "../support/loadNamespace"

function getBrowserRegion(navigator: FakeNavigator): string {
return loadApmUtils(navigator).getBrowserRegion()
}

type DialingCode = { region_code: string; value: string }

function getDefaultDialingCode(
dialingCodes: DialingCode[],
navigator: FakeNavigator = {},
): string {
return loadApmUtils(navigator).getDefaultDialingCode(dialingCodes)
}

describe("getBrowserRegion", () => {
it("extracts the region subtag from a language-region locale", () => {
expect(getBrowserRegion({ language: "en-GB" })).toBe("GB")
expect(getBrowserRegion({ language: "fr-CA" })).toBe("CA")
})

it("returns an empty string when there is no region subtag", () => {
expect(getBrowserRegion({ language: "en" })).toBe("")
expect(getBrowserRegion({ language: "fr" })).toBe("")
})

it("skips a script subtag and picks the region", () => {
expect(getBrowserRegion({ language: "zh-Hant-TW" })).toBe("TW")
})

it("ignores non-ISO (numeric UN M49) regions", () => {
// "es-419" (Latin America) has no 2-letter ISO region to match against.
expect(getBrowserRegion({ language: "es-419" })).toBe("")
})

it("uppercases the region regardless of source casing", () => {
expect(getBrowserRegion({ language: "en-gb" })).toBe("GB")
})

it("prefers navigator.languages[0] over navigator.language", () => {
expect(
getBrowserRegion({ languages: ["en-GB", "fr-FR"], language: "de-DE" }),
).toBe("GB")
})

it("falls back to userLanguage when language is empty", () => {
expect(getBrowserRegion({ language: "", userLanguage: "en-US" })).toBe("US")
})

it("returns an empty string when no locale is available", () => {
expect(getBrowserRegion({})).toBe("")
})
})

describe("getDefaultDialingCode", () => {
const codes: DialingCode[] = [
{ region_code: "AF", value: "+93" },
{ region_code: "GB", value: "+44" },
{ region_code: "US", value: "+1" },
]

it("picks the code whose region matches the browser locale", () => {
expect(getDefaultDialingCode(codes, { language: "en-GB" })).toBe("+44")
expect(getDefaultDialingCode(codes, { language: "en-US" })).toBe("+1")
})

it("matches region codes case-insensitively", () => {
expect(
getDefaultDialingCode(
[{ region_code: "gb", value: "+44" }],
{ language: "en-GB" },
),
).toBe("+44")
})

it("falls back to the first code when the locale has no region", () => {
expect(getDefaultDialingCode(codes, { language: "en" })).toBe("+93")
})

it("falls back to the first code when no region matches", () => {
expect(getDefaultDialingCode(codes, { language: "fr-FR" })).toBe("+93")
})

it("returns an empty string for an empty list", () => {
expect(getDefaultDialingCode([], { language: "en-GB" })).toBe("")
})
})
58 changes: 58 additions & 0 deletions test/support/loadNamespace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
import * as ts from "typescript"

/**
* The SDK sources use the TypeScript internal-namespace style
* (`module ProcessOut { export function ... }`) and are shipped as a single
* global bundle via `tsc --outFile`. That means they expose nothing to ES
* module `import`, so we cannot import the helpers directly.
*
* Instead, we transpile the real source file and evaluate it in an isolated
* function scope, returning the resulting `ProcessOut` namespace object. A
* `navigator` implementation is injected so locale-dependent helpers are
* deterministic regardless of the machine running the tests.
*
* This exercises the exact source that ships — no re-implementation, no
* test-only hooks baked into the production files.
*/

const compiledCache = new Map<string, string>()

function compile(relativePath: string): string {
const absolute = resolve(process.cwd(), relativePath)
if (!compiledCache.has(absolute)) {
const source = readFileSync(absolute, "utf8")
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2020,
},
})
compiledCache.set(absolute, outputText)
}
return compiledCache.get(absolute)!
}

export interface FakeNavigator {
language?: string
languages?: string[]
userLanguage?: string
}

/**
* Load `src/apm/utils.ts` and return its `ProcessOut` namespace, with the
* given `navigator` shim visible to the module's code.
*/
export function loadApmUtils(navigator: FakeNavigator = {}): Record<string, any> {
const js = compile("src/apm/utils.ts")
const moduleShim = { exports: {} as Record<string, any> }
const run = new Function(
"module",
"exports",
"navigator",
`${js}\nmodule.exports = ProcessOut;`,
)
run(moduleShim, moduleShim.exports, navigator)
return moduleShim.exports
}
8 changes: 8 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config"

export default defineConfig({
test: {
include: ["test/**/*.test.ts"],
environment: "node",
},
})
Loading
Loading