Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .claude/rules/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Generic advice that doesn't apply here: configuring an element through its HTML
- **ARCH-17** `add(PaymentPlans)` returns `undefined`. `add(Modal)` returns `{ open, close }`, even when the container doesn't exist. A second `add()` on the same container replaces the widget. Why: integrations rely on these return values and on a second `add()` to refresh a widget. Check: unit tests.
- **ARCH-18** Every option keeps its default: `monochrome` is `true`, `locale` is `'en'`, `hideBorder` is `false`, and `transitionDelay` is 5500 ms, turns the animation off when negative, and becomes 1000 ms from 0 to 999 ms. Why: a merchant who sets no option keeps the behaviour they had. Check: unit tests.
- **ARCH-19** `onClose` and `onModalClose` receive DOM events with the four members that preact/compat adds: `persist()`, `isPropagationStopped()`, `isDefaultPrevented()` and `nativeEvent`. Why: merchant callbacks may call them. Check: unit tests.
- **ARCH-13** No exception reaches the merchant's page. A misconfiguration logs one console warning prefixed `[Alma widgets]`. Why: an error in the widget must never break the merchant's checkout. Check: unit tests and contract tests.
- **ARCH-13** No exception reaches the merchant's page. Each distinct failure logs one console warning prefixed `[Alma widgets]`, through `warnOnce`, so a message is never logged twice. Why: an error in the widget must never break the merchant's checkout, and the console stays readable. Check: unit tests and contract tests.
- **ARCH-25** Merchants change the widget only through the options of `add()`. The widget offers them no other hook: no `part` attribute, no slot, no custom property they can set, and no class or ID that the docs tell them to style. Why: the shadow root keeps merchant CSS out, so the widget's look stays ours to change in any release, and an option is a hook that every release keeps working. Check: review.
- **ARCH-08** An option, a callback, the event that a callback receives, or a tag may be added when it is optional and its default keeps the current behaviour. `documentation.md` describes it, and the release is a minor one. Removing or renaming one, or changing its type or default, needs a major release. Why: an integration keeps working across the releases of one major version. Check: review, and the unit tests of ARCH-16 to ARCH-18.

Expand Down
2 changes: 1 addition & 1 deletion .claude/rules/widgets.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Generic advice that doesn't apply here: the `@customElement` decorator, `CustomE
- **ARCH-25** Merchants change the widget only through the options of `add()`. The widget offers them no other hook: no `part` attribute, no slot, no custom property they can set, and no class or ID that the docs tell them to style. Why: the shadow root keeps merchant CSS out, so the widget's look stays ours to change in any release, and an option is a hook that every release keeps working. Check: review.
- **ARCH-08** An option, a callback, the event that a callback receives, or a tag may be added when it is optional and its default keeps the current behaviour. `documentation.md` describes it, and the release is a minor one. Removing or renaming one, or changing its type or default, needs a major release. Why: an integration keeps working across the releases of one major version. Check: review, and the unit tests of ARCH-16 to ARCH-18.
- **ARCH-09** No `new CustomEvent` and no `reflect: true`. A widget reaches the page only through the callbacks of its options. Why: an event or a reflected attribute adds to the contract with merchants. Check: review.
- **ARCH-13** No exception reaches the merchant's page. A misconfiguration logs one console warning prefixed `[Alma widgets]`. Why: an error in the widget must never break the merchant's checkout. Check: unit tests and contract tests.
- **ARCH-13** No exception reaches the merchant's page. Each distinct failure logs one console warning prefixed `[Alma widgets]`, through `warnOnce`, so a message is never logged twice. Why: an error in the widget must never break the merchant's checkout, and the console stays readable. Check: unit tests and contract tests.
- **ARCH-19** `onClose` and `onModalClose` receive DOM events with the four members that preact/compat adds: `persist()`, `isPropagationStopped()`, `isDefaultPrevented()` and `nativeEvent`. Why: merchant callbacks may call them. Check: unit tests.

## Code
Expand Down
53 changes: 44 additions & 9 deletions src/domain/api/get-eligibility.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,32 +139,67 @@ describe('getEligibility', () => {
throw securityError
}

it('fails with one warning and sends no request when the read throws', async () => {
it('warns once and sends the request when the read throws', async () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(throwing)
const setItem = vi.spyOn(Storage.prototype, 'setItem')
vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible)

expect(await getEligibility(input())).toEqual(FAILED)
expect(fetchFromApi).not.toHaveBeenCalled()
expect(await getEligibility(input())).toEqual({
status: StatusResponse.SUCCESS,
plans: mockPlansAllEligible,
})
expect(fetchFromApi).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/^\[Alma widgets\] /), securityError)
expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be read'), securityError)
// The write is still tried, and works.
expect(setItem).toHaveBeenCalledTimes(1)
expect(sessionStorage.length).toBe(1)
})

