@spur.us/monocle-react 1.1.1-canary.v20250918211544 → 1.2.0-canary.v20251001171618
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.
- package/.turbo/turbo-build.log +10 -10
- package/CHANGELOG.md +16 -0
- package/dist/index.d.mts +14 -3
- package/dist/index.d.ts +14 -3
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/contexts/MonocleProvider.tsx +8 -1
- package/src/types.ts +14 -3
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
> @spur.us/monocle-react@1.
|
|
2
|
+
> @spur.us/monocle-react@1.2.0-canary.v20251001171618 build /home/runner/work/javascript/javascript/packages/monocle-react
|
|
3
3
|
> tsup
|
|
4
4
|
|
|
5
5
|
[34mCLI[39m Building entry: {"index":"src/index.ts"}
|
|
@@ -10,13 +10,13 @@
|
|
|
10
10
|
[34mCLI[39m Cleaning output folder
|
|
11
11
|
[34mCJS[39m Build start
|
|
12
12
|
[34mESM[39m Build start
|
|
13
|
-
[32mCJS[39m [1mdist/index.js [22m[32m6.
|
|
14
|
-
[32mCJS[39m [1mdist/index.js.map [22m[
|
|
15
|
-
[32mCJS[39m ⚡️ Build success in
|
|
16
|
-
[32mESM[39m [1mdist/index.mjs [22m[32m4.
|
|
17
|
-
[32mESM[39m [1mdist/index.mjs.map [22m[32m9.
|
|
18
|
-
[32mESM[39m ⚡️ Build success in
|
|
13
|
+
[32mCJS[39m [1mdist/index.js [22m[32m6.12 KB[39m
|
|
14
|
+
[32mCJS[39m [1mdist/index.js.map [22m[32m10.11 KB[39m
|
|
15
|
+
[32mCJS[39m ⚡️ Build success in 49ms
|
|
16
|
+
[32mESM[39m [1mdist/index.mjs [22m[32m4.32 KB[39m
|
|
17
|
+
[32mESM[39m [1mdist/index.mjs.map [22m[32m9.96 KB[39m
|
|
18
|
+
[32mESM[39m ⚡️ Build success in 49ms
|
|
19
19
|
[34mDTS[39m Build start
|
|
20
|
-
[32mDTS[39m ⚡️ Build success in
|
|
21
|
-
[32mDTS[39m [1mdist/index.d.ts [22m[32m1.
|
|
22
|
-
[32mDTS[39m [1mdist/index.d.mts [22m[32m1.
|
|
20
|
+
[32mDTS[39m ⚡️ Build success in 1934ms
|
|
21
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m1.55 KB[39m
|
|
22
|
+
[32mDTS[39m [1mdist/index.d.mts [22m[32m1.55 KB[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @spur.us/monocle-react
|
|
2
2
|
|
|
3
|
+
## 1.1.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f12a046: Fix refresh logic in `MonocleProvider`
|
|
8
|
+
- 74d2cb6: Fix `onAssessment` function signature in `MonocleConfig` type.
|
|
9
|
+
|
|
10
|
+
Fix `MonocleProvider` issue where assessment isn't set.
|
|
11
|
+
|
|
12
|
+
- 5dd4555: Fix refresh return type in `MonocleContextType`
|
|
13
|
+
- a6967b1: Set isLoading to false after successful refresh
|
|
14
|
+
- Updated dependencies [abccf0d]
|
|
15
|
+
- Updated dependencies [74d2cb6]
|
|
16
|
+
- Updated dependencies [c9b9f35]
|
|
17
|
+
- @spur.us/types@0.3.0
|
|
18
|
+
|
|
3
19
|
## 1.1.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/dist/index.d.mts
CHANGED
|
@@ -5,12 +5,23 @@ import React from 'react';
|
|
|
5
5
|
* @interface MonocleProviderProps
|
|
6
6
|
*/
|
|
7
7
|
interface MonocleProviderProps {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The child components to be wrapped by the MonocleProvider.
|
|
10
|
+
*/
|
|
9
11
|
children: React.ReactNode;
|
|
10
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* The publishable key used for authentication with Monocle.
|
|
14
|
+
*/
|
|
11
15
|
publishableKey: string;
|
|
12
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided
|
|
18
|
+
*/
|
|
13
19
|
domain?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Optional cpd parameter to add an arbitrary, session-based tag to the Monocle Assessment.
|
|
22
|
+
* This can be used for session verification, tracking, and analysis on your backend.
|
|
23
|
+
*/
|
|
24
|
+
cpd?: string;
|
|
14
25
|
}
|
|
15
26
|
|
|
16
27
|
interface MonocleContextType {
|
package/dist/index.d.ts
CHANGED
|
@@ -5,12 +5,23 @@ import React from 'react';
|
|
|
5
5
|
* @interface MonocleProviderProps
|
|
6
6
|
*/
|
|
7
7
|
interface MonocleProviderProps {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The child components to be wrapped by the MonocleProvider.
|
|
10
|
+
*/
|
|
9
11
|
children: React.ReactNode;
|
|
10
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* The publishable key used for authentication with Monocle.
|
|
14
|
+
*/
|
|
11
15
|
publishableKey: string;
|
|
12
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided
|
|
18
|
+
*/
|
|
13
19
|
domain?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Optional cpd parameter to add an arbitrary, session-based tag to the Monocle Assessment.
|
|
22
|
+
* This can be used for session verification, tracking, and analysis on your backend.
|
|
23
|
+
*/
|
|
24
|
+
cpd?: string;
|
|
14
25
|
}
|
|
15
26
|
|
|
16
27
|
interface MonocleContextType {
|
package/dist/index.js
CHANGED
|
@@ -74,7 +74,8 @@ var MonocleContext = (0, import_react2.createContext)(null);
|
|
|
74
74
|
var MonocleProviderComponent = ({
|
|
75
75
|
children,
|
|
76
76
|
publishableKey,
|
|
77
|
-
domain = DOMAIN
|
|
77
|
+
domain = DOMAIN,
|
|
78
|
+
cpd
|
|
78
79
|
}) => {
|
|
79
80
|
const [assessment, setAssessment] = (0, import_react2.useState)(void 0);
|
|
80
81
|
const [isLoading, setIsLoading] = (0, import_react2.useState)(true);
|
|
@@ -94,7 +95,11 @@ var MonocleProviderComponent = ({
|
|
|
94
95
|
const script = document.createElement("script");
|
|
95
96
|
script.id = "_mcl";
|
|
96
97
|
script.async = true;
|
|
97
|
-
|
|
98
|
+
let src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
|
|
99
|
+
if (cpd) {
|
|
100
|
+
src += `&cpd=${cpd}`;
|
|
101
|
+
}
|
|
102
|
+
script.src = src;
|
|
98
103
|
script.onload = () => {
|
|
99
104
|
resolve();
|
|
100
105
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/contexts/MonocleProvider.tsx","../src/utils/useMaxAllowedInstancesGuard.tsx","../src/constants.ts"],"sourcesContent":["export * from './contexts';\n\nexport type { MonocleProviderProps } from './types';\n","import React, {\n createContext,\n useContext,\n useEffect,\n useState,\n useMemo,\n useCallback,\n} from 'react';\nimport { withMaxAllowedInstancesGuard } from '../utils';\nimport { MonocleProviderProps } from '../types';\nimport { DOMAIN } from '../constants';\n\ninterface MonocleContextType {\n assessment: string | undefined;\n refresh: () => Promise<void>;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst MonocleContext = createContext<MonocleContextType | null>(null);\n\nconst MonocleProviderComponent: React.FC<MonocleProviderProps> = ({\n children,\n publishableKey,\n domain = DOMAIN,\n}) => {\n const [assessment, setAssessment] = useState<string | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const loadScript = () => {\n return new Promise<void>((resolve, reject) => {\n const existingScript = document.getElementById('_mcl');\n if (existingScript) {\n // If script exists but hasn't loaded yet, wait for it\n if (!window.MCL) {\n existingScript.onload = () => resolve();\n existingScript.onerror = () =>\n reject(new Error('Failed to load Monocle script'));\n } else {\n resolve();\n }\n return;\n }\n\n const script = document.createElement('script');\n script.id = '_mcl';\n script.async = true;\n script.src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;\n script.onload = () => {\n resolve();\n };\n script.onerror = (_e) => {\n console.error('MonocleProvider: Script failed to load');\n reject(new Error('Failed to load Monocle script'));\n };\n document.head.appendChild(script);\n });\n };\n\n const refresh = useCallback(async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n if (window.MCL) {\n await window.MCL.refresh();\n } else {\n throw new Error('MCL object not found on window');\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Unknown error occurred')\n );\n setIsLoading(false);\n }\n }, []);\n\n useEffect(() => {\n const initializeMCL = async () => {\n try {\n await loadScript();\n if (window.MCL) {\n // Configure MCL with our callback to receive assessment updates\n await window.MCL.configure({\n onAssessment: (assessment: string) => {\n setAssessment(assessment);\n setIsLoading(false);\n },\n });\n\n // Check if assessment is already available\n const existingAssessment = window.MCL.getAssessment();\n if (existingAssessment) {\n setAssessment(existingAssessment);\n setIsLoading(false);\n }\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Failed to initialize MCL')\n );\n setIsLoading(false);\n }\n };\n\n // Only initialize if we don't already have an assessment\n if (!assessment) {\n initializeMCL();\n }\n\n // Cleanup function to reset callback on unmount\n return () => {\n if (window.MCL) {\n window.MCL.configure({ onAssessment: undefined });\n }\n };\n }, [publishableKey, domain]);\n\n const contextValue = useMemo(\n () => ({ assessment, refresh, isLoading, error }),\n [assessment, refresh, isLoading, error]\n );\n\n return (\n <MonocleContext.Provider value={contextValue}>\n {children}\n </MonocleContext.Provider>\n );\n};\n\nexport const MonocleProvider = withMaxAllowedInstancesGuard(\n MonocleProviderComponent,\n 'MonocleProvider',\n 'Only one instance of MonocleProvider is allowed'\n);\n\n/**\n * Hook to access the Monocle context.\n *\n * @returns {MonocleContextType} The Monocle context containing assessment data, loading state, and error information\n * @throws {Error} When used outside of a MonocleProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { assessment, isLoading, error, refresh } = useMonocle();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Assessment: {assessment}</div>;\n * }\n * ```\n */\nexport const useMonocle = () => {\n const context = useContext(MonocleContext);\n if (!context) {\n throw new Error('useMonocle must be used within a MonocleProvider');\n }\n return context;\n};\n","import React from 'react';\n\nconst instanceCounter = new Map<string, number>();\n\n/**\n * A React hook that ensures a component is not instantiated more than a specified number of times.\n * Throws an error if the maximum number of instances is exceeded.\n *\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @param maxCount - The maximum number of allowed instances (defaults to 1)\n * @throws Error when the maximum number of instances is exceeded\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * useMaxAllowedInstancesGuard('MyComponent', 'Only one instance of MyComponent is allowed');\n * return <div>My Component</div>;\n * };\n * ```\n */\nexport function useMaxAllowedInstancesGuard(\n name: string,\n error: string,\n maxCount = 1\n): void {\n React.useEffect(() => {\n const count = instanceCounter.get(name) || 0;\n if (count === maxCount) {\n throw new Error(error);\n }\n instanceCounter.set(name, count + 1);\n\n return () => {\n const currentCount = instanceCounter.get(name) || 0;\n instanceCounter.set(name, Math.max(0, currentCount - 1));\n };\n }, []);\n}\n\n/**\n * A higher-order component that wraps a component with instance count protection.\n * This HOC ensures that the wrapped component cannot be instantiated more than once\n * (or a specified number of times) in the application.\n *\n * @param WrappedComponent - The component to wrap with instance count protection\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @returns A new component with instance count protection\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withMaxAllowedInstancesGuard(\n * MyComponent,\n * 'MyComponent',\n * 'Only one instance of MyComponent is allowed'\n * );\n * ```\n */\nexport function withMaxAllowedInstancesGuard<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n name: string,\n error: string\n): React.ComponentType<P> {\n const displayName =\n WrappedComponent.displayName ||\n WrappedComponent.name ||\n name ||\n 'Component';\n\n const Hoc: React.FC<P> = (props) => {\n useMaxAllowedInstancesGuard(name, error);\n return <WrappedComponent {...props} />;\n };\n\n Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;\n return Hoc;\n}\n","export const DOMAIN = 'mcl.spur.us';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAOO;;;ACPP,mBAAkB;AAwEP;AAtEX,IAAM,kBAAkB,oBAAI,IAAoB;AAmBzC,SAAS,4BACd,MACA,OACA,WAAW,GACL;AACN,eAAAC,QAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,gBAAgB,IAAI,IAAI,KAAK;AAC3C,QAAI,UAAU,UAAU;AACtB,YAAM,IAAI,MAAM,KAAK;AAAA,IACvB;AACA,oBAAgB,IAAI,MAAM,QAAQ,CAAC;AAEnC,WAAO,MAAM;AACX,YAAM,eAAe,gBAAgB,IAAI,IAAI,KAAK;AAClD,sBAAgB,IAAI,MAAM,KAAK,IAAI,GAAG,eAAe,CAAC,CAAC;AAAA,IACzD;AAAA,EACF,GAAG,CAAC,CAAC;AACP;AAqBO,SAAS,6BACd,kBACA,MACA,OACwB;AACxB,QAAM,cACJ,iBAAiB,eACjB,iBAAiB,QACjB,QACA;AAEF,QAAM,MAAmB,CAAC,UAAU;AAClC,gCAA4B,MAAM,KAAK;AACvC,WAAO,4CAAC,oBAAkB,GAAG,OAAO;AAAA,EACtC;AAEA,MAAI,cAAc,gCAAgC,WAAW;AAC7D,SAAO;AACT;;;AC7EO,IAAM,SAAS;;;AF6HlB,IAAAC,sBAAA;AA1GJ,IAAM,qBAAiB,6BAAyC,IAAI;AAEpE,IAAM,2BAA2D,CAAC;AAAA,EAChE;AAAA,EACA;AAAA,EACA,SAAS;AACX,MAAM;AACJ,QAAM,CAAC,YAAY,aAAa,QAAI,wBAA6B,MA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,cAAc,CAACC,gBAAuB;AACpC,4BAAcA,WAAU;AACxB,2BAAa,KAAK;AAAA,YACpB;AAAA,UACF,CAAC;AAGD,gBAAM,qBAAqB,OAAO,IAAI,cAAc;AACpD,cAAI,oBAAoB;AACtB,0BAAc,kBAAkB;AAChC,yBAAa,KAAK;AAAA,UACpB;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ;AAAA,UACE,eAAe,QAAQ,MAAM,IAAI,MAAM,0BAA0B;AAAA,QACnE;AACA,qBAAa,KAAK;AAAA,MACpB;AAAA,IACF;AAGA,QAAI,CAAC,YAAY;AACf,oBAAc;AAAA,IAChB;AAGA,WAAO,MAAM;AACX,UAAI,OAAO,KAAK;AACd,eAAO,IAAI,UAAU,EAAE,cAAc,OAAU,CAAC;AAAA,MAClD;AAAA,IACF;AAAA,EACF,GAAG,CAAC,gBAAgB,MAAM,CAAC;AAE3B,QAAM,mBAAe;AAAA,IACnB,OAAO,EAAE,YAAY,SAAS,WAAW,MAAM;AAAA,IAC/C,CAAC,YAAY,SAAS,WAAW,KAAK;AAAA,EACxC;AAEA,SACE,6CAAC,eAAe,UAAf,EAAwB,OAAO,cAC7B,UACH;AAEJ;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AACF;AAoBO,IAAM,aAAa,MAAM;AAC9B,QAAM,cAAU,0BAAW,cAAc;AACzC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,SAAO;AACT;","names":["import_react","React","import_jsx_runtime","assessment"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/contexts/MonocleProvider.tsx","../src/utils/useMaxAllowedInstancesGuard.tsx","../src/constants.ts"],"sourcesContent":["export * from './contexts';\n\nexport type { MonocleProviderProps } from './types';\n","import React, {\n createContext,\n useContext,\n useEffect,\n useState,\n useMemo,\n useCallback,\n} from 'react';\nimport { withMaxAllowedInstancesGuard } from '../utils';\nimport { MonocleProviderProps } from '../types';\nimport { DOMAIN } from '../constants';\n\ninterface MonocleContextType {\n assessment: string | undefined;\n refresh: () => Promise<void>;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst MonocleContext = createContext<MonocleContextType | null>(null);\n\nconst MonocleProviderComponent: React.FC<MonocleProviderProps> = ({\n children,\n publishableKey,\n domain = DOMAIN,\n cpd,\n}) => {\n const [assessment, setAssessment] = useState<string | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const loadScript = () => {\n return new Promise<void>((resolve, reject) => {\n const existingScript = document.getElementById('_mcl');\n if (existingScript) {\n // If script exists but hasn't loaded yet, wait for it\n if (!window.MCL) {\n existingScript.onload = () => resolve();\n existingScript.onerror = () =>\n reject(new Error('Failed to load Monocle script'));\n } else {\n resolve();\n }\n return;\n }\n\n const script = document.createElement('script');\n script.id = '_mcl';\n script.async = true;\n\n let src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;\n if (cpd) {\n src += `&cpd=${cpd}`;\n }\n script.src = src;\n\n script.onload = () => {\n resolve();\n };\n script.onerror = (_e) => {\n console.error('MonocleProvider: Script failed to load');\n reject(new Error('Failed to load Monocle script'));\n };\n document.head.appendChild(script);\n });\n };\n\n const refresh = useCallback(async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n if (window.MCL) {\n await window.MCL.refresh();\n } else {\n throw new Error('MCL object not found on window');\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Unknown error occurred')\n );\n setIsLoading(false);\n }\n }, []);\n\n useEffect(() => {\n const initializeMCL = async () => {\n try {\n await loadScript();\n if (window.MCL) {\n // Configure MCL with our callback to receive assessment updates\n await window.MCL.configure({\n onAssessment: (assessment: string) => {\n setAssessment(assessment);\n setIsLoading(false);\n },\n });\n\n // Check if assessment is already available\n const existingAssessment = window.MCL.getAssessment();\n if (existingAssessment) {\n setAssessment(existingAssessment);\n setIsLoading(false);\n }\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Failed to initialize MCL')\n );\n setIsLoading(false);\n }\n };\n\n // Only initialize if we don't already have an assessment\n if (!assessment) {\n initializeMCL();\n }\n\n // Cleanup function to reset callback on unmount\n return () => {\n if (window.MCL) {\n window.MCL.configure({ onAssessment: undefined });\n }\n };\n }, [publishableKey, domain]);\n\n const contextValue = useMemo(\n () => ({ assessment, refresh, isLoading, error }),\n [assessment, refresh, isLoading, error]\n );\n\n return (\n <MonocleContext.Provider value={contextValue}>\n {children}\n </MonocleContext.Provider>\n );\n};\n\nexport const MonocleProvider = withMaxAllowedInstancesGuard(\n MonocleProviderComponent,\n 'MonocleProvider',\n 'Only one instance of MonocleProvider is allowed'\n);\n\n/**\n * Hook to access the Monocle context.\n *\n * @returns {MonocleContextType} The Monocle context containing assessment data, loading state, and error information\n * @throws {Error} When used outside of a MonocleProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { assessment, isLoading, error, refresh } = useMonocle();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Assessment: {assessment}</div>;\n * }\n * ```\n */\nexport const useMonocle = () => {\n const context = useContext(MonocleContext);\n if (!context) {\n throw new Error('useMonocle must be used within a MonocleProvider');\n }\n return context;\n};\n","import React from 'react';\n\nconst instanceCounter = new Map<string, number>();\n\n/**\n * A React hook that ensures a component is not instantiated more than a specified number of times.\n * Throws an error if the maximum number of instances is exceeded.\n *\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @param maxCount - The maximum number of allowed instances (defaults to 1)\n * @throws Error when the maximum number of instances is exceeded\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * useMaxAllowedInstancesGuard('MyComponent', 'Only one instance of MyComponent is allowed');\n * return <div>My Component</div>;\n * };\n * ```\n */\nexport function useMaxAllowedInstancesGuard(\n name: string,\n error: string,\n maxCount = 1\n): void {\n React.useEffect(() => {\n const count = instanceCounter.get(name) || 0;\n if (count === maxCount) {\n throw new Error(error);\n }\n instanceCounter.set(name, count + 1);\n\n return () => {\n const currentCount = instanceCounter.get(name) || 0;\n instanceCounter.set(name, Math.max(0, currentCount - 1));\n };\n }, []);\n}\n\n/**\n * A higher-order component that wraps a component with instance count protection.\n * This HOC ensures that the wrapped component cannot be instantiated more than once\n * (or a specified number of times) in the application.\n *\n * @param WrappedComponent - The component to wrap with instance count protection\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @returns A new component with instance count protection\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withMaxAllowedInstancesGuard(\n * MyComponent,\n * 'MyComponent',\n * 'Only one instance of MyComponent is allowed'\n * );\n * ```\n */\nexport function withMaxAllowedInstancesGuard<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n name: string,\n error: string\n): React.ComponentType<P> {\n const displayName =\n WrappedComponent.displayName ||\n WrappedComponent.name ||\n name ||\n 'Component';\n\n const Hoc: React.FC<P> = (props) => {\n useMaxAllowedInstancesGuard(name, error);\n return <WrappedComponent {...props} />;\n };\n\n Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;\n return Hoc;\n}\n","export const DOMAIN = 'mcl.spur.us';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAOO;;;ACPP,mBAAkB;AAwEP;AAtEX,IAAM,kBAAkB,oBAAI,IAAoB;AAmBzC,SAAS,4BACd,MACA,OACA,WAAW,GACL;AACN,eAAAC,QAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,gBAAgB,IAAI,IAAI,KAAK;AAC3C,QAAI,UAAU,UAAU;AACtB,YAAM,IAAI,MAAM,KAAK;AAAA,IACvB;AACA,oBAAgB,IAAI,MAAM,QAAQ,CAAC;AAEnC,WAAO,MAAM;AACX,YAAM,eAAe,gBAAgB,IAAI,IAAI,KAAK;AAClD,sBAAgB,IAAI,MAAM,KAAK,IAAI,GAAG,eAAe,CAA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AY,SAAS,WAAW,KAAK;AAAA,EACxC;AAEA,SACE,6CAAC,eAAe,UAAf,EAAwB,OAAO,cAC7B,UACH;AAEJ;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AACF;AAoBO,IAAM,aAAa,MAAM;AAC9B,QAAM,cAAU,0BAAW,cAAc;AACzC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,SAAO;AACT;","names":["import_react","React","import_jsx_runtime","assessment"]}
|
package/dist/index.mjs
CHANGED
|
@@ -44,7 +44,8 @@ var MonocleContext = createContext(null);
|
|
|
44
44
|
var MonocleProviderComponent = ({
|
|
45
45
|
children,
|
|
46
46
|
publishableKey,
|
|
47
|
-
domain = DOMAIN
|
|
47
|
+
domain = DOMAIN,
|
|
48
|
+
cpd
|
|
48
49
|
}) => {
|
|
49
50
|
const [assessment, setAssessment] = useState(void 0);
|
|
50
51
|
const [isLoading, setIsLoading] = useState(true);
|
|
@@ -64,7 +65,11 @@ var MonocleProviderComponent = ({
|
|
|
64
65
|
const script = document.createElement("script");
|
|
65
66
|
script.id = "_mcl";
|
|
66
67
|
script.async = true;
|
|
67
|
-
|
|
68
|
+
let src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
|
|
69
|
+
if (cpd) {
|
|
70
|
+
src += `&cpd=${cpd}`;
|
|
71
|
+
}
|
|
72
|
+
script.src = src;
|
|
68
73
|
script.onload = () => {
|
|
69
74
|
resolve();
|
|
70
75
|
};
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/contexts/MonocleProvider.tsx","../src/utils/useMaxAllowedInstancesGuard.tsx","../src/constants.ts"],"sourcesContent":["import React, {\n createContext,\n useContext,\n useEffect,\n useState,\n useMemo,\n useCallback,\n} from 'react';\nimport { withMaxAllowedInstancesGuard } from '../utils';\nimport { MonocleProviderProps } from '../types';\nimport { DOMAIN } from '../constants';\n\ninterface MonocleContextType {\n assessment: string | undefined;\n refresh: () => Promise<void>;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst MonocleContext = createContext<MonocleContextType | null>(null);\n\nconst MonocleProviderComponent: React.FC<MonocleProviderProps> = ({\n children,\n publishableKey,\n domain = DOMAIN,\n}) => {\n const [assessment, setAssessment] = useState<string | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const loadScript = () => {\n return new Promise<void>((resolve, reject) => {\n const existingScript = document.getElementById('_mcl');\n if (existingScript) {\n // If script exists but hasn't loaded yet, wait for it\n if (!window.MCL) {\n existingScript.onload = () => resolve();\n existingScript.onerror = () =>\n reject(new Error('Failed to load Monocle script'));\n } else {\n resolve();\n }\n return;\n }\n\n const script = document.createElement('script');\n script.id = '_mcl';\n script.async = true;\n script.src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;\n script.onload = () => {\n resolve();\n };\n script.onerror = (_e) => {\n console.error('MonocleProvider: Script failed to load');\n reject(new Error('Failed to load Monocle script'));\n };\n document.head.appendChild(script);\n });\n };\n\n const refresh = useCallback(async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n if (window.MCL) {\n await window.MCL.refresh();\n } else {\n throw new Error('MCL object not found on window');\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Unknown error occurred')\n );\n setIsLoading(false);\n }\n }, []);\n\n useEffect(() => {\n const initializeMCL = async () => {\n try {\n await loadScript();\n if (window.MCL) {\n // Configure MCL with our callback to receive assessment updates\n await window.MCL.configure({\n onAssessment: (assessment: string) => {\n setAssessment(assessment);\n setIsLoading(false);\n },\n });\n\n // Check if assessment is already available\n const existingAssessment = window.MCL.getAssessment();\n if (existingAssessment) {\n setAssessment(existingAssessment);\n setIsLoading(false);\n }\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Failed to initialize MCL')\n );\n setIsLoading(false);\n }\n };\n\n // Only initialize if we don't already have an assessment\n if (!assessment) {\n initializeMCL();\n }\n\n // Cleanup function to reset callback on unmount\n return () => {\n if (window.MCL) {\n window.MCL.configure({ onAssessment: undefined });\n }\n };\n }, [publishableKey, domain]);\n\n const contextValue = useMemo(\n () => ({ assessment, refresh, isLoading, error }),\n [assessment, refresh, isLoading, error]\n );\n\n return (\n <MonocleContext.Provider value={contextValue}>\n {children}\n </MonocleContext.Provider>\n );\n};\n\nexport const MonocleProvider = withMaxAllowedInstancesGuard(\n MonocleProviderComponent,\n 'MonocleProvider',\n 'Only one instance of MonocleProvider is allowed'\n);\n\n/**\n * Hook to access the Monocle context.\n *\n * @returns {MonocleContextType} The Monocle context containing assessment data, loading state, and error information\n * @throws {Error} When used outside of a MonocleProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { assessment, isLoading, error, refresh } = useMonocle();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Assessment: {assessment}</div>;\n * }\n * ```\n */\nexport const useMonocle = () => {\n const context = useContext(MonocleContext);\n if (!context) {\n throw new Error('useMonocle must be used within a MonocleProvider');\n }\n return context;\n};\n","import React from 'react';\n\nconst instanceCounter = new Map<string, number>();\n\n/**\n * A React hook that ensures a component is not instantiated more than a specified number of times.\n * Throws an error if the maximum number of instances is exceeded.\n *\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @param maxCount - The maximum number of allowed instances (defaults to 1)\n * @throws Error when the maximum number of instances is exceeded\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * useMaxAllowedInstancesGuard('MyComponent', 'Only one instance of MyComponent is allowed');\n * return <div>My Component</div>;\n * };\n * ```\n */\nexport function useMaxAllowedInstancesGuard(\n name: string,\n error: string,\n maxCount = 1\n): void {\n React.useEffect(() => {\n const count = instanceCounter.get(name) || 0;\n if (count === maxCount) {\n throw new Error(error);\n }\n instanceCounter.set(name, count + 1);\n\n return () => {\n const currentCount = instanceCounter.get(name) || 0;\n instanceCounter.set(name, Math.max(0, currentCount - 1));\n };\n }, []);\n}\n\n/**\n * A higher-order component that wraps a component with instance count protection.\n * This HOC ensures that the wrapped component cannot be instantiated more than once\n * (or a specified number of times) in the application.\n *\n * @param WrappedComponent - The component to wrap with instance count protection\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @returns A new component with instance count protection\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withMaxAllowedInstancesGuard(\n * MyComponent,\n * 'MyComponent',\n * 'Only one instance of MyComponent is allowed'\n * );\n * ```\n */\nexport function withMaxAllowedInstancesGuard<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n name: string,\n error: string\n): React.ComponentType<P> {\n const displayName =\n WrappedComponent.displayName ||\n WrappedComponent.name ||\n name ||\n 'Component';\n\n const Hoc: React.FC<P> = (props) => {\n useMaxAllowedInstancesGuard(name, error);\n return <WrappedComponent {...props} />;\n };\n\n Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;\n return Hoc;\n}\n","export const DOMAIN = 'mcl.spur.us';\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACPP,OAAO,WAAW;AAwEP;AAtEX,IAAM,kBAAkB,oBAAI,IAAoB;AAmBzC,SAAS,4BACd,MACA,OACA,WAAW,GACL;AACN,QAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,gBAAgB,IAAI,IAAI,KAAK;AAC3C,QAAI,UAAU,UAAU;AACtB,YAAM,IAAI,MAAM,KAAK;AAAA,IACvB;AACA,oBAAgB,IAAI,MAAM,QAAQ,CAAC;AAEnC,WAAO,MAAM;AACX,YAAM,eAAe,gBAAgB,IAAI,IAAI,KAAK;AAClD,sBAAgB,IAAI,MAAM,KAAK,IAAI,GAAG,eAAe,CAAC,CAAC;AAAA,IACzD;AAAA,EACF,GAAG,CAAC,CAAC;AACP;AAqBO,SAAS,6BACd,kBACA,MACA,OACwB;AACxB,QAAM,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9B,QAAM,UAAU,WAAW,cAAc;AACzC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,SAAO;AACT;","names":["jsx","assessment"]}
|
|
1
|
+
{"version":3,"sources":["../src/contexts/MonocleProvider.tsx","../src/utils/useMaxAllowedInstancesGuard.tsx","../src/constants.ts"],"sourcesContent":["import React, {\n createContext,\n useContext,\n useEffect,\n useState,\n useMemo,\n useCallback,\n} from 'react';\nimport { withMaxAllowedInstancesGuard } from '../utils';\nimport { MonocleProviderProps } from '../types';\nimport { DOMAIN } from '../constants';\n\ninterface MonocleContextType {\n assessment: string | undefined;\n refresh: () => Promise<void>;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst MonocleContext = createContext<MonocleContextType | null>(null);\n\nconst MonocleProviderComponent: React.FC<MonocleProviderProps> = ({\n children,\n publishableKey,\n domain = DOMAIN,\n cpd,\n}) => {\n const [assessment, setAssessment] = useState<string | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const loadScript = () => {\n return new Promise<void>((resolve, reject) => {\n const existingScript = document.getElementById('_mcl');\n if (existingScript) {\n // If script exists but hasn't loaded yet, wait for it\n if (!window.MCL) {\n existingScript.onload = () => resolve();\n existingScript.onerror = () =>\n reject(new Error('Failed to load Monocle script'));\n } else {\n resolve();\n }\n return;\n }\n\n const script = document.createElement('script');\n script.id = '_mcl';\n script.async = true;\n\n let src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;\n if (cpd) {\n src += `&cpd=${cpd}`;\n }\n script.src = src;\n\n script.onload = () => {\n resolve();\n };\n script.onerror = (_e) => {\n console.error('MonocleProvider: Script failed to load');\n reject(new Error('Failed to load Monocle script'));\n };\n document.head.appendChild(script);\n });\n };\n\n const refresh = useCallback(async () => {\n try {\n setIsLoading(true);\n setError(null);\n\n if (window.MCL) {\n await window.MCL.refresh();\n } else {\n throw new Error('MCL object not found on window');\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Unknown error occurred')\n );\n setIsLoading(false);\n }\n }, []);\n\n useEffect(() => {\n const initializeMCL = async () => {\n try {\n await loadScript();\n if (window.MCL) {\n // Configure MCL with our callback to receive assessment updates\n await window.MCL.configure({\n onAssessment: (assessment: string) => {\n setAssessment(assessment);\n setIsLoading(false);\n },\n });\n\n // Check if assessment is already available\n const existingAssessment = window.MCL.getAssessment();\n if (existingAssessment) {\n setAssessment(existingAssessment);\n setIsLoading(false);\n }\n }\n } catch (err) {\n setError(\n err instanceof Error ? err : new Error('Failed to initialize MCL')\n );\n setIsLoading(false);\n }\n };\n\n // Only initialize if we don't already have an assessment\n if (!assessment) {\n initializeMCL();\n }\n\n // Cleanup function to reset callback on unmount\n return () => {\n if (window.MCL) {\n window.MCL.configure({ onAssessment: undefined });\n }\n };\n }, [publishableKey, domain]);\n\n const contextValue = useMemo(\n () => ({ assessment, refresh, isLoading, error }),\n [assessment, refresh, isLoading, error]\n );\n\n return (\n <MonocleContext.Provider value={contextValue}>\n {children}\n </MonocleContext.Provider>\n );\n};\n\nexport const MonocleProvider = withMaxAllowedInstancesGuard(\n MonocleProviderComponent,\n 'MonocleProvider',\n 'Only one instance of MonocleProvider is allowed'\n);\n\n/**\n * Hook to access the Monocle context.\n *\n * @returns {MonocleContextType} The Monocle context containing assessment data, loading state, and error information\n * @throws {Error} When used outside of a MonocleProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { assessment, isLoading, error, refresh } = useMonocle();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n *\n * return <div>Assessment: {assessment}</div>;\n * }\n * ```\n */\nexport const useMonocle = () => {\n const context = useContext(MonocleContext);\n if (!context) {\n throw new Error('useMonocle must be used within a MonocleProvider');\n }\n return context;\n};\n","import React from 'react';\n\nconst instanceCounter = new Map<string, number>();\n\n/**\n * A React hook that ensures a component is not instantiated more than a specified number of times.\n * Throws an error if the maximum number of instances is exceeded.\n *\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @param maxCount - The maximum number of allowed instances (defaults to 1)\n * @throws Error when the maximum number of instances is exceeded\n *\n * @example\n * ```tsx\n * const MyComponent = () => {\n * useMaxAllowedInstancesGuard('MyComponent', 'Only one instance of MyComponent is allowed');\n * return <div>My Component</div>;\n * };\n * ```\n */\nexport function useMaxAllowedInstancesGuard(\n name: string,\n error: string,\n maxCount = 1\n): void {\n React.useEffect(() => {\n const count = instanceCounter.get(name) || 0;\n if (count === maxCount) {\n throw new Error(error);\n }\n instanceCounter.set(name, count + 1);\n\n return () => {\n const currentCount = instanceCounter.get(name) || 0;\n instanceCounter.set(name, Math.max(0, currentCount - 1));\n };\n }, []);\n}\n\n/**\n * A higher-order component that wraps a component with instance count protection.\n * This HOC ensures that the wrapped component cannot be instantiated more than once\n * (or a specified number of times) in the application.\n *\n * @param WrappedComponent - The component to wrap with instance count protection\n * @param name - A unique identifier for the component type\n * @param error - The error message to display if the maximum count is exceeded\n * @returns A new component with instance count protection\n *\n * @example\n * ```tsx\n * const ProtectedComponent = withMaxAllowedInstancesGuard(\n * MyComponent,\n * 'MyComponent',\n * 'Only one instance of MyComponent is allowed'\n * );\n * ```\n */\nexport function withMaxAllowedInstancesGuard<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n name: string,\n error: string\n): React.ComponentType<P> {\n const displayName =\n WrappedComponent.displayName ||\n WrappedComponent.name ||\n name ||\n 'Component';\n\n const Hoc: React.FC<P> = (props) => {\n useMaxAllowedInstancesGuard(name, error);\n return <WrappedComponent {...props} />;\n };\n\n Hoc.displayName = `withMaxAllowedInstancesGuard(${displayName})`;\n return Hoc;\n}\n","export const DOMAIN = 'mcl.spur.us';\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACPP,OAAO,WAAW;AAwEP;AAtEX,IAAM,kBAAkB,oBAAI,IAAoB;AAmB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AAK;AAAA,MACpB;AAAA,IACF;AAGA,QAAI,CAAC,YAAY;AACf,oBAAc;AAAA,IAChB;AAGA,WAAO,MAAM;AACX,UAAI,OAAO,KAAK;AACd,eAAO,IAAI,UAAU,EAAE,cAAc,OAAU,CAAC;AAAA,MAClD;AAAA,IACF;AAAA,EACF,GAAG,CAAC,gBAAgB,MAAM,CAAC;AAE3B,QAAM,eAAe;AAAA,IACnB,OAAO,EAAE,YAAY,SAAS,WAAW,MAAM;AAAA,IAC/C,CAAC,YAAY,SAAS,WAAW,KAAK;AAAA,EACxC;AAEA,SACE,gBAAAD,KAAC,eAAe,UAAf,EAAwB,OAAO,cAC7B,UACH;AAEJ;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AACF;AAoBO,IAAM,aAAa,MAAM;AAC9B,QAAM,UAAU,WAAW,cAAc;AACzC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,SAAO;AACT;","names":["jsx","assessment"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spur.us/monocle-react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0-canary.v20251001171618",
|
|
4
4
|
"description": "Monocle React library",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"spur",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"author": "Spur",
|
|
21
21
|
"license": "MIT",
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@spur.us/types": "^0.3.0
|
|
23
|
+
"@spur.us/types": "^0.3.0"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
26
|
"react": "^18.0.0 || ^19.0.0 || ^19.0.0-0",
|
|
@@ -23,6 +23,7 @@ const MonocleProviderComponent: React.FC<MonocleProviderProps> = ({
|
|
|
23
23
|
children,
|
|
24
24
|
publishableKey,
|
|
25
25
|
domain = DOMAIN,
|
|
26
|
+
cpd,
|
|
26
27
|
}) => {
|
|
27
28
|
const [assessment, setAssessment] = useState<string | undefined>(undefined);
|
|
28
29
|
const [isLoading, setIsLoading] = useState(true);
|
|
@@ -46,7 +47,13 @@ const MonocleProviderComponent: React.FC<MonocleProviderProps> = ({
|
|
|
46
47
|
const script = document.createElement('script');
|
|
47
48
|
script.id = '_mcl';
|
|
48
49
|
script.async = true;
|
|
49
|
-
|
|
50
|
+
|
|
51
|
+
let src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
|
|
52
|
+
if (cpd) {
|
|
53
|
+
src += `&cpd=${cpd}`;
|
|
54
|
+
}
|
|
55
|
+
script.src = src;
|
|
56
|
+
|
|
50
57
|
script.onload = () => {
|
|
51
58
|
resolve();
|
|
52
59
|
};
|
package/src/types.ts
CHANGED
|
@@ -5,10 +5,21 @@ import React from 'react';
|
|
|
5
5
|
* @interface MonocleProviderProps
|
|
6
6
|
*/
|
|
7
7
|
export interface MonocleProviderProps {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The child components to be wrapped by the MonocleProvider.
|
|
10
|
+
*/
|
|
9
11
|
children: React.ReactNode;
|
|
10
|
-
/**
|
|
12
|
+
/**
|
|
13
|
+
* The publishable key used for authentication with Monocle.
|
|
14
|
+
*/
|
|
11
15
|
publishableKey: string;
|
|
12
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided
|
|
18
|
+
*/
|
|
13
19
|
domain?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Optional cpd parameter to add an arbitrary, session-based tag to the Monocle Assessment.
|
|
22
|
+
* This can be used for session verification, tracking, and analysis on your backend.
|
|
23
|
+
*/
|
|
24
|
+
cpd?: string;
|
|
14
25
|
}
|