@servicetitan/web-components 40.2.2 → 40.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/common.d.ts +22 -6
  2. package/dist/common.d.ts.map +1 -1
  3. package/dist/common.js +7 -2
  4. package/dist/common.js.map +1 -1
  5. package/dist/globals.d.ts +9 -7
  6. package/dist/globals.d.ts.map +1 -1
  7. package/dist/globals.js +17 -6
  8. package/dist/globals.js.map +1 -1
  9. package/dist/loader.d.ts.map +1 -1
  10. package/dist/loader.js +26 -24
  11. package/dist/loader.js.map +1 -1
  12. package/dist/patches/kendo-scrollbar-width/get-mfe-maybe-uses-kendo-grid.d.ts +3 -0
  13. package/dist/patches/kendo-scrollbar-width/get-mfe-maybe-uses-kendo-grid.d.ts.map +1 -0
  14. package/dist/patches/kendo-scrollbar-width/get-mfe-maybe-uses-kendo-grid.js +12 -0
  15. package/dist/patches/kendo-scrollbar-width/get-mfe-maybe-uses-kendo-grid.js.map +1 -0
  16. package/dist/patches/kendo-scrollbar-width/index.d.ts +3 -0
  17. package/dist/patches/kendo-scrollbar-width/index.d.ts.map +1 -0
  18. package/dist/patches/kendo-scrollbar-width/index.js +4 -0
  19. package/dist/patches/kendo-scrollbar-width/index.js.map +1 -0
  20. package/dist/patches/kendo-scrollbar-width/set-kendo-scrollbar-width.d.ts +2 -0
  21. package/dist/patches/kendo-scrollbar-width/set-kendo-scrollbar-width.d.ts.map +1 -0
  22. package/dist/patches/kendo-scrollbar-width/set-kendo-scrollbar-width.js +26 -0
  23. package/dist/patches/kendo-scrollbar-width/set-kendo-scrollbar-width.js.map +1 -0
  24. package/dist/register.d.ts.map +1 -1
  25. package/dist/register.js +30 -7
  26. package/dist/register.js.map +1 -1
  27. package/dist/use-host-shared-dependencies.d.ts +7 -0
  28. package/dist/use-host-shared-dependencies.d.ts.map +1 -0
  29. package/dist/use-host-shared-dependencies.js +17 -0
  30. package/dist/use-host-shared-dependencies.js.map +1 -0
  31. package/dist/use-prefetch.d.ts +2 -3
  32. package/dist/use-prefetch.d.ts.map +1 -1
  33. package/dist/use-prefetch.js +18 -12
  34. package/dist/use-prefetch.js.map +1 -1
  35. package/dist/utils/get-bundle-info.d.ts +7 -5
  36. package/dist/utils/get-bundle-info.d.ts.map +1 -1
  37. package/dist/utils/get-bundle-info.js +5 -3
  38. package/dist/utils/get-bundle-info.js.map +1 -1
  39. package/dist/utils/get-mfe-has-compatible-launchdarkly-version.d.ts +6 -6
  40. package/dist/utils/get-mfe-has-compatible-launchdarkly-version.d.ts.map +1 -1
  41. package/dist/utils/get-mfe-has-compatible-launchdarkly-version.js +7 -7
  42. package/dist/utils/get-mfe-has-compatible-launchdarkly-version.js.map +1 -1
  43. package/dist/utils/validate-bundle-info.d.ts +5 -5
  44. package/dist/utils/validate-bundle-info.d.ts.map +1 -1
  45. package/dist/utils/validate-bundle-info.js +6 -5
  46. package/dist/utils/validate-bundle-info.js.map +1 -1
  47. package/dist/utils/web-component.d.ts +4 -4
  48. package/dist/utils/web-component.d.ts.map +1 -1
  49. package/dist/utils/web-component.js +27 -11
  50. package/dist/utils/web-component.js.map +1 -1
  51. package/package.json +18 -14
  52. package/src/common.ts +27 -6
  53. package/src/globals.ts +26 -8
  54. package/src/loader.tsx +32 -36
  55. package/src/patches/kendo-scrollbar-width/get-mfe-maybe-uses-kendo-grid.ts +11 -0
  56. package/src/patches/kendo-scrollbar-width/index.ts +2 -0
  57. package/src/patches/kendo-scrollbar-width/set-kendo-scrollbar-width.ts +27 -0
  58. package/src/register.tsx +35 -8
  59. package/src/use-host-shared-dependencies.ts +26 -0
  60. package/src/use-prefetch.ts +38 -40
  61. package/src/utils/get-bundle-info.ts +11 -8
  62. package/src/utils/get-mfe-has-compatible-launchdarkly-version.ts +7 -7
  63. package/src/utils/validate-bundle-info.ts +9 -8
  64. package/src/utils/web-component.tsx +39 -16
  65. package/dist/contexts/tests/mfe-data-context.test.d.ts +0 -2
  66. package/dist/contexts/tests/mfe-data-context.test.d.ts.map +0 -1
  67. package/dist/contexts/tests/mfe-data-context.test.js +0 -60
  68. package/dist/contexts/tests/mfe-data-context.test.js.map +0 -1
  69. package/dist/contexts/tests/mfe-metadata-context.test.d.ts +0 -2
  70. package/dist/contexts/tests/mfe-metadata-context.test.d.ts.map +0 -1
  71. package/dist/contexts/tests/mfe-metadata-context.test.js +0 -41
  72. package/dist/contexts/tests/mfe-metadata-context.test.js.map +0 -1
  73. package/src/__mocks__/expect-styles-in-dom.ts +0 -11
  74. package/src/__mocks__/index.ts +0 -3
  75. package/src/__mocks__/register-anvil2-harness.tsx +0 -49
  76. package/src/__mocks__/register-component.tsx +0 -20
  77. package/src/__mocks__/test-component.tsx +0 -41
  78. package/src/__tests__/common.test.ts +0 -204
  79. package/src/__tests__/delayed.test.tsx +0 -49
  80. package/src/__tests__/event-bus-types.test.ts +0 -620
  81. package/src/__tests__/event-bus.test.ts +0 -240
  82. package/src/__tests__/get-value-for-environment.test.ts +0 -95
  83. package/src/__tests__/globals.test.ts +0 -16
  84. package/src/__tests__/headless-loader.test.tsx +0 -123
  85. package/src/__tests__/history-manager.test.ts +0 -111
  86. package/src/__tests__/loader.test.tsx +0 -1178
  87. package/src/__tests__/register-anvil2-optional.test.tsx +0 -32
  88. package/src/__tests__/register-anvil2.test.tsx +0 -80
  89. package/src/__tests__/register-headless.test.tsx +0 -97
  90. package/src/__tests__/register-legacy-root.test.tsx +0 -38
  91. package/src/__tests__/register.test.tsx +0 -247
  92. package/src/__tests__/use-prefetch.test.tsx +0 -235
  93. package/src/contexts/tests/mfe-data-context.test.tsx +0 -64
  94. package/src/contexts/tests/mfe-metadata-context.test.tsx +0 -34
  95. package/src/css-injector/__tests__/mfe-style-registry.test.ts +0 -163
  96. package/src/css-injector/__tests__/with-css-injector.test.tsx +0 -128
  97. package/src/utils/__tests__/get-cached-metadata.test.ts +0 -94
  98. package/src/utils/__tests__/get-mfe-has-compatible-launchdarkly-version.test.ts +0 -54
  99. package/src/utils/__tests__/get-mfe-supports-rerendering.test.ts +0 -99
  100. package/src/utils/__tests__/get-mfe-supports-versioned-ld-client.test.ts +0 -38
  101. package/src/utils/__tests__/is-versioned-url.test.ts +0 -18
  102. package/src/utils/__tests__/load-scripts.test.ts +0 -171
  103. package/src/utils/__tests__/supports-prefetch.test.ts +0 -27
  104. package/src/utils/__tests__/ttl-cache.test.ts +0 -98