it('warns about the read and about the write when the whole storage is blocked', async () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(throwing)
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(throwing)
vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible)

expect((await getEligibility(input())).status).toBe(StatusResponse.SUCCESS)
expect(warn).toHaveBeenCalledTimes(2)
expect(warn).toHaveBeenNthCalledWith(
1,
expect.stringContaining('could not be read'),
securityError,
)
expect(warn).toHaveBeenNthCalledWith(
2,
expect.stringContaining('could not be cached'),
securityError,
)
})

it('fails with one warning when the write throws, after one request', async () => {
it('warns once and returns the plans when the write throws', async () => {
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new DOMException('The quota has been exceeded.', 'QuotaExceededError')
})
vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible)

expect(await getEligibility(input())).toEqual(FAILED)
expect(await getEligibility(input())).toEqual({
status: StatusResponse.SUCCESS,
plans: mockPlansAllEligible,
})
expect(fetchFromApi).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('could not be cached'),
expect.any(DOMException),
)
})

it('fails with one warning when the delete of an expired entry throws', async () => {
it('warns once and sends the request when the delete of an expired entry throws', async () => {
seed({ value: mockPlansAllEligible, timestamp: Date.now() - HOUR })
vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(throwing)
vi.mocked(fetchFromApi).mockResolvedValue(mockPlansAllEligible)

expect(await getEligibility(input())).toEqual(FAILED)
expect(fetchFromApi).not.toHaveBeenCalled()
expect((await getEligibility(input())).status).toBe(StatusResponse.SUCCESS)
expect(fetchFromApi).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledTimes(1)
})
})
Expand Down
9 changes: 5 additions & 4 deletions src/domain/api/get-eligibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const requestEligibility = async (input: EligibilityInput): Promise<EligibilityR
return { status: StatusResponse.SUCCESS, plans: response }
}

// Cache first. Never rejects. A sent request always finishes and writes the cache.
// Cache first. Never rejects. A sent request always finishes and tries to write the cache.
export const getEligibility = async (input: EligibilityInput): Promise<EligibilityResult> => {
const { purchaseAmount, configPlans } = input
// The merchant's options arrive unchecked.
Expand All @@ -60,11 +60,12 @@ export const getEligibility = async (input: EligibilityInput): Promise<Eligibili
return fail('The eligibility cache key could not be built.', error)
}

let cached: EligibilityPlan[] | null
// The cache only saves a request: a storage error never hides the plans.
let cached: EligibilityPlan[] | null = null
try {
cached = readCache(key)
} catch (error) {
return fail('The eligibility cache could not be read or cleaned.', error)
warnOnce('The eligibility cache could not be read or cleaned.', error)
}
if (cached) {
return { status: StatusResponse.SUCCESS, plans: cached }
Expand All @@ -78,7 +79,7 @@ export const getEligibility = async (input: EligibilityInput): Promise<Eligibili
try {
setCache(key, result.plans)
} catch (error) {
return fail('The eligibility response could not be cached.', error)
warnOnce('The eligibility response could not be cached.', error)
}

return result
Expand Down
17 changes: 10 additions & 7 deletions tests/integration/contract/failures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,12 @@ const observe = async ({
}

/**
* No error reaches the page, and the console gets at most one warning, prefixed
* `[Alma widgets]`.
* No error reaches the page, and the console gets at most one warning per distinct failure,
* prefixed `[Alma widgets]`. A case with one failure keeps the default of one.
*/
const expectNoEscape = ({ escaped, warnings }: Outcome) => {
const expectNoEscape = ({ escaped, warnings }: Outcome, maxWarnings = 1) => {
expect(escaped).toEqual([])
expect(warnings.length).toBeLessThanOrEqual(1)
expect(warnings.length).toBeLessThanOrEqual(maxWarnings)
warnings.forEach(([message]) => {
expect(String(message).startsWith('[Alma widgets]')).toBe(true)
})
Expand Down Expand Up @@ -174,7 +174,7 @@ describe('API failures', () => {
})

describe('storage failures', () => {
it('shows no plan when the sessionStorage getter throws', async () => {
it('renders the plans and caches nothing when the sessionStorage getter throws', async () => {
const outcome = await observe({
before: () =>
Object.defineProperty(globalThis, 'sessionStorage', {
Expand All @@ -185,8 +185,11 @@ describe('storage failures', () => {
}),
})

expect(outcome.options).toBe(0)
expectNoEscape(outcome)
expect(outcome.options).toBe(3)
expect(outcome.requests).toBe(1)
expect(outcome.keys).toEqual([])
// The read and the write fail for the same reason, and each logs its own warning.
expectNoEscape(outcome, 2)
})
})

Expand Down