guardian / guardian/dotcom-rendering

[Bug]: inital window.guardian can be incorrectly typed due to serialization

Open
#15,564 1 comment 0 reactions 1 assignee Claimed by @Jakeii View on GitHub
Dominant language
TypeScript
Stars
274
Forks
34
Avg merge
2d 22h
Merged PRs (30d)
121

Description

The default value of `window.guardian` that's injected into the page goes through `JSON.strigify`, this strips any incompatible keyvalues - namely functions and keys with `undefined` values.

This is somewhat unexpected! [There are a few functions stubbed in `createGuardian`](https://github.com/guardian/dotcom-rendering/blob/main/dotcom-rendering/src/model/guardian.ts#L181-L189), that do not actually get on to the page, until they're later added by client side code.

this
```ts
{
...
modules: {
// This is a stub for the sentry module, which is later initialised on the client with the `reportError` function.
sentry: {
reportError: () => {},
},
// This is a stub for the abTests module, which is later initialised on the client with the `getParticipations`, `isUserInTest` and `isUserInTestGroup` functions.
abTests: {
getParticipations: () => ({}),
isUserInTest: () => false,
isUserInTestGroup: () => false,
},
},
}
```
becomes this when stringified:
```
{"modules":{"sentry":{},"abTests":{}}}`
```

This led to a hard to track bug in commercial where we expected `window.guardian.modules.abTests` to be
```
{
getParticipations: () => ({}),
isUserInTest: () => ({}),
isUserInTestGroup: () => ({}),
} || undefined
```
but `{}` wasn't expected!

[`type-fest` has some types to check for this sort of thing](https://github.com/sindresorhus/type-fest#json), perhaps they could be incorporated to ensure that the returntype of `createGuardian` is safely serializable?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.