@croct/plug-react 0.4.2 → 0.5.0-next.2

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 (92) hide show
  1. package/CroctProvider.d.ts +7 -7
  2. package/CroctProvider.js +37 -0
  3. package/CroctProvider.js.map +1 -0
  4. package/README.md +245 -107
  5. package/api/evaluate.d.ts +7 -0
  6. package/api/evaluate.js +15 -0
  7. package/api/evaluate.js.map +1 -0
  8. package/api/fetchContent.d.ts +13 -0
  9. package/api/fetchContent.js +20 -0
  10. package/api/fetchContent.js.map +1 -0
  11. package/api/index.d.ts +2 -0
  12. package/api/index.js +19 -0
  13. package/api/index.js.map +1 -0
  14. package/components/Personalization/index.d.ts +10 -10
  15. package/components/Personalization/index.js +13 -0
  16. package/components/Personalization/index.js.map +1 -0
  17. package/components/Slot/index.d.ts +19 -19
  18. package/components/Slot/index.js +13 -0
  19. package/components/Slot/index.js.map +1 -0
  20. package/components/index.d.ts +2 -2
  21. package/components/index.js +19 -0
  22. package/components/index.js.map +1 -0
  23. package/hooks/Cache.d.ts +22 -22
  24. package/hooks/Cache.js +62 -0
  25. package/hooks/Cache.js.map +1 -0
  26. package/hooks/index.d.ts +3 -3
  27. package/hooks/index.js +20 -0
  28. package/hooks/index.js.map +1 -0
  29. package/hooks/useContent.d.ts +18 -17
  30. package/hooks/useContent.js +25 -0
  31. package/hooks/useContent.js.map +1 -0
  32. package/hooks/useCroct.d.ts +2 -2
  33. package/hooks/useCroct.js +14 -0
  34. package/hooks/useCroct.js.map +1 -0
  35. package/hooks/useEvaluation.d.ts +11 -11
  36. package/hooks/useEvaluation.js +35 -0
  37. package/hooks/useEvaluation.js.map +1 -0
  38. package/hooks/useLoader.d.ts +5 -5
  39. package/hooks/useLoader.js +41 -0
  40. package/hooks/useLoader.js.map +1 -0
  41. package/index.d.ts +5 -3
  42. package/index.js +20 -337
  43. package/index.js.map +1 -1
  44. package/package.json +33 -46
  45. package/src/api/evaluate.test.ts +59 -0
  46. package/src/api/evaluate.ts +19 -0
  47. package/src/api/fetchContent.test.ts +134 -0
  48. package/src/api/fetchContent.ts +47 -0
  49. package/src/api/index.ts +2 -0
  50. package/src/components/index.ts +2 -0
  51. package/src/global.d.ts +7 -0
  52. package/src/hooks/Cache.test.ts +280 -0
  53. package/src/hooks/Cache.ts +97 -0
  54. package/src/hooks/index.ts +3 -0
  55. package/src/hooks/useContent.ssr.test.ts +23 -0
  56. package/src/hooks/useContent.test.ts +66 -0
  57. package/src/hooks/useContent.ts +69 -0
  58. package/src/hooks/useCroct.ts +13 -0
  59. package/src/hooks/useEvaluation.ssr.test.ts +23 -0
  60. package/src/hooks/useEvaluation.test.ts +92 -0
  61. package/src/hooks/useEvaluation.ts +58 -0
  62. package/src/hooks/useLoader.test.ts +320 -0
  63. package/src/hooks/useLoader.ts +50 -0
  64. package/src/index.ts +5 -0
  65. package/src/react-app-env.d.ts +1 -0
  66. package/src/ssr-polyfills.ssr.test.ts +46 -0
  67. package/src/ssr-polyfills.test.ts +65 -0
  68. package/src/ssr-polyfills.ts +68 -0
  69. package/ssr-polyfills.d.ts +3 -3
  70. package/ssr-polyfills.js +64 -0
  71. package/ssr-polyfills.js.map +1 -0
  72. package/CroctProvider.test.d.ts +0 -1
  73. package/components/Personalization/index.d.test.d.ts +0 -1
  74. package/components/Personalization/index.stories.d.ts +0 -7
  75. package/components/Personalization/index.test.d.ts +0 -1
  76. package/components/Slot/index.d.test.d.ts +0 -1
  77. package/components/Slot/index.stories.d.ts +0 -17
  78. package/components/Slot/index.test.d.ts +0 -1
  79. package/hooks/Cache.test.d.ts +0 -1
  80. package/hooks/useContent.d.test.d.ts +0 -1
  81. package/hooks/useContent.ssr.test.d.ts +0 -1
  82. package/hooks/useContent.stories.d.ts +0 -19
  83. package/hooks/useContent.test.d.ts +0 -1
  84. package/hooks/useCroct.ssr.test.d.ts +0 -1
  85. package/hooks/useCroct.test.d.ts +0 -1
  86. package/hooks/useEvaluation.d.test.d.ts +0 -1
  87. package/hooks/useEvaluation.ssr.test.d.ts +0 -1
  88. package/hooks/useEvaluation.stories.d.ts +0 -8
  89. package/hooks/useEvaluation.test.d.ts +0 -1
  90. package/hooks/useLoader.test.d.ts +0 -1
  91. package/ssr-polyfills.ssr.test.d.ts +0 -1
  92. package/ssr-polyfills.test.d.ts +0 -1
