Skip to content

Commit

Permalink
fix(quantic): headless quantic bundle updated to support sending RGA …
Browse files Browse the repository at this point in the history
…feedback when LWS is disabled (#4781)

## [SFINT-5858](https://coveord.atlassian.net/browse/SFINT-5858)

We have noticed couple Salesforce specific issue, with the RGA
evaluations request sent to the Answer API to evaluate answers,
We previously fixed a similar issue in Salesforce environment where the
security setting Lightning Web Security (LWS) was enabled and now we
have noticed couple other issue in Salesforce where the security setting
Lightning Web Security (LWS) is enabled.


### 1. First issue:
The headers constructor is not supported in Salesforce where LWS is
disabled:
 
<img width="1727" alt="Screenshot 2024-12-06 at 10 25 12 AM"
src="https://github.com/user-attachments/assets/bf866b37-b681-4cf0-8e09-4de9600209a3">

RTK Query uses the Headers constructor to build its requests so the
absence of the Headers interface caused an issue,
This has been fixed by injecting the
[headears-polyfill](https://www.npmjs.com/package/headers-polyfill) in
the Headless bundle built for Quantic.

### 2. Second issue:
We have noticed the following behaviour when using `Fetch` in an
environment where LWS is disabled:
doing:
```javascript
const request = new Request("https://example.com/", {
  method: 'POST',
  headers: new Headers({
    'Content-Type': 'application/json',
  }),
  body: JSON.stringify({
    title: 'foo',
  }),
});
const response = await fetch(request);
```
Does not work ❌
but the following:
```javascript
const url = "https://example.com/";
const options = {
  method: 'POST',
    headers: new Headers({
    'Content-Type': 'application/json',
  }),
    body: JSON.stringify({
    title: 'foo',
  }),
};
const response =  await fetch(url, options)
```
Does work ✅

We think that SF fails to understand the Request object that's why the
syntax `fetch(request)` doesn't work but `fetch(url, options)` does
work.

Unfortunately, Redux RTK was using the first way of calling fetch, with
a Request object, which was not working in our SF env.
A workaround I found to surpass this is explained in the following:

## Workaround explanation 

in the following lines we call `fetchBaseQuery`, it's the base mechanism
provided by RTK Query to send requests:
https://github.com/coveo/ui-kit/blob/79433ed6fb33bee24e31c5d1bf2f75c63fb9f2ce/packages/headless/src/api/knowledge/answer-slice.ts#L41-L43
it accepts a parameter fetchFn that allows you run a custom fn function,
this fetchFn function receives a Request object as parameter,
the default fetchFn is defined as :
```
(request: Request) => {fetch(request)}
```
To update this behaviour I can pass a custom fetchFn that does this
instead only for the Headless Quantic bundle:
```
(request: Request) => {
        const url = request.url;
        const options = {
          method: request.method,
          headers: request.headers,
          body: request.body,
          ...
        }; 
     fetch(url, options)
  }
```
I will be calling fetchBaseQuery using my custom fetch function:
```
    const data = fetchBaseQuery({
      baseUrl: `${platformEndpoint}/rest/organizations/${organizationId}/answer/v1/configs/${answerConfigurationId}`,
      fetchFn: myCustomFetchFn
    })(updatedArgs, api, extraOptions);
```

This way we make sure that RTK Query calls the fetch function in a way
that will in Salesforce.
I modified our es build script to do this code modification when
building the Headless bundle made to work for Quantic in Salesforce.


### Before

https://github.com/user-attachments/assets/ad9bee25-88b1-46df-b13c-f9ec39a2d6f5


### After


https://github.com/user-attachments/assets/0fce042b-cd51-41af-95f8-819012ffcf57



 


[SFINT-5858]:
https://coveord.atlassian.net/browse/SFINT-5858?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
  • Loading branch information
mmitiche authored Jan 22, 2025
1 parent a331579 commit e84d61b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 5 deletions.
5 changes: 2 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 35 additions & 2 deletions packages/headless/esbuild.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,38 @@ const quanticUmd = Object.entries(quanticUseCaseEntries).map((entry) => {

const globalName = getUmdGlobalName(useCase);

const target = /}\)\(updatedArgs, api, extraOptions\);/g;

const replacement = `
fetchFn: (request: Request | String) => {
if (request instanceof String) {
throw new Error("The provided 'request' must be a Request object.");
}
const url = request.url;
const options: { [key: string]: any } = {};
[
'method',
'headers',
'body',
'mode',
'credentials',
'cache',
'redirect',
'referrer',
'referrerPolicy',
'integrity',
'keepalive',
'signal',
].forEach((key) => {
options[key] = request[key as keyof Request];
});
options.duplex = 'half';
return fetch(url, options);
},
})(updatedArgs,{...api, signal: null},extraOptions);
`;

return buildBrowserConfig(
{
entryPoints: [entryPoint],
Expand All @@ -167,6 +199,7 @@ const quanticUmd = Object.entries(quanticUseCaseEntries).map((entry) => {
},
external: ['crypto'],
inject: [
'ponyfills/headers-shim.js',
'ponyfills/global-this-shim.js',
'ponyfills/abortable-fetch-shim.js',
'../../node_modules/navigator.sendbeacon/dist/navigator.sendbeacon.cjs.js',
Expand All @@ -175,8 +208,8 @@ const quanticUmd = Object.entries(quanticUseCaseEntries).map((entry) => {
umdWrapper({libraryName: globalName}),
codeReplacerPlugin(
'src/api/knowledge/answer-slice.ts',
'(updatedArgs, api, extraOptions)',
'(updatedArgs,{...api, signal: null},extraOptions)'
target,
replacement
),
],
},
Expand Down
1 change: 1 addition & 0 deletions packages/headless/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@
"dayjs": "1.11.13",
"exponential-backoff": "3.1.1",
"fast-equals": "5.0.1",
"headers-polyfill": "4.0.3",
"navigator.sendbeacon": "0.0.20",
"node-abort-controller": "3.1.1",
"pino": "9.6.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/headless/ponyfills/headers-shim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {Headers} from 'headers-polyfill';

export {Headers};

0 comments on commit e84d61b

Please sign in to comment.