@@ -1,1178 +0,0 @@
1
- import { LD_SERVICE_TOKEN } from '@servicetitan/launchdarkly-service';
2
- import { Log } from '@servicetitan/log-service';
3
- import { Provider, ProviderProps } from '@servicetitan/react-ioc';
4
- import { ExposedDependencies, getVersionMismatches } from '@servicetitan/startup-utils';
5
- import '@testing-library/jest-dom';
6
- import { act, render, screen, waitFor } from '@testing-library/react';
7
- import { FC, ReactNode, RefObject, useEffect, useRef } from 'react';
8
- import * as common from '../common';
9
- import {
10
- EXPOSED_DEPENDENCIES_TOKEN,
11
- EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
12
- Entries,
13
- ExposedInstanceDependencies,
14
- } from '../common';
15
- import { EVENT_BUS_TOKEN } from '../event-bus';
16
- import { HistoryManager } from '../history-manager';
17
- import { Loader, LoaderProps, UnrestrictedLoaderProps } from '../loader';
18
- import { Metadata } from '../types';
19
- import { getMFEHasCompatibleLaunchDarklyVersion } from '../utils/get-mfe-has-compatible-launchdarkly-version';
20
- import { getMFEHasUniqueChunkNamespace } from '../utils/get-mfe-has-unique-chunk-namespace';
21
- import { getMFESupportsVersionedLDClient } from '../utils/get-mfe-supports-versioned-ld-client';
22
-
23
- jest.mock('@servicetitan/startup-utils', () => ({
24
- getVersionMismatches: jest.fn(),
25
- }));
26
- jest.mock('../utils/get-mfe-has-compatible-launchdarkly-version');
27
- jest.mock('../utils/get-mfe-has-unique-chunk-namespace');
28
- jest.mock('../utils/get-mfe-supports-versioned-ld-client');
29
-
30
- describe('[web-components] Loader', () => {
31
- const localHosts = ['localhost', '127.0.0.1'];
32
- const baseUrl = 'http://unpkg.servicetitan.com/mfe';
33
- const baseName = 'mfe-component';
34
- const WEB_COMPONENT_NAME = `${baseName}-abc123`;
35
- let webComponentState: Partial<Entries>;
36
- let webComponent: WebComponent | undefined;
37
- class WebComponent extends HTMLElement {
38
- provide = (entries: Entries) => {
39
- // eslint-disable-next-line @typescript-eslint/no-this-alias
40
- webComponent = this;
41
- for (const [key, value] of Object.entries(entries)) {
42
- /*
43
- * set values to external state so that we can call or
44
- * check any of the values in the test
45
- */
46
- webComponentState[key as keyof Entries] = value;
47
- }
48
- };
49
- }
50
-
51
- let props: LoaderProps<any>;
52
- let onloadRef: Function | null;
53
- let onerrorRef: Function | null;
54
- let singletons: ProviderProps['singletons'];
55
- let getJsonMockFns: Record<string, Function>;
56
-
57
- let metadata: Metadata;
58
-
59
- beforeAll(() => {
60
- // register web component in order to test the `provide` method
61
- window.customElements.define(WEB_COMPONENT_NAME, WebComponent);
62
-
63
- /*
64
- * mock <script>'s onload/onerror so that we can call them directly from the test,
65
- * because they won't call themselves in the test environment
66
- */
67
- Object.defineProperty(HTMLScriptElement.prototype, 'onload', {
68
- get() {
69
- return this._onload;
70
- },
71
- set(onload: Function) {
72
- onloadRef = onload;
73
- this._onload = onload;
74
- },
75
- });
76
- Object.defineProperty(HTMLScriptElement.prototype, 'onerror', {
77
- get() {
78
- return this._onerror;
79
- },
80
- set(onerror: Function) {
81
- onerrorRef = onerror;
82
- this._onerror = onerror;
83
- },
84
- });
85
- });
86
-
87
- function setStartupVersion(version: string | undefined) {
88
- metadata.bundledWith = version ? { '@servicetitan/startup': version } : undefined;
89
- }
90
-
91
- function initializeGetJsonMockFns(url = baseUrl) {
92
- getJsonMockFns = {
93
- [`${url}/dist/metadata.json`]: () => {
94
- return Promise.resolve({
95
- data: metadata,
96
- headers: {} as Headers,
97
- url,
98
- });
99
- },
100
- };
101
- }
102
-
103
- beforeEach(() => {
104
- jest.resetAllMocks();
105
- document.querySelectorAll('script').forEach(script => script.remove());
106
-
107
- webComponentState = {};
108
- webComponent = undefined;
109
- metadata = {
110
- name: WEB_COMPONENT_NAME,
111
- version: `0.0.0-test-abc123`,
112
- sharedDependencies: {},
113
- dependencies: {},
114
- entrypoints: {
115
- full: {
116
- css: ['full.css'],
117
- js: ['full.js'],
118
- },
119
- light: {
120
- css: ['light.css'],
121
- js: ['light.js'],
122
- },
123
- },
124
- };
125
- setStartupVersion('27.2.0');
126
- props = { src: baseUrl, cache: false };
127
- onloadRef = null;
128
- onerrorRef = null;
129
- singletons = [];
130
- initializeGetJsonMockFns();
131
-
132
- jest.spyOn(common, 'getJson').mockImplementation((url, _) => {
133
- if (getJsonMockFns[url] === undefined) {
134
- throw new Error(`Unexpected getJson call with url: ${url}`);
135
- }
136
- return getJsonMockFns[url]();
137
- });
138
- jest.mocked(getMFEHasCompatibleLaunchDarklyVersion).mockReturnValue(true);
139
- jest.mocked(getVersionMismatches).mockReturnValue(undefined);
140
- jest.mocked(getMFEHasUniqueChunkNamespace).mockReturnValue(true);
141
- jest.mocked(getMFESupportsVersionedLDClient).mockReturnValue(false);
142
- });
143
-
144
- const Root = () => (
145
- <Provider singletons={singletons}>
146
- <Loader {...props} />
147
- </Provider>
148
- );
149
-
150
- function subject() {
151
- return render(<Root />);
152
- }
153
-
154
- async function waitForScriptLoad() {
155
- await waitFor(() => expect(onloadRef).not.toBeNull());
156
- act(() => {
157
- onloadRef!();
158
- });
159
- }
160
-
161
- test('renders default loading fallback', async () => {
162
- subject();
163
-
164
- await waitFor(() => expect(screen.getByText('Loading...')).toBeInTheDocument());
165
- });
166
-
167
- function expectPreservesComponentState(rerender: (ui: ReactNode) => any, action?: () => void) {
168
- expect(common.getJson).toHaveBeenCalledTimes(1);
169
-
170
- action?.();
171
- rerender(<Root />);
172
-
173
- expect(common.getJson).toHaveBeenCalledTimes(1);
174
- }
175
-
176
- function itRendersErrorFallback(triggerFailure?: () => void | Promise<void>) {
177
- beforeEach(() => {
178
- jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress error boundary logging
179
- });
180
-
181
- test('renders default error fallback', async () => {
182
- subject();
183
- await triggerFailure?.();
184
-
185
- await waitFor(() =>
186
- expect(screen.getByText('Something went wrong')).toBeInTheDocument()
187
- );
188
- });
189
-
190
- describe.each(localHosts)('when src contains "%s"', host => {
191
- beforeEach(() => {
192
- props.src = `http://${host}/mfe`;
193
- initializeGetJsonMockFns(props.src);
194
- });
195
-
196
- test('appends src to error fallback', async () => {
197
- subject();
198
- await triggerFailure?.();
199
-
200
- await waitFor(() =>
201
- expect(
202
- screen.getByText(`Something went wrong loading ${props.src}`)
203
- ).toBeInTheDocument()
204
- );
205
- });
206
- });
207
-
208
- describe('when an errorFallback is provided', () => {
209
- beforeEach(() => {
210
- props.errorFallback = <div>bar</div>;
211
- });
212
-
213
- test('renders provided error fallback', async () => {
214
- subject();
215
- await triggerFailure?.();
216
-
217
- await waitFor(() => expect(screen.getByText('bar')).toBeInTheDocument());
218
- });
219
- });
220
- }
221
-
222
- describe.each(localHosts)('when src contains "%s"', host => {
223
- beforeEach(() => {
224
- props.src = `http://${host}/mfe`;
225
- initializeGetJsonMockFns(props.src);
226
- });
227
-
228
- test('appends src to lading fallback', async () => {
229
- subject();
230
-
231
- await waitFor(() =>
232
- expect(screen.getByText(`Loading ${props.src}...`)).toBeInTheDocument()
233
- );
234
- });
235
- });
236
-
237
- describe('with ref parameter', () => {
238
- let loaderRef: RefObject<any> | undefined;
239
-
240
- const RootWithRef = () => {
241
- const ref = useRef(null);
242
-
243
- useEffect(() => {
244
- loaderRef = ref;
245
- }, []);
246
-
247
- return <Loader {...props} ref={ref} />;
248
- };
249
-
250
- const subject = () => render(<RootWithRef />);
251
-
252
- beforeEach(() => (loaderRef = undefined));
253
-
254
- test('initializes ref object', () => {
255
- subject();
256
-
257
- expect(loaderRef?.current).not.toBeNull();
258
- });
259
- });
260
-
261
- describe('when loadingFallback is provided', () => {
262
- beforeEach(() => {
263
- props.loadingFallback = <div>foo</div>;
264
- });
265
-
266
- test('renders provided loading fallback', async () => {
267
- subject();
268
-
269
- await waitFor(() => expect(screen.getByText('foo')).toBeInTheDocument());
270
- });
271
-
272
- test('preserves component state when loading fallback is updated', () => {
273
- const { rerender } = subject();
274
-
275
- expectPreservesComponentState(rerender, () => (props.loadingFallback = <div>foo</div>));
276
- });
277
- });
278
-
279
- describe('when the loadingFallback throws an error', () => {
280
- beforeEach(() => {
281
- const ThrowError: FC = () => {
282
- throw new Error('woops');
283
- };
284
- props.loadingFallback = <ThrowError />;
285
- });
286
-
287
- itRendersErrorFallback();
288
- });
289
-
290
- describe('when loadingFallback is not delayed', () => {
291
- beforeEach(() => (props.loadingFallbackDelayed = false));
292
-
293
- test('renders loading fallback immediately', () => {
294
- subject();
295
-
296
- expect(screen.getByText(/loading/i)).toBeInTheDocument();
297
- });
298
- });
299
-
300
- describe('when a script tag (with a webComponent data attr) for this bundle is in the DOM before Loader is rendered', () => {
301
- beforeEach(() => {
302
- const script = document.createElement('script');
303
- script.setAttribute('src', `${baseUrl}/dist/bundle/light/light.js`);
304
- script.dataset.webComponent = 'foo';
305
- document.body.appendChild(script);
306
- });
307
-
308
- /*
309
- * when a script tag is already in the dom, we don't need to manually trigger the onload,
310
- * as we do with the remaining tests
311
- */
312
- test('renders web component', async () => {
313
- subject();
314
- await waitFor(() =>
315
- expect(document.querySelector(WEB_COMPONENT_NAME)).toBeInTheDocument()
316
- );
317
- });
318
- });
319
-
320
- describe('when metadata request is pending', () => {
321
- let resolveMetadata: (() => void) | undefined;
322
-
323
- beforeEach(() => {
324
- const { src } = props;
325
- getJsonMockFns[`${src}/dist/metadata.json`] = () =>
326
- new Promise(resolve => {
327
- resolveMetadata = () =>
328
- resolve({ data: metadata, headers: {} as Headers, url: src });
329
- });
330
- });
331
-
332
- afterEach(() => {
333
- resolveMetadata?.();
334
- resolveMetadata = undefined;
335
- });
336
-
337
- describe('when rerendered with same src', () => {
338
- beforeEach(() => {
339
- const { rerender } = subject();
340
- props.onRequestError = jest.fn();
341
- rerender(<Root />);
342
- });
343
-
344
- test('requests metadata once', () => {
345
- expect(common.getJson).toHaveBeenCalledTimes(1);
346
- });
347
-
348
- describe('when metadata resolves', () => {
349
- beforeEach(() => resolveMetadata?.());
350
-
351
- test('renders the web component', async () => {
352
- await waitForScriptLoad();
353
-
354
- await waitFor(() =>
355
- expect(document.querySelector(WEB_COMPONENT_NAME)).toBeInTheDocument()
356
- );
357
- });
358
- });
359
- });
360
-
361
- describe('when rerendered with a new src', () => {
362
- const newSrc = 'http://unpkg.servicetitan.com/other-mfe';
363
-
364
- beforeEach(() => {
365
- const { rerender } = subject();
366
- getJsonMockFns[`${newSrc}/dist/metadata.json`] = () =>
367
- Promise.resolve({ data: metadata, headers: {} as Headers, url: newSrc });
368
- props.src = newSrc;
369
- rerender(<Root />);
370
- });
371
-
372
- test('requests metadata for the new src', () => {
373
- expect(common.getJson).toHaveBeenCalledTimes(2);
374
- });
375
- });
376
- });
377
-
378
- describe('after the script tag added is loaded', () => {
379
- async function scriptLoadedSetup() {
380
- const result = subject();
381
- await waitForScriptLoad();
382
- await waitFor(() =>
383
- expect(document.querySelector(WEB_COMPONENT_NAME)).toBeInTheDocument()
384
- );
385
- return result;
386
- }
387
-
388
- test('hides web component', async () => {
389
- await scriptLoadedSetup();
390
-
391
- expect(document.querySelector(WEB_COMPONENT_NAME)).not.toBeVisible();
392
- });
393
-
394
- function itAddsJsEntrypointToWebComponent(entrypointTestText: string, urlFn: () => string) {
395
- test(`adds the ${entrypointTestText} to a script tag`, async () => {
396
- await scriptLoadedSetup();
397
- const script = document.querySelector('script');
398
- expect(script).toHaveAttribute('src', urlFn());
399
- });
400
- }
401
-
402
- function itAddsCssEntrypointToWebComponent(
403
- entrypointTestText: string,
404
- urlFn: () => string
405
- ) {
406
- test(`adds the ${entrypointTestText} to the web component style-urls attribute`, async () => {
407
- await scriptLoadedSetup();
408
- expect(webComponent).toHaveAttribute(
409
- 'style-urls',
410
- encodeURIComponent(JSON.stringify([urlFn()]))
411
- );
412
- });
413
- }
414
-
415
- function itCallsGetJsonWithUrlAndCacheValue(
416
- urlFn: () => string,
417
- cache: string | undefined
418
- ) {
419
- test(`getJson is called with url and cache set to ${cache}`, async () => {
420
- await scriptLoadedSetup();
421
- expect(common.getJson).toHaveBeenCalledWith(
422
- urlFn(),
423
- expect.objectContaining({ cache })
424
- );
425
- });
426
- }
427
-
428
- describe('when the metadata contains no dependencies prop', () => {
429
- const dependencies = 'baz';
430
- function addGetJsonPackageJsonMockFn(url: string) {
431
- getJsonMockFns[`${url}/package.json`] = () => ({
432
- data: { dependencies },
433
- });
434
- }
435
-
436
- beforeEach(() => {
437
- metadata.dependencies = undefined;
438
- addGetJsonPackageJsonMockFn(baseUrl);
439
- });
440
-
441
- test('dependencies are pulled from package.json', async () => {
442
- await scriptLoadedSetup();
443
- expect(getVersionMismatches).toHaveBeenCalledWith(
444
- expect.anything(),
445
- dependencies,
446
- expect.anything()
447
- );
448
- });
449
-
450
- itCallsGetJsonWithUrlAndCacheValue(() => `${baseUrl}/package.json`, 'no-store');
451
-
452
- describe('when baseUrl is versioned', () => {
453
- const versionedBaseUrl = 'http://unpkg.localhost/mfe@v1.0.0';
454
-
455
- beforeEach(() => {
456
- props = { src: versionedBaseUrl };
457
- initializeGetJsonMockFns(versionedBaseUrl);
458
- addGetJsonPackageJsonMockFn(versionedBaseUrl);
459
- });
460
-
461
- itCallsGetJsonWithUrlAndCacheValue(
462
- () => `${versionedBaseUrl}/package.json`,
463
- undefined
464
- );
465
- });
466
- });
467
-
468
- describe('when data is passed in as a prop', () => {
469
- beforeEach(() => {
470
- props.data = { fooBar: 'foobar' };
471
- });
472
-
473
- test('data is spread as data attributes in kebab case on the web component', async () => {
474
- await scriptLoadedSetup();
475
- expect(webComponent).toHaveAttribute('data-foo-bar', 'foobar');
476
- });
477
- });
478
-
479
- itAddsJsEntrypointToWebComponent(
480
- 'light js entrypoint from metadata.json',
481
- () => `${baseUrl}/dist/bundle/light/${metadata.entrypoints!.light.js[0]}`
482
- );
483
-
484
- itAddsCssEntrypointToWebComponent(
485
- 'light css entrypoint from metadata.json',
486
- () => `${baseUrl}/dist/bundle/light/${metadata.entrypoints!.light.css[0]}`
487
- );
488
-
489
- describe('when the entrypoint specifies a dev-server port', () => {
490
- const port = 3000;
491
-
492
- beforeEach(() => {
493
- Object.assign(metadata.entrypoints!.light, { port });
494
- });
495
-
496
- function withPort(url: string) {
497
- const result = new URL(url);
498
- result.port = String(port);
499
- return String(result);
500
- }
501
-
502
- itAddsJsEntrypointToWebComponent(
503
- 'entrypoint with dev-server port',
504
- () => `${withPort(baseUrl)}/dist/bundle/light/${metadata.entrypoints!.light.js[0]}`
505
- );
506
-
507
- describe('when NODE_ENV is production', () => {
508
- const originalNodeEnv = process.env.NODE_ENV;
509
-
510
- beforeEach(() => (process.env.NODE_ENV = 'production'));
511
-
512
- afterEach(() => (process.env.NODE_ENV = originalNodeEnv));
513
-
514
- itAddsJsEntrypointToWebComponent(
515
- 'entrypoint without dev-server port',
516
- () => `${baseUrl}/dist/bundle/light/${metadata.entrypoints!.light.js[0]}`
517
- );
518
- });
519
- });
520
-
521
- describe('when entrypoint has module: true', () => {
522
- beforeEach(() => {
523
- metadata.entrypoints!.light.module = true;
524
- });
525
-
526
- test('creates script with type="module"', async () => {
527
- await scriptLoadedSetup();
528
-
529
- expect(document.querySelector('script')).toHaveAttribute('type', 'module');
530
- });
531
- });
532
-
533
- describe('when the startup version is < 17.0.0', () => {
534
- beforeEach(() => {
535
- setStartupVersion('16.0.0');
536
- });
537
-
538
- itAddsJsEntrypointToWebComponent(
539
- 'full js entrypoint from metadata.json',
540
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.js[0]}`
541
- );
542
-
543
- itAddsCssEntrypointToWebComponent(
544
- 'full css entrypoint from metadata.json',
545
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.css[0]}`
546
- );
547
- });
548
-
549
- describe('when the startup version is missing', () => {
550
- beforeEach(() => {
551
- setStartupVersion(undefined);
552
- });
553
-
554
- itAddsJsEntrypointToWebComponent(
555
- 'full js entrypoint from metadata.json',
556
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.js[0]}`
557
- );
558
-
559
- itAddsCssEntrypointToWebComponent(
560
- 'full css entrypoint from metadata.json',
561
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.css[0]}`
562
- );
563
- });
564
-
565
- itCallsGetJsonWithUrlAndCacheValue(() => `${baseUrl}/dist/metadata.json`, 'no-store');
566
-
567
- describe('when baseUrl is versioned', () => {
568
- const versionedBaseUrl = 'http://unpkg.localhost/mfe@v1.0.0';
569
-
570
- beforeEach(() => {
571
- props.src = versionedBaseUrl;
572
- initializeGetJsonMockFns(versionedBaseUrl);
573
- });
574
-
575
- itCallsGetJsonWithUrlAndCacheValue(
576
- () => `${versionedBaseUrl}/dist/metadata.json`,
577
- undefined
578
- );
579
- });
580
-
581
- describe('when the metadata request fails', () => {
582
- const fallbackCssEntrypoint = 'foo.css';
583
- const fallbackJsEntrypoint = 'bar.js';
584
-
585
- beforeEach(() => {
586
- getJsonMockFns[`${baseUrl}/dist/metadata.json`] = () => {
587
- return Promise.reject(new Error('metadata request failed'));
588
- };
589
- });
590
-
591
- test('renders the error fallback', async () => {
592
- jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress error boundary logging
593
- subject();
594
-
595
- await waitFor(() =>
596
- expect(screen.getByText('Something went wrong')).toBeInTheDocument()
597
- );
598
- });
599
-
600
- describe('when the fallback url is provided', () => {
601
- function addGetJsonFallbackMockFn(url: string) {
602
- getJsonMockFns[`${url}/dist/metadata.json`] = () => {
603
- const fallbackMetadata = { ...metadata };
604
- fallbackMetadata.entrypoints = {
605
- light: {
606
- css: [fallbackCssEntrypoint],
607
- js: [fallbackJsEntrypoint],
608
- },
609
- };
610
- return Promise.resolve({
611
- data: fallbackMetadata,
612
- headers: {} as Headers,
613
- url,
614
- });
615
- };
616
- }
617
- const fallbackSrc = 'http://localhost/mfe-fallback';
618
-
619
- beforeEach(() => {
620
- props.fallbackSrc = fallbackSrc;
621
- addGetJsonFallbackMockFn(fallbackSrc);
622
- });
623
-
624
- itAddsJsEntrypointToWebComponent(
625
- "js entrypoint from the fallback url's metadata.json",
626
- () => `${fallbackSrc}/dist/bundle/light/${fallbackJsEntrypoint}`
627
- );
628
-
629
- itAddsCssEntrypointToWebComponent(
630
- "css entrypoint from the fallback url's metadata.json",
631
- () => `${fallbackSrc}/dist/bundle/light/${fallbackCssEntrypoint}`
632
- );
633
-
634
- itCallsGetJsonWithUrlAndCacheValue(
635
- () => `${fallbackSrc}/dist/metadata.json`,
636
- 'no-store'
637
- );
638
-
639
- describe('when fallback url is versioned', () => {
640
- const fallbackSrc = 'http://unpkg.localhost/mfe-fallback@v1.0.0';
641
-
642
- beforeEach(() => {
643
- props.fallbackSrc = fallbackSrc;
644
- addGetJsonFallbackMockFn(fallbackSrc);
645
- });
646
-
647
- itCallsGetJsonWithUrlAndCacheValue(
648
- () => `${fallbackSrc}/dist/metadata.json`,
649
- undefined
650
- );
651
- });
652
- });
653
- });
654
-
655
- describe('when the metadata does not contain entrypoints', () => {
656
- const cssEntrypoint = 'foo.css';
657
- const jsEntrypoint = 'bar.js';
658
- beforeEach(() => {
659
- metadata.entrypoints = undefined;
660
- getJsonMockFns[`${baseUrl}/dist/bundle/light/entrypoints.json`] = () => {
661
- return Promise.resolve({
662
- data: { css: [cssEntrypoint], js: [jsEntrypoint] },
663
- });
664
- };
665
- });
666
-
667
- itAddsJsEntrypointToWebComponent(
668
- 'js entrypoint from entrypoints.json',
669
- () => `${baseUrl}/dist/bundle/light/${jsEntrypoint}`
670
- );
671
-
672
- itAddsCssEntrypointToWebComponent(
673
- 'css entrypoint from entrypoints.json',
674
- () => `${baseUrl}/dist/bundle/light/${cssEntrypoint}`
675
- );
676
-
677
- describe('when entrypoints.json is missing', () => {
678
- beforeEach(() => {
679
- getJsonMockFns[`${baseUrl}/dist/bundle/light/entrypoints.json`] = () => {
680
- return Promise.reject();
681
- };
682
- });
683
-
684
- itAddsJsEntrypointToWebComponent(
685
- 'default js entrypoint',
686
- () => `${baseUrl}/dist/bundle/light/index.js`
687
- );
688
-
689
- itAddsCssEntrypointToWebComponent(
690
- 'default css entrypoint',
691
- () => `${baseUrl}/dist/bundle/light/index.css`
692
- );
693
- });
694
- });
695
-
696
- test('renders web component', async () => {
697
- await scriptLoadedSetup();
698
- expect(document.querySelector(WEB_COMPONENT_NAME)).toBeInTheDocument();
699
- });
700
-
701
- test('renders "data-mfe-name" attribute with undecorated name', async () => {
702
- await scriptLoadedSetup();
703
-
704
- expect(document.querySelector(WEB_COMPONENT_NAME)).toHaveAttribute(
705
- 'data-mfe-name',
706
- baseName
707
- );
708
- });
709
-
710
- const mfeVersionAttribute = 'data-mfe-version';
711
-
712
- test(`renders "${mfeVersionAttribute}" attribute`, async () => {
713
- await scriptLoadedSetup();
714
-
715
- expect(document.querySelector(WEB_COMPONENT_NAME)).toHaveAttribute(
716
- mfeVersionAttribute,
717
- metadata.version
718
- );
719
- });
720
-
721
- describe('when metadata omits version', () => {
722
- beforeEach(() => delete metadata.version);
723
-
724
- test(`omits "${mfeVersionAttribute}" attribute`, async () => {
725
- await scriptLoadedSetup();
726
-
727
- expect(document.querySelector(WEB_COMPONENT_NAME)).not.toHaveAttribute(
728
- mfeVersionAttribute
729
- );
730
- });
731
- });
732
-
733
- describe('after the web component is ready', () => {
734
- async function webComponentReadySetup() {
735
- const result = await scriptLoadedSetup();
736
-
737
- act(() => {
738
- webComponentState.onReady!();
739
- });
740
-
741
- return result;
742
- }
743
-
744
- test('removes loading fallback', async () => {
745
- await webComponentReadySetup();
746
- expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
747
- });
748
-
749
- test('shows web component', async () => {
750
- await webComponentReadySetup();
751
-
752
- expect(document.querySelector(WEB_COMPONENT_NAME)).toBeVisible();
753
- });
754
-
755
- describe('when data is provided', () => {
756
- beforeEach(() => {
757
- props.data = { foo: 'bar' };
758
- });
759
-
760
- test('provides stringified data to the web component', async () => {
761
- await webComponentReadySetup();
762
- expect(webComponent).toHaveAttribute(
763
- 'data-mfe-data',
764
- JSON.stringify(props.data)
765
- );
766
- });
767
- });
768
-
769
- describe('when a className is provided', () => {
770
- beforeEach(() => {
771
- props.className = 'foobar';
772
- });
773
-
774
- test('provides the className to the web component', async () => {
775
- await webComponentReadySetup();
776
- expect(webComponent).toHaveClass('foobar');
777
- });
778
- });
779
-
780
- (
781
- [
782
- [Log, 'logService'],
783
- [HistoryManager, 'historyManager'],
784
- [EXPOSED_DEPENDENCIES_TOKEN, 'exposedDependencies'],
785
- [EXPOSED_INSTANCE_DEPENDENCIES_TOKEN, 'exposedInstanceDependencies'],
786
- [EVENT_BUS_TOKEN, 'eventBus'],
787
- ] as [any, string][]
788
- ).forEach(([klass, propName]) => {
789
- describe(`when ${propName} is provided`, () => {
790
- beforeEach(() => {
791
- singletons?.push({ provide: klass, useValue: propName });
792
- });
793
-
794
- test(`provides ${propName} to the web component`, async () => {
795
- await webComponentReadySetup();
796
- expect(webComponentState[propName as keyof Entries]).toEqual(propName);
797
- });
798
- });
799
- });
800
-
801
- describe('when ldService is provided via EXPOSED_INSTANCE_DEPENDENCIES', () => {
802
- let ldService: { getVersionClient?: jest.Mock };
803
-
804
- beforeEach(() => {
805
- ldService = {};
806
- singletons?.push({
807
- provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
808
- useValue: { launchDarkly: { version: '1.0', ldService } },
809
- });
810
- });
811
-
812
- test('provides ldService to the web component', async () => {
813
- await webComponentReadySetup();
814
- expect(webComponentState.ldService).toEqual(ldService);
815
- });
816
-
817
- describe('when MFE has incompatible LaunchDarkly version', () => {
818
- beforeEach(() => {
819
- jest.mocked(getMFEHasCompatibleLaunchDarklyVersion).mockReturnValue(false);
820
- });
821
-
822
- function itDoesNotProvideLDService() {
823
- test('does not provide ldService to the web component', async () => {
824
- await webComponentReadySetup();
825
- expect(webComponentState.ldService).toBeUndefined();
826
- });
827
- }
828
-
829
- itDoesNotProvideLDService();
830
-
831
- describe('when MFE supports a versioned LD client', () => {
832
- beforeEach(() => {
833
- jest.mocked(getMFESupportsVersionedLDClient).mockReturnValue(true);
834
- });
835
-
836
- itDoesNotProvideLDService();
837
-
838
- describe("when the host's LDService supports a versioned client", () => {
839
- beforeEach(() => {
840
- ldService.getVersionClient = jest.fn();
841
- });
842
-
843
- test('provides ldService to the web component', async () => {
844
- await webComponentReadySetup();
845
- expect(webComponentState.ldService).toEqual(ldService);
846
- });
847
- });
848
- });
849
- });
850
- });
851
-
852
- describe('when only LaunchDarkly version is provided via EXPOSED_INTERNAL_DEPENDENCIES', () => {
853
- beforeEach(() => {
854
- singletons?.push({
855
- provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
856
- useValue: { launchDarkly: { version: '1.0' } },
857
- });
858
- });
859
-
860
- describe('when ldService is provided via LD_SERVICE_TOKEN', () => {
861
- const ldService = Symbol('ldService');
862
-
863
- beforeEach(() =>
864
- singletons?.push({ provide: LD_SERVICE_TOKEN, useValue: ldService })
865
- );
866
-
867
- test('adds ldService to exposedInternalDependencies provided to web component', async () => {
868
- await webComponentReadySetup();
869
- expect(webComponentState.exposedInstanceDependencies).toEqual(
870
- expect.objectContaining({
871
- launchDarkly: expect.objectContaining({ ldService }),
872
- })
873
- );
874
- });
875
-
876
- test('provides ldService to the web component', async () => {
877
- await webComponentReadySetup();
878
- expect(webComponentState.ldService).toEqual(ldService);
879
- });
880
-
881
- test('preserves state when component is rerendered', async () => {
882
- const { rerender } = await webComponentReadySetup();
883
-
884
- expectPreservesComponentState(rerender);
885
- });
886
- });
887
- });
888
-
889
- describe('when metadata.bundledWith includes LaunchDarkly', () => {
890
- const version = '1.0.0';
891
-
892
- beforeEach(() => {
893
- metadata.bundledWith = { 'launchdarkly-js-client-sdk': version };
894
- });
895
-
896
- function itAddsLaunchDarklyVersion() {
897
- test('adds LaunchDarkly version to exposedInternalDependencies provided to web component', async () => {
898
- await webComponentReadySetup();
899
-
900
- expect(webComponentState.exposedInstanceDependencies).toEqual(
901
- expect.objectContaining({ launchDarkly: { version } })
902
- );
903
- });
904
- }
905
-
906
- describe('when EXPOSED_INTERNAL_DEPENDENCIES omits launchDarkly', () => {
907
- beforeEach(() => {
908
- singletons?.push({
909
- provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
910
- useValue: {},
911
- });
912
- });
913
-
914
- itAddsLaunchDarklyVersion();
915
- });
916
-
917
- describe('when EXPOSED_INTERNAL_DEPENDENCIES.launchDarkly omits ldService', () => {
918
- beforeEach(() => {
919
- singletons?.push({
920
- provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
921
- useValue: { launchDarkly: { version: '1.2.3' } },
922
- });
923
- });
924
-
925
- itAddsLaunchDarklyVersion();
926
- });
927
- });
928
-
929
- describe('when a script tag (without a webComponent data attr) for this bundle is in the DOM before Loader is rendered', () => {
930
- const originalOnloadSpy = jest.fn();
931
-
932
- beforeEach(() => {
933
- const script = document.createElement('script');
934
- script.setAttribute('src', `${baseUrl}/dist/bundle/light/light.js`);
935
- script.onload = originalOnloadSpy;
936
- document.body.appendChild(script);
937
- });
938
-
939
- test('onload handler gets unassigned after it gets called', async () => {
940
- await webComponentReadySetup();
941
- expect(onloadRef).toBeNull();
942
- });
943
- });
944
-
945
- describe('when there are version mismatches', () => {
946
- const exposedDependencies: ExposedDependencies = {
947
- foo: { variable: 'foo', version: '1.0' },
948
- };
949
- const exposedInstanceDependencies: ExposedInstanceDependencies = {
950
- launchDarkly: { version: '1.0' },
951
- };
952
- const mismatchedDeps = {
953
- foo: { host: '1.0', package: '2.0' },
954
- };
955
-
956
- beforeEach(() => {
957
- jest.mocked(getVersionMismatches).mockReturnValue(mismatchedDeps);
958
- singletons?.push(
959
- {
960
- provide: EXPOSED_DEPENDENCIES_TOKEN,
961
- useValue: exposedDependencies,
962
- },
963
- {
964
- provide: EXPOSED_INSTANCE_DEPENDENCIES_TOKEN,
965
- useValue: exposedInstanceDependencies,
966
- }
967
- );
968
- });
969
-
970
- itAddsJsEntrypointToWebComponent(
971
- 'full js entrypoint from metadata.json',
972
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.js[0]}`
973
- );
974
-
975
- itAddsCssEntrypointToWebComponent(
976
- 'full css entrypoint from metadata.json',
977
- () => `${baseUrl}/dist/bundle/full/${metadata.entrypoints!.full.css[0]}`
978
- );
979
-
980
- describe('when logService is provided', () => {
981
- const logService = { warning: jest.fn() };
982
-
983
- beforeEach(() => {
984
- singletons?.push({ provide: Log, useValue: logService });
985
- });
986
-
987
- test('logs "mismatch" warning', async () => {
988
- await webComponentReadySetup();
989
-
990
- expect(logService.warning).toHaveBeenCalledWith(
991
- expect.objectContaining({
992
- category: 'MicroFrontends.DependenciesMismatch',
993
- data: {
994
- package: baseUrl,
995
- dependencies: JSON.stringify(mismatchedDeps),
996
- },
997
- })
998
- );
999
- });
1000
-
1001
- describe('when host exposes no dependencies', () => {
1002
- beforeEach(() => {
1003
- singletons = singletons?.filter(
1004
- ({ provide }: any) => provide !== EXPOSED_DEPENDENCIES_TOKEN
1005
- );
1006
- });
1007
-
1008
- test('logs "no dependencies" warning', async () => {
1009
- await webComponentReadySetup();
1010
-
1011
- expect(logService.warning).toHaveBeenCalledWith(
1012
- expect.objectContaining({
1013
- category: 'MicroFrontends.NoExposedDependencies',
1014
- })
1015
- );
1016
- });
1017
- });
1018
-
1019
- describe('when MFE has incompatible version of LaunchDarkly', () => {
1020
- beforeEach(() => {
1021
- jest.mocked(getMFEHasCompatibleLaunchDarklyVersion).mockReturnValue(
1022
- false
1023
- );
1024
- });
1025
-
1026
- test('logs "LaunchDarkly mismatch" warning', async () => {
1027
- await webComponentReadySetup();
1028
-
1029
- expect(logService.warning).toHaveBeenCalledWith(
1030
- expect.objectContaining({
1031
- category: 'MicroFrontends.LaunchDarklyMismatch',
1032
- data: {
1033
- package: props.src,
1034
- hostVersion:
1035
- exposedInstanceDependencies.launchDarkly?.version,
1036
- },
1037
- })
1038
- );
1039
- });
1040
- });
1041
- });
1042
- });
1043
- });
1044
-
1045
- test('onload handler gets unassigned after it gets called', async () => {
1046
- await scriptLoadedSetup();
1047
- expect(onloadRef).toBeNull();
1048
- });
1049
- });
1050
-
1051
- describe('when the script tag fails to load', () => {
1052
- beforeEach(() => {
1053
- jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress error boundary logging
1054
- });
1055
-
1056
- async function triggerScriptError() {
1057
- await waitFor(() => onerrorRef !== null);
1058
- act(() => {
1059
- onerrorRef!();
1060
- });
1061
- }
1062
-
1063
- itRendersErrorFallback(triggerScriptError);
1064
-
1065
- test('does not hang on the loading fallback', async () => {
1066
- subject();
1067
- await triggerScriptError();
1068
-
1069
- await waitFor(() => expect(screen.queryByText(/loading/i)).not.toBeInTheDocument());
1070
- });
1071
- });
1072
-
1073
- describe('when cache is enabled', () => {
1074
- beforeAll(() => {
1075
- jest.useFakeTimers();
1076
- jest.spyOn(console, 'error').mockImplementation(jest.fn); // suppress "suspended resource finished loading inside a test" error
1077
- });
1078
-
1079
- beforeEach(() => delete props.cache);
1080
-
1081
- function preloadComponent({ id, cache }: { id?: string; cache?: boolean | number } = {}) {
1082
- if (id) {
1083
- props.src = `http://localhost/${id}`;
1084
- initializeGetJsonMockFns(props.src);
1085
- }
1086
- if (cache !== undefined) {
1087
- props.cache = cache;
1088
- }
1089
- subject();
1090
- jest.mocked(common.getJson).mockClear();
1091
- }
1092
-
1093
- function itReloadsMetadataAfter(delay: number, description: string) {
1094
- test(`reloads metadata after ${description}`, () => {
1095
- act(() => jest.advanceTimersByTime(delay - 1));
1096
- subject();
1097
- expect(common.getJson).not.toHaveBeenCalled();
1098
-
1099
- act(() => jest.advanceTimersByTime(1));
1100
- subject();
1101
- expect(common.getJson).toHaveBeenCalledTimes(1);
1102
- });
1103
- }
1104
-
1105
- function itNeverReloadsMetadata() {
1106
- test('never reloads metadata', () => {
1107
- jest.runOnlyPendingTimers();
1108
- subject();
1109
-
1110
- expect(common.getJson).not.toHaveBeenCalled();
1111
- });
1112
- }
1113
-
1114
- describe('when component was previously loaded', () => {
1115
- beforeEach(() => preloadComponent({ id: 'mfe1' }));
1116
-
1117
- itNeverReloadsMetadata();
1118
- });
1119
-
1120
- describe('when cache is true', () => {
1121
- beforeEach(() => preloadComponent({ id: 'mfe2', cache: true }));
1122
-
1123
- test('uses cached metadata', () => {
1124
- subject();
1125
-
1126
- expect(common.getJson).not.toHaveBeenCalled();
1127
- });
1128
-
1129
- itReloadsMetadataAfter(1000 * 60 * 15, 'fifteen minutes');
1130
- });
1131
-
1132
- describe('when cache is true and mfe does not have unique chunk namespace', () => {
1133
- beforeEach(() => {
1134
- jest.mocked(getMFEHasUniqueChunkNamespace).mockReturnValue(false);
1135
- preloadComponent({ id: 'mfe3', cache: true });
1136
- });
1137
-
1138
- itNeverReloadsMetadata();
1139
- });
1140
-
1141
- describe('when component has custom ttl', () => {
1142
- const customTtl = 1000 * 60; // one minute
1143
-
1144
- beforeEach(() => preloadComponent({ id: 'mfe4', cache: customTtl }));
1145
-
1146
- itReloadsMetadataAfter(customTtl, 'custom ttl');
1147
- });
1148
-
1149
- describe('when component has zero ttl', () => {
1150
- beforeEach(() => preloadComponent({ id: 'mfe5', cache: 0 }));
1151
-
1152
- test('always reloads metadata', () => {
1153
- subject();
1154
-
1155
- expect(common.getJson).toHaveBeenCalledTimes(1);
1156
- });
1157
- });
1158
-
1159
- describe("when mfe doesn't have unique chunk namespace", () => {
1160
- beforeEach(() => {
1161
- preloadComponent({ id: 'mfe6' });
1162
- setStartupVersion('27.1.1');
1163
- });
1164
-
1165
- itNeverReloadsMetadata();
1166
- });
1167
-
1168
- describe('when headless mfe is loaded after non-headless mfe', () => {
1169
- beforeEach(() => {
1170
- preloadComponent({ id: 'mfe7' });
1171
- (props as UnrestrictedLoaderProps).isHeadless = true;
1172
- initializeGetJsonMockFns(props.src);
1173
- });
1174
-
1175
- itNeverReloadsMetadata();
1176
- });
1177
- });
1178
- });