@spur.us/monocle-react 1.1.1 → 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.
@@ -1,5 +1,5 @@
1
1
 
2
- > @spur.us/monocle-react@1.1.1 build /home/runner/work/javascript/javascript/packages/monocle-react
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
  CLI Building entry: {"index":"src/index.ts"}
@@ -10,13 +10,13 @@
10
10
  CLI Cleaning output folder
11
11
  CJS Build start
12
12
  ESM Build start
13
- CJS dist/index.js 6.04 KB
14
- CJS dist/index.js.map 9.95 KB
15
- CJS ⚡️ Build success in 40ms
16
- ESM dist/index.mjs 4.24 KB
17
- ESM dist/index.mjs.map 9.80 KB
18
- ESM ⚡️ Build success in 41ms
13
+ CJS dist/index.js 6.12 KB
14
+ CJS dist/index.js.map 10.11 KB
15
+ CJS ⚡️ Build success in 49ms
16
+ ESM dist/index.mjs 4.32 KB
17
+ ESM dist/index.mjs.map 9.96 KB
18
+ ESM ⚡️ Build success in 49ms
19
19
  DTS Build start
20
- DTS ⚡️ Build success in 2128ms
21
- DTS dist/index.d.ts 1.30 KB
22
- DTS dist/index.d.mts 1.30 KB
20
+ DTS ⚡️ Build success in 1934ms
21
+ DTS dist/index.d.ts 1.55 KB
22
+ DTS dist/index.d.mts 1.55 KB
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
- /** The child components to be wrapped by the MonocleProvider. */
8
+ /**
9
+ * The child components to be wrapped by the MonocleProvider.
10
+ */
9
11
  children: React.ReactNode;
10
- /** The publishable key used for authentication with Monocle. */
12
+ /**
13
+ * The publishable key used for authentication with Monocle.
14
+ */
11
15
  publishableKey: string;
12
- /** Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided */
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
- /** The child components to be wrapped by the MonocleProvider. */
8
+ /**
9
+ * The child components to be wrapped by the MonocleProvider.
10
+ */
9
11
  children: React.ReactNode;
10
- /** The publishable key used for authentication with Monocle. */
12
+ /**
13
+ * The publishable key used for authentication with Monocle.
14
+ */
11
15
  publishableKey: string;
12
- /** Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided */
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
- script.src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
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,O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AAM;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,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;;;AFoIlB,IAAAC,sBAAA;AAjHJ,IAAM,qBAAiB,6BAAyC,IAAI;AAEpE,IAAM,2BAA2D,CAAC;A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AA,IACpB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,+BAAU,MAAM;AACd,UAAM,gBAAgB,YAAY;AAChC,UAAI;AACF,cAAM,WAAW;AACjB,YAAI,OAAO,KAAK;AAEd,gBAAM,OAAO,IAAI,UAAU;AAAA,YACzB,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"]}
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
- script.src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
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
  };
@@ -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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AkB;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,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"]}
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;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,cACJ,iBAAiB,eACjB,iBAAiB,QACjB,QACA;AAEF,QAAM,MAAmB,CAAC,UAAU;AAClC,gCAA4B,MAAM,KAAK;AACvC,WAAO,oBAAC,oBAAkB,GAAG,OAAO;AAAA,EACt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AAI,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.1.1",
3
+ "version": "1.2.0-canary.v20251001171618",
4
4
  "description": "Monocle React library",
5
5
  "keywords": [
6
6
  "spur",
@@ -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
- script.src = `https://${domain}/d/mcl.js?tk=${publishableKey}`;
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
- /** The child components to be wrapped by the MonocleProvider. */
8
+ /**
9
+ * The child components to be wrapped by the MonocleProvider.
10
+ */
9
11
  children: React.ReactNode;
10
- /** The publishable key used for authentication with Monocle. */
12
+ /**
13
+ * The publishable key used for authentication with Monocle.
14
+ */
11
15
  publishableKey: string;
12
- /** Optional base domain for the Monocle API. Defaults to `mcl.spur.us` if not provided */
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
  }