package/index.js CHANGED
@@ -1,339 +1,22 @@
1
- var jsxRuntime = require('react/jsx-runtime');
2
- var react = require('react');
3
- var csrPlug = require('@croct/plug');
4
-
5
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
6
-
7
- var csrPlug__default = /*#__PURE__*/_interopDefaultLegacy(csrPlug);
8
-
9
- function _objectWithoutPropertiesLoose(source, excluded) {
10
- if (source == null) return {};
11
- var target = {};
12
- var sourceKeys = Object.keys(source);
13
- var key, i;
14
-
15
- for (i = 0; i < sourceKeys.length; i++) {
16
- key = sourceKeys[i];
17
- if (excluded.indexOf(key) >= 0) continue;
18
- target[key] = source[key];
19
- }
20
-
21
- return target;
22
- }
23
-
24
- function isSsr() {
25
- return typeof window === 'undefined' || typeof window.document === 'undefined' || typeof window.document.createElement === 'undefined';
26
- }
27
- var croct = !isSsr() ? csrPlug__default["default"] : new Proxy(csrPlug__default["default"], {
28
- get(_, property) {
29
- switch (property) {
30
- case 'initialized':
31
- return false;
32
-
33
- case 'plug':
34
- return () => {// no-op
35
- };
36
-
37
- case 'unplug':
38
- return () => Promise.resolve();
39
-
40
- default:
41
- throw new Error("Property croct." + String(property) + " is not supported on server-side (SSR). Consider refactoring " + 'the logic as a side-effect (useEffect) or a client-side callback (onClick, onChange, etc).');
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
42
7
  }
43
- }
44
-
45
- });
46
-
47
- var _excluded$4 = ["children"];
48
- var CroctContext = /*#__PURE__*/react.createContext(null);
49
- CroctContext.displayName = 'CroctContext';
50
- var CroctProvider = _ref => {
51
- var {
52
- children
53
- } = _ref,
54
- configuration = _objectWithoutPropertiesLoose(_ref, _excluded$4);
55
-
56
- var parent = react.useContext(CroctContext);
57
-
58
- if (parent !== null) {
59
- throw new Error('You cannot render <CroctProvider> inside another <CroctProvider>. ' + 'Croct should only be initialized once in the application.');
60
- }
61
-
62
- var context = react.useMemo(() => ({
63
- get plug() {
64
- if (!croct.initialized) {
65
- croct.plug(configuration);
66
- }
67
-
68
- return croct;
69
- }
70
-
71
- }), [configuration]);
72
- react.useEffect(() => {
73
- croct.plug(configuration);
74
- return () => {
75
- croct.unplug();
76
- };
77
- }, []);
78
- return jsxRuntime.jsx(CroctContext.Provider, {
79
- value: context,
80
- children: children
81
- });
82
- };
83
-
84
- class Cache {
85
- constructor(defaultExpiration) {
86
- this.cache = {};
87
- this.defaultExpiration = void 0;
88
- this.defaultExpiration = defaultExpiration;
89
- }
90
-
91
- load(configuration) {
92
- var {
93
- cacheKey,
94
- loader,
95
- fallback,
96
- expiration = this.defaultExpiration
97
- } = configuration;
98
- var cachedEntry = this.get(cacheKey);
99
-
100
- if (cachedEntry !== undefined) {
101
- if (cachedEntry.error !== undefined) {
102
- if (fallback !== undefined) {
103
- return fallback;
104
- }
105
-
106
- throw cachedEntry.error;
107
- }
108
-
109
- if (cachedEntry.result !== undefined) {
110
- return cachedEntry.result;
111
- }
112
-
113
- throw cachedEntry.promise;
114
- }
115
-
116
- var entry = {
117
- dispose: () => {
118
- if (entry.timeout !== undefined || expiration < 0) {
119
- return;
120
- }
121
-
122
- entry.timeout = window.setTimeout(() => {
123
- delete this.cache[cacheKey];
124
- }, expiration);
125
- },
126
- promise: loader().then(result => {
127
- entry.result = result;
128
- return result;
129
- }).catch(error => {
130
- entry.error = error;
131
- }).finally(() => {
132
- entry.dispose();
133
- })
134
- };
135
- this.cache[cacheKey] = entry;
136
- throw entry.promise;
137
- }
138
-
139
- get(cacheKey) {
140
- var entry = this.cache[cacheKey];
141
-
142
- if (entry === undefined) {
143
- return undefined;
144
- }
145
-
146
- if (entry.timeout !== undefined) {
147
- clearTimeout(entry.timeout);
148
- delete entry.timeout;
149
- entry.dispose();
150
- }
151
-
152
- return entry;
153
- }
154
-
155
- }
156
-
157
- var _excluded$3 = ["initial"];
158
- var cache = new Cache(60 * 1000);
159
- function useLoader(_ref) {
160
- var _cache$get;
161
-
162
- var {
163
- initial
164
- } = _ref,
165
- options = _objectWithoutPropertiesLoose(_ref, _excluded$3);
166
-
167
- var loadedValue = (_cache$get = cache.get(options.cacheKey)) == null ? void 0 : _cache$get.result;
168
- var [value, setValue] = react.useState(loadedValue !== undefined ? loadedValue : initial);
169
- var [isUnmounted, setUnmounted] = react.useState(false);
170
- react.useEffect(() => {
171
- if (initial !== undefined) {
172
- try {
173
- setValue(cache.load(options));
174
- } catch (result) {
175
- if (result instanceof Promise) {
176
- result.then(resolvedValue => {
177
- if (!isUnmounted) {
178
- setValue(resolvedValue);
179
- }
180
- });
181
- return;
182
- }
183
-
184
- setValue(undefined);
185
- return;
186
- }
187
- }
188
-
189
- return () => {
190
- setUnmounted(true);
191
- };
192
- }, []);
193
-
194
- if (value === undefined) {
195
- return cache.load(options);
196
- }
197
-
198
- return value;
199
- }
200
-
201
- function useCroct() {
202
- var context = react.useContext(CroctContext);
203
-
204
- if (context === null) {
205
- throw new Error('useCroct() can only be used in the context of a <CroctProvider> component.');
206
- }
207
-
208
- return context.plug;
209
- }
210
-
211
- var _excluded$2 = ["cacheKey", "fallback", "initial", "expiration"];
212
-
213
- function cleanEvaluationOptions(options) {
214
- var result = {};
215
-
216
- for (var [key, value] of Object.entries(options)) {
217
- if (value !== undefined) {
218
- result[key] = value;
219
- }
220
- }
221
-
222
- return result;
223
- }
224
-
225
- function useCsrEvaluation(expression, options) {
226
- var _options$attributes;
227
-
228
- if (options === void 0) {
229
- options = {};
230
- }
231
-
232
- var {
233
- cacheKey,
234
- fallback,
235
- initial,
236
- expiration
237
- } = options,
238
- evaluationOptions = _objectWithoutPropertiesLoose(options, _excluded$2);
239
-
240
- var croct = useCroct();
241
- return useLoader({
242
- cacheKey: "useEvaluation:" + (cacheKey != null ? cacheKey : '') + ":" + expression + ":" + JSON.stringify((_options$attributes = options.attributes) != null ? _options$attributes : ''),
243
- loader: () => croct.evaluate(expression, cleanEvaluationOptions(evaluationOptions)),
244
- initial: initial,
245
- fallback: fallback,
246
- expiration: expiration
247
- });
248
- }
249
-
250
- function useSsrEvaluation(_, _temp) {
251
- var {
252
- initial
253
- } = _temp === void 0 ? {} : _temp;
254
-
255
- if (initial === undefined) {
256
- throw new Error('The initial value is required for server-side rendering (SSR).');
257
- }
258
-
259
- return initial;
260
- }
261
-
262
- var useEvaluation = isSsr() ? useSsrEvaluation : useCsrEvaluation;
263
-
264
- function useCsrContent(id, options) {
265
- if (options === void 0) {
266
- options = {};
267
- }
268
-
269
- var {
270
- fallback,
271
- initial,
272
- cacheKey,
273
- expiration
274
- } = options;
275
- var croct = useCroct();
276
- return useLoader({
277
- cacheKey: "useContent:" + (cacheKey != null ? cacheKey : '') + ":" + id,
278
- loader: () => croct.fetch(id).then(_ref => {
279
- var {
280
- payload
281
- } = _ref;
282
- return payload;
283
- }),
284
- initial: initial,
285
- fallback: fallback,
286
- expiration: expiration
287
- });
288
- }
289
-
290
- function useSsrContent(_, _temp) {
291
- var {
292
- initial
293
- } = _temp === void 0 ? {} : _temp;
294
-
295
- if (initial === undefined) {
296
- throw new Error('The initial value is required for server-side rendering (SSR).');
297
- }
298
-
299
- return initial;
300
- }
301
-
302
- var useContent = isSsr() ? useSsrContent : useCsrContent;
303
-
304
- var _excluded$1 = ["expression", "children"];
305
- function Personalization(props) {
306
- var {
307
- expression,
308
- children
309
- } = props,
310
- options = _objectWithoutPropertiesLoose(props, _excluded$1);
311
-
312
- var result = useEvaluation(expression, options);
313
- return jsxRuntime.jsx(react.Fragment, {
314
- children: children(result)
315
- });
316
- }
317
-
318
- var _excluded = ["id", "children"];
319
- var Slot = props => {
320
- var {
321
- id,
322
- children
323
- } = props,
324
- options = _objectWithoutPropertiesLoose(props, _excluded);
325
-
326
- var data = useContent(id, options);
327
- return jsxRuntime.jsx(react.Fragment, {
328
- children: children(data)
329
- });
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
330
15
  };
331
-
332
- exports.CroctContext = CroctContext;
333
- exports.CroctProvider = CroctProvider;
334
- exports.Personalization = Personalization;
335
- exports.Slot = Slot;
336
- exports.useContent = useContent;
337
- exports.useCroct = useCroct;
338
- exports.useEvaluation = useEvaluation;
339
- //# sourceMappingURL=index.js.map
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("@croct/plug/sdk/json"), exports);
18
+ __exportStar(require("@croct/plug/slot"), exports);
19
+ __exportStar(require("./CroctProvider"), exports);
20
+ __exportStar(require("./hooks"), exports);
21
+ __exportStar(require("./components"), exports);
22
+ //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/ssr-polyfills.ts","../src/CroctProvider.tsx","../src/hooks/Cache.ts","../src/hooks/useLoader.ts","../src/hooks/useCroct.ts","../src/hooks/useEvaluation.ts","../src/hooks/useContent.ts","../src/components/Personalization/index.tsx","../src/components/Slot/index.tsx"],"sourcesContent":["import csrPlug, {Plug} from '@croct/plug';\n\nexport function isSsr(): boolean {\n return typeof window === 'undefined'\n || typeof window.document === 'undefined'\n || typeof window.document.createElement === 'undefined';\n}\n\nexport const croct: Plug = !isSsr() ? csrPlug : new Proxy(csrPlug, {\n get(_, property: keyof Plug) {\n switch (property) {\n case 'initialized':\n return false;\n\n case 'plug':\n return () => {\n // no-op\n };\n\n case 'unplug':\n return () => Promise.resolve();\n\n default:\n throw new Error(\n `Property croct.${String(property)} is not supported on server-side (SSR). Consider refactoring `\n + 'the logic as a side-effect (useEffect) or a client-side callback (onClick, onChange, etc).',\n );\n }\n },\n});\n\n","import {createContext, FunctionComponent, PropsWithChildren, ReactElement, useContext, useEffect, useMemo} from 'react';\nimport {Configuration, Plug} from '@croct/plug';\nimport {croct} from './ssr-polyfills';\n\nexport type CroctProviderProps = PropsWithChildren<Configuration & Required<Pick<Configuration, 'appId'>>>;\n\nexport const CroctContext = createContext<{plug: Plug}|null>(null);\nCroctContext.displayName = 'CroctContext';\n\nexport const CroctProvider: FunctionComponent<CroctProviderProps> = ({children, ...configuration}): ReactElement => {\n const parent = useContext(CroctContext);\n\n if (parent !== null) {\n throw new Error(\n 'You cannot render <CroctProvider> inside another <CroctProvider>. '\n + 'Croct should only be initialized once in the application.',\n );\n }\n\n const context = useMemo(() => ({\n get plug() {\n if (!croct.initialized) {\n croct.plug(configuration);\n }\n\n return croct;\n },\n }), [configuration]);\n\n useEffect(() => {\n croct.plug(configuration);\n\n return () => {\n croct.unplug();\n };\n }, []);\n\n return (\n <CroctContext.Provider value={context}>\n {children}\n </CroctContext.Provider>\n );\n};\n","export type EntryLoader<R> = (...args: any) => Promise<R>;\n\nexport type EntryOptions<R> = {\n cacheKey: string,\n loader: EntryLoader<R>,\n fallback?: R,\n expiration?: number,\n};\n\ntype Entry<R = any> = {\n promise: Promise<any>,\n result?: R,\n dispose: () => void,\n timeout?: number,\n error?: any,\n};\n\nexport class Cache {\n private readonly cache: Record<string, Entry> = {};\n\n private readonly defaultExpiration: number;\n\n public constructor(defaultExpiration: number) {\n this.defaultExpiration = defaultExpiration;\n }\n\n public load<R>(configuration: EntryOptions<R>): R {\n const {cacheKey, loader, fallback, expiration = this.defaultExpiration} = configuration;\n\n const cachedEntry = this.get<R>(cacheKey);\n\n if (cachedEntry !== undefined) {\n if (cachedEntry.error !== undefined) {\n if (fallback !== undefined) {\n return fallback;\n }\n\n throw cachedEntry.error;\n }\n\n if (cachedEntry.result !== undefined) {\n return cachedEntry.result;\n }\n\n throw cachedEntry.promise;\n }\n\n const entry: Entry<R> = {\n dispose: () => {\n if (entry.timeout !== undefined || expiration < 0) {\n return;\n }\n\n entry.timeout = window.setTimeout(\n (): void => {\n delete this.cache[cacheKey];\n },\n expiration,\n );\n },\n promise: loader()\n .then((result): R => {\n entry.result = result;\n\n return result;\n })\n .catch(error => {\n entry.error = error;\n })\n .finally(() => {\n entry.dispose();\n }),\n };\n\n this.cache[cacheKey] = entry;\n\n throw entry.promise;\n }\n\n public get<R>(cacheKey: string): Entry<R>|undefined {\n const entry = this.cache[cacheKey];\n\n if (entry === undefined) {\n return undefined;\n }\n\n if (entry.timeout !== undefined) {\n clearTimeout(entry.timeout);\n\n delete entry.timeout;\n\n entry.dispose();\n }\n\n return entry;\n }\n}\n","import {useEffect, useState} from 'react';\nimport {Cache, EntryOptions} from './Cache';\n\nconst cache = new Cache(60 * 1000);\n\nexport type CacheOptions<R> = EntryOptions<R> & {\n initial?: R,\n};\n\nexport function useLoader<R>({initial, ...options}: CacheOptions<R>): R {\n const loadedValue: R|undefined = cache.get<R>(options.cacheKey)?.result;\n const [value, setValue] = useState(loadedValue !== undefined ? loadedValue : initial);\n const [isUnmounted, setUnmounted] = useState(false);\n\n useEffect(\n () => {\n if (initial !== undefined) {\n try {\n setValue(cache.load(options));\n } catch (result: unknown) {\n if (result instanceof Promise) {\n result.then((resolvedValue: R) => {\n if (!isUnmounted) {\n setValue(resolvedValue);\n }\n });\n\n return;\n }\n\n setValue(undefined);\n\n return;\n }\n }\n\n return () => {\n setUnmounted(true);\n };\n },\n [],\n );\n\n if (value === undefined) {\n return cache.load(options);\n }\n\n return value;\n}\n","import {Plug} from '@croct/plug';\nimport {useContext} from 'react';\nimport {CroctContext} from '../CroctProvider';\n\nexport function useCroct(): Plug {\n const context = useContext(CroctContext);\n\n if (context === null) {\n throw new Error('useCroct() can only be used in the context of a <CroctProvider> component.');\n }\n\n return context.plug;\n}\n","import {JsonValue} from '@croct/plug/sdk/json';\nimport {EvaluationOptions} from '@croct/sdk/facade/evaluatorFacade';\nimport {useLoader} from './useLoader';\nimport {useCroct} from './useCroct';\nimport {isSsr} from '../ssr-polyfills';\n\nfunction cleanEvaluationOptions(options: EvaluationOptions): EvaluationOptions {\n const result: EvaluationOptions = {};\n\n for (const [key, value] of Object.entries(options)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport type UseEvaluationOptions<I, F> = EvaluationOptions & {\n initial?: I,\n fallback?: F,\n cacheKey?: string,\n expiration?: number,\n};\n\ntype UseEvaluationHook = <T extends JsonValue, I = T, F = T>(\n expression: string,\n options?: UseEvaluationOptions<I, F>,\n) => T | I | F;\n\nfunction useCsrEvaluation<T = JsonValue, I = T, F = T>(\n expression: string,\n options: UseEvaluationOptions<I, F> = {},\n): T | I | F {\n const {cacheKey, fallback, initial, expiration, ...evaluationOptions} = options;\n const croct = useCroct();\n\n return useLoader<T | I | F>({\n cacheKey: `useEvaluation:${cacheKey ?? ''}:${expression}:${JSON.stringify(options.attributes ?? '')}`,\n loader: () => croct.evaluate<T & JsonValue>(expression, cleanEvaluationOptions(evaluationOptions)),\n initial: initial,\n fallback: fallback,\n expiration: expiration,\n });\n}\n\nfunction useSsrEvaluation<T = JsonValue, I = T, F = T>(\n _: string,\n {initial}: UseEvaluationOptions<I, F> = {},\n): T | I | F {\n if (initial === undefined) {\n throw new Error('The initial value is required for server-side rendering (SSR).');\n }\n\n return initial;\n}\n\nexport const useEvaluation: UseEvaluationHook = isSsr() ? useSsrEvaluation : useCsrEvaluation;\n","import {SlotContent, SlotId, SlotMap} from '@croct/plug/fetch';\nimport {NullableJsonObject} from '@croct/plug/sdk/json';\nimport {useLoader} from './useLoader';\nimport {useCroct} from './useCroct';\nimport {isSsr} from '../ssr-polyfills';\n\nexport type UseContentOptions<I, F> = {\n fallback?: F,\n initial?: I,\n cacheKey?: string,\n expiration?: number,\n};\n\nfunction useCsrContent<I, F>(id: SlotId, options: UseContentOptions<I, F> = {}): SlotContent<SlotId> | I | F {\n const {fallback, initial, cacheKey, expiration} = options;\n const croct = useCroct();\n\n return useLoader({\n cacheKey: `useContent:${cacheKey ?? ''}:${id}`,\n loader: () => croct.fetch<SlotContent<SlotId>>(id).then(({payload}) => payload),\n initial: initial,\n fallback: fallback,\n expiration: expiration,\n });\n}\n\nfunction useSsrContent<I, F>(_: SlotId, {initial}: UseContentOptions<I, F> = {}): SlotContent<SlotId> | I | F {\n if (initial === undefined) {\n throw new Error('The initial value is required for server-side rendering (SSR).');\n }\n\n return initial;\n}\n\ntype UseContentHook = {\n <P extends NullableJsonObject, I = P, F = P>(\n id: keyof SlotMap extends never ? string : never,\n options?: UseContentOptions<I, F>\n ): P | I | F,\n\n <S extends keyof SlotMap>(\n id: S,\n options?: UseContentOptions<never, never>\n ): SlotContent<S>,\n\n <I, S extends keyof SlotMap>(\n id: S,\n options?: UseContentOptions<I, never>\n ): SlotContent<S> | I,\n\n <F, S extends keyof SlotMap>(\n id: S,\n options?: UseContentOptions<never, F>\n ): SlotContent<S> | F,\n\n <I, F, S extends keyof SlotMap>(\n id: S,\n options?: UseContentOptions<I, F>\n ): SlotContent<S> | I | F,\n};\n\nexport const useContent: UseContentHook = isSsr() ? useSsrContent : useCsrContent;\n","import {ReactChild, ReactElement, Fragment} from 'react';\nimport {JsonValue} from '@croct/plug/sdk/json';\nimport {UseEvaluationOptions, useEvaluation} from '../../hooks';\n\ntype Renderer<T> = (result: T) => ReactChild;\n\nexport type PersonalizationProps<T extends JsonValue = JsonValue, I = T, F = T> = UseEvaluationOptions<I, F> & {\n expression: string,\n children: Renderer<T | I | F>,\n};\n\nexport function Personalization<T extends JsonValue, I, F>(\n props:\n Extract<T | I | F, JsonValue> extends never\n ? PersonalizationProps\n : PersonalizationProps<T, I, F>,\n): ReactElement;\n\nexport function Personalization<I, F>(props: PersonalizationProps<JsonValue, I, F>): ReactElement {\n const {expression, children, ...options} = props;\n const result = useEvaluation(expression, options);\n\n return (<Fragment>{children(result)}</Fragment>);\n}\n","import {Fragment, ReactChild, ReactElement} from 'react';\nimport {SlotContent, SlotId, SlotMap} from '@croct/plug/fetch';\nimport {NullableJsonObject} from '@croct/plug/sdk/json';\nimport {useContent, UseContentOptions} from '../../hooks';\n\ntype Renderer<P> = (props: P) => ReactChild;\n\nexport type SlotProps<P, I = P, F = P, S extends SlotId = SlotId> = UseContentOptions<I, F> & {\n id: S,\n children: Renderer<P | I | F>,\n};\n\ntype SlotComponent = {\n <P, I, F>(\n props:\n Extract<P | I | F, NullableJsonObject> extends never\n ? SlotProps<NullableJsonObject, never, never, keyof SlotMap extends never ? string : never>\n : SlotProps<P, I, F, keyof SlotMap extends never ? string : never>\n ): ReactElement,\n\n <S extends keyof SlotMap>(props: SlotProps<SlotContent<S>, never, never, S>): ReactElement,\n\n <I, S extends keyof SlotMap>(props: SlotProps<SlotContent<S>, I, never, S>): ReactElement,\n\n <F, S extends keyof SlotMap>(props: SlotProps<SlotContent<S>, never, F, S>): ReactElement,\n\n <I, F, S extends keyof SlotMap>(props: SlotProps<SlotContent<S>, I, F, S>): ReactElement,\n\n (props: SlotProps<void, void, void>): ReactElement,\n};\n\nexport const Slot: SlotComponent = <I, F>(props: SlotProps<NullableJsonObject, I, F>): ReactElement => {\n const {id, children, ...options} = props;\n const data: SlotContent<SlotId> | I | F = useContent(id, options);\n\n return <Fragment>{children(data)}</Fragment>;\n};\n"],"names":["isSsr","window","document","createElement","croct","csrPlug","Proxy","get","_","property","Promise","resolve","Error","String","CroctContext","createContext","displayName","CroctProvider","children","configuration","_excluded","parent","useContext","context","useMemo","plug","initialized","useEffect","unplug","_jsx","Provider","value","Cache","constructor","defaultExpiration","cache","load","cacheKey","loader","fallback","expiration","cachedEntry","undefined","error","result","promise","entry","dispose","timeout","setTimeout","then","catch","finally","clearTimeout","useLoader","initial","options","loadedValue","setValue","useState","isUnmounted","setUnmounted","resolvedValue","useCroct","cleanEvaluationOptions","key","Object","entries","useCsrEvaluation","expression","evaluationOptions","JSON","stringify","attributes","evaluate","useSsrEvaluation","useEvaluation","useCsrContent","id","fetch","payload","useSsrContent","useContent","Personalization","props","Fragment","Slot","data"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;SAEgBA,QAAK;AACjB,EAAA,OAAO,OAAOC,MAAP,KAAkB,WAAlB,IACA,OAAOA,MAAM,CAACC,QAAd,KAA2B,WAD3B,IAEA,OAAOD,MAAM,CAACC,QAAP,CAAgBC,aAAvB,KAAyC,WAFhD,CAAA;AAGH,CAAA;AAEM,IAAMC,KAAK,GAAS,CAACJ,KAAK,EAAN,GAAWK,2BAAX,GAAqB,IAAIC,KAAJ,CAAUD,2BAAV,EAAmB;AAC/DE,EAAAA,GAAG,CAACC,CAAD,EAAIC,QAAJ,EAAwB;AACvB,IAAA,QAAQA,QAAR;AACI,MAAA,KAAK,aAAL;AACI,QAAA,OAAO,KAAP,CAAA;;AAEJ,MAAA,KAAK,MAAL;AACI,QAAA,OAAO,MAAK;SAAZ,CAAA;;AAIJ,MAAA,KAAK,QAAL;AACI,QAAA,OAAO,MAAMC,OAAO,CAACC,OAAR,EAAb,CAAA;;AAEJ,MAAA;QACI,MAAM,IAAIC,KAAJ,CACF,iBAAkBC,GAAAA,MAAM,CAACJ,QAAD,CAAxB,GACE,+DAAA,GAAA,4FAFA,CAAN,CAAA;AAbR,KAAA;AAkBH,GAAA;;AApB8D,CAAnB,CAAzC;;;ICFMK,YAAY,gBAAGC,mBAAa,CAAoB,IAApB,EAAlC;AACPD,YAAY,CAACE,WAAb,GAA2B,cAA3B,CAAA;AAEO,IAAMC,aAAa,GAA0C,IAA+C,IAAA;EAAA,IAA9C;AAACC,IAAAA,QAAAA;GAA6C,GAAA,IAAA;AAAA,MAAhCC,aAAgC,GAAA,6BA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AACH,GAAA;;AAED,EAAA,OAAO2C,OAAP,CAAA;AACH,CAAA;;IA6BY2B,UAAU,GAAmBlF,KAAK,EAAKiF,GAAAA,aAAL,GAAqBJ;;;AC3C9D,SAAUM,eAAV,CAAgCC,KAAhC,EAA4E;EAC9E,IAAM;IAACf,UAAD;AAAanD,IAAAA,QAAAA;AAAb,GAAA,GAAqCkE,KAA3C;MAAgC5B,OAAhC,iCAA2C4B,KAA3C,EAAAhE,WAAA,CAAA,CAAA;;AACA,EAAA,IAAMwB,MAAM,GAAGgC,aAAa,CAACP,UAAD,EAAab,OAAb,CAA5B,CAAA;EAEA,OAAQ3B,cAAC,CAAAwD,cAAA,EAAU;IAAAnE,QAAA,EAAAA,QAAQ,CAAC0B,MAAD,CAAA;AAAR,GAAV,CAAT,CAAA;AACH;;;ACQY0C,IAAAA,IAAI,GAAyBF,KAAP,IAAmE;EAClG,IAAM;IAACN,EAAD;AAAK5D,IAAAA,QAAAA;AAAL,GAAA,GAA6BkE,KAAnC;MAAwB5B,OAAxB,iCAAmC4B,KAAnC,EAAA,SAAA,CAAA,CAAA;;AACA,EAAA,IAAMG,IAAI,GAAgCL,UAAU,CAACJ,EAAD,EAAKtB,OAAL,CAApD,CAAA;EAEA,OAAO3B,cAAA,CAACwD,cAAD,EAAW;IAAAnE,QAAA,EAAAA,QAAQ,CAACqE,IAAD,CAAA;AAAR,GAAX,CAAP,CAAA;AACH;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uDAAqC;AACrC,mDAAiC;AACjC,kDAAgC;AAChC,0CAAwB;AACxB,+CAA6B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@croct/plug-react",
3
- "version": "0.4.2",
3
+ "version": "0.5.0-next.2",
4
4
  "description": "React components and hooks to plug your React applications into Croct.",
5
5
  "author": {
6
6
  "name": "Croct",
@@ -25,11 +25,10 @@
25
25
  "node": ">=10"
26
26
  },
27
27
  "scripts": {
28
- "lint": "eslint 'src/**/*.ts' 'src/**/*.tsx' 'examples/**/*.ts' 'examples/**/*.tsx'",
28
+ "lint": "eslint 'src/**/*.ts' 'src/**/*.tsx'",
29
29
  "test": "jest -c jest.config.js --coverage",
30
30
  "validate": "tsc --noEmit",
31
- "build": "tsc",
32
- "bundle": "microbundle --jsx React.createElement --no-compress --format modern,cjs",
31
+ "build": "tsc -p tsconfig.build.json",
33
32
  "storybook": "start-storybook -s ./.storybook/static -p 6006 --no-manager-cache",
34
33
  "build-storybook": "build-storybook -s ./.storybook/static"
35
34
  },
@@ -38,55 +37,43 @@
38
37
  "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
39
38
  },
40
39
  "dependencies": {
41
- "@croct/plug": "^0.10.1"
40
+ "@croct/plug": "^0.11.0-alpha.4",
41
+ "@croct/sdk": "^0.11.0-alpha.3"
42
42
  },
43
43
  "devDependencies": {
44
- "@babel/core": "^7.18.5",
45
- "@babel/preset-env": "^7.18.2",
46
- "@babel/preset-react": "^7.17.12",
47
- "@babel/preset-typescript": "^7.17.12",
48
- "@storybook/addon-actions": "^6.5.9",
49
- "@storybook/addon-essentials": "^6.5.9",
50
- "@storybook/addon-links": "^6.5.9",
51
- "@storybook/builder-webpack5": "^6.5.9",
52
- "@storybook/manager-webpack5": "^6.5.9",
53
- "@storybook/react": "^6.5.9",
54
- "@testing-library/jest-dom": "^5.16.4",
55
- "@testing-library/react": "^13.3.0",
56
- "@testing-library/react-hooks": "^8.0.0",
57
- "@types/jest": "^28.1.2",
58
- "@types/node": "^16.11.41",
59
- "@types/react": "^18.0.14",
60
- "@types/react-dom": "^18.0.5",
61
- "@typescript-eslint/eslint-plugin": "^5.28.0",
62
- "@typescript-eslint/parser": "^5.28.0",
63
- "babel-eslint": "^10.1.0",
64
- "babel-jest": "^28.1.1",
65
- "babel-loader": "^8.2.5",
66
- "eslint": "^8.17.0",
67
- "eslint-config-airbnb-base": "^15.0.0",
68
- "eslint-config-standard": "^17.0.0",
69
- "eslint-config-standard-react": "^11.0.1",
70
- "eslint-plugin-import": "^2.26.0",
71
- "eslint-plugin-jest": "^26.5.3",
72
- "eslint-plugin-n": "^15.2.3",
73
- "eslint-plugin-node": "^11.1.0",
74
- "eslint-plugin-promise": "^6.0.0",
75
- "eslint-plugin-react": "^7.30.0",
76
- "eslint-plugin-standard": "^5.0.0",
77
- "jest": "^28.1.1",
78
- "jest-environment-jsdom": "^28.1.1",
79
- "jest-environment-node": "^28.1.1",
80
- "microbundle": "^0.15.0",
44
+ "@babel/core": "^7.20.2",
45
+ "@babel/preset-env": "^7.20.2",
46
+ "@babel/preset-react": "^7.18.6",
47
+ "@babel/preset-typescript": "^7.18.6",
48
+ "@croct/eslint-plugin": "^0.6.3",
49
+ "@storybook/addon-actions": "^6.5.13",
50
+ "@storybook/addon-essentials": "^6.5.13",
51
+ "@storybook/addon-links": "^6.5.13",
52
+ "@storybook/builder-webpack5": "^6.5.13",
53
+ "@storybook/manager-webpack5": "^6.5.13",
54
+ "@storybook/react": "^6.5.13",
55
+ "@testing-library/jest-dom": "^5.16.5",
56
+ "@testing-library/react": "^13.4.0",
57
+ "@types/jest": "^29.2.3",
58
+ "@types/node": "^18.11.9",
59
+ "@types/react": "^18.0.25",
60
+ "@types/react-dom": "^18.0.9",
61
+ "@typescript-eslint/eslint-plugin": "^5.43.0",
62
+ "@typescript-eslint/parser": "^5.43.0",
63
+ "babel-loader": "^9.1.0",
64
+ "eslint": "^8.28.0",
65
+ "jest": "^29.0.0",
66
+ "jest-environment-jsdom": "^29.0.0",
67
+ "jest-environment-node": "^29.0.0",
81
68
  "react": "^18.2.0",
82
69
  "react-dom": "^18.2.0",
83
70
  "ts-node": "^10.8.1",
84
- "typescript": "^4.7.3",
85
- "webpack": "^5.73.0"
71
+ "typescript": "^4.9.3",
72
+ "webpack": "^5.75.0"
86
73
  },
87
74
  "files": [
88
75
  "**/*.js",
89
- "**/*.js.map",
90
- "**/*.ts"
76
+ "**/*.ts",
77
+ "**/*.map"
91
78
  ]
92
79
  }
@@ -0,0 +1,59 @@
1
+ import {Evaluator} from '@croct/sdk/evaluator';
2
+ import {evaluate, EvaluationOptions} from './evaluate';
3
+
4
+ const mockEvaluate: Evaluator['evaluate'] = jest.fn();
5
+
6
+ jest.mock(
7
+ '@croct/sdk/evaluator',
8
+ () => ({
9
+ __esModule: true,
10
+ /*
11
+ * eslint-disable-next-line prefer-arrow-callback --
12
+ * The mock can't be an arrow function because calling new on
13
+ * an arrow function is not allowed in JavaScript.
14
+ */
15
+ Evaluator: jest.fn(function constructor(this: Evaluator) {
16
+ this.evaluate = mockEvaluate;
17
+ }),
18
+ }),
19
+ );
20
+
21
+ describe('evaluate', () => {
22
+ const apiKey = '00000000-0000-0000-0000-000000000000';
23
+
24
+ afterEach(() => {
25
+ jest.clearAllMocks();
26
+ });
27
+
28
+ it('should forward the call to the evaluator', async () => {
29
+ const options: EvaluationOptions = {
30
+ apiKey: apiKey,
31
+ timeout: 100,
32
+ };
33
+
34
+ const query = 'true';
35
+
36
+ jest.mocked(mockEvaluate).mockResolvedValue(true);
37
+
38
+ await expect(evaluate(query, options)).resolves.toBe(true);
39
+
40
+ expect(Evaluator).toHaveBeenCalledWith({
41
+ apiKey: options.apiKey,
42
+ });
43
+
44
+ expect(mockEvaluate).toHaveBeenCalledWith(query, {
45
+ timeout: options.timeout,
46
+ });
47
+ });
48
+
49
+ it('should return the fallback value on error', async () => {
50
+ const options: EvaluationOptions = {
51
+ apiKey: apiKey,
52
+ fallback: false,
53
+ };
54
+
55
+ jest.mocked(mockEvaluate).mockRejectedValue(new Error('error'));
56
+
57
+ await expect(evaluate('true', options)).resolves.toBe(false);
58
+ });
59
+ });
@@ -0,0 +1,19 @@
1
+ import {Evaluator, EvaluationOptions as BaseOptions} from '@croct/sdk/evaluator';
2
+ import {JsonValue} from '@croct/plug/sdk/json';
3
+
4
+ export type EvaluationOptions<T extends JsonValue = JsonValue> = BaseOptions & {
5
+ apiKey: string,
6
+ fallback?: T,
7
+ };
8
+
9
+ export function evaluate<T extends JsonValue>(query: string, options: EvaluationOptions<T>): Promise<T> {
10
+ const {apiKey, fallback, ...rest} = options;
11
+ const promise = (new Evaluator({apiKey: apiKey}))
12
+ .evaluate(query, rest) as Promise<T>;
13
+
14
+ if (fallback !== undefined) {
15
+ return promise.catch(() => fallback);
16
+ }
17
+
18
+ return promise;
19
+ }