@capitalos/react 1.0.0-rc.6 → 1.0.0-rc.8

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.
@@ -91,6 +91,7 @@ export declare class CapitalOSError extends Error {
91
91
  declare type CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {
92
92
  renderingContext: T;
93
93
  methods?: Partial<IframeConnectionMethods>;
94
+ sizeWidth?: boolean;
94
95
  };
95
96
 
96
97
  export declare type CapitalOsRenderingContext = {
@@ -200,7 +201,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
200
201
  name: string;
201
202
  logoUrl: string | null;
202
203
  }>, "many">;
203
- physicalCard: z_2.ZodNullable<z_2.ZodObject<{
204
+ physicalCard: z_2.ZodNullable<z_2.ZodObject<z_2.objectUtil.extendShape<{
204
205
  status: z_2.ZodEnum<["active", "disabled", "canceled"]>;
205
206
  shipment: z_2.ZodObject<{
206
207
  address: z_2.ZodObject<{
@@ -260,8 +261,9 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
260
261
  trackingNumber: string | null;
261
262
  trackingUrl: string | null;
262
263
  }>;
264
+ }, {
263
265
  id: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
264
- }, "strip", z_2.ZodTypeAny, {
266
+ }>, "strip", z_2.ZodTypeAny, {
265
267
  status: "active" | "canceled" | "disabled";
266
268
  shipment: {
267
269
  status: "pending" | "canceled" | "rejected" | "returned" | "shipped";
@@ -300,6 +302,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
300
302
  };
301
303
  id?: string | null | undefined;
302
304
  }>>;
305
+ cardSpendPolicyId: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
303
306
  }, "strip", z_2.ZodTypeAny, {
304
307
  status: "active" | "inactive" | "canceled" | "frozen";
305
308
  id: string;
@@ -354,6 +357,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
354
357
  id?: string | null | undefined;
355
358
  } | null;
356
359
  nickname?: string | null | undefined;
360
+ cardSpendPolicyId?: string | null | undefined;
357
361
  }, {
358
362
  status: "active" | "inactive" | "canceled" | "frozen";
359
363
  id: string;
@@ -408,6 +412,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
408
412
  id?: string | null | undefined;
409
413
  } | null;
410
414
  nickname?: string | null | undefined;
415
+ cardSpendPolicyId?: string | null | undefined;
411
416
  }>;
412
417
 
413
418
  /**
@@ -421,6 +426,7 @@ export declare type CardDetailsProps = CommonProps & {
421
426
  */
422
427
  cardId: string;
423
428
  cardOnly?: boolean | undefined;
429
+ hideAddress?: boolean | undefined;
424
430
  };
425
431
 
426
432
  /**
@@ -457,6 +463,23 @@ export declare type CommonProps = {
457
463
 
458
464
  export declare function decodeOneTimeToken(token: string): any;
459
465
 
466
+ /**
467
+ * Renders the CapitalOS Dev Tools experience.
468
+ * Allows for simulating transactions, etc.
469
+ */
470
+ declare function DevTools(props: DevToolsProps): JSX.Element;
471
+ export { DevTools }
472
+ export { DevTools as DevTools_alias_1 }
473
+
474
+ export declare function DevToolsButton({ onClick, isLoading }: DevToolsButtonProps): JSX.Element;
475
+
476
+ declare interface DevToolsButtonProps {
477
+ onClick?: () => void;
478
+ isLoading?: boolean;
479
+ }
480
+
481
+ export declare type DevToolsProps = CommonProps;
482
+
460
483
  /**
461
484
  * Renders the CapitalOS Dispute Transaction experience.
462
485
  */
@@ -519,6 +542,9 @@ export declare type IframeConnectionMethods = {
519
542
  makePayment?: {
520
543
  onDone?: () => void;
521
544
  };
545
+ devTools?: {
546
+ onClose?: () => void;
547
+ };
522
548
  };
523
549
 
524
550
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
@@ -715,14 +741,17 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
715
741
  entryPoint: z.ZodLiteral<"cardDetails">;
716
742
  cardId: z.ZodString;
717
743
  cardOnly: z.ZodOptional<z.ZodBoolean>;
744
+ hideAddress: z.ZodOptional<z.ZodBoolean>;
718
745
  }, "strip", z.ZodTypeAny, {
719
746
  cardId: string;
720
747
  entryPoint: "cardDetails";
721
748
  cardOnly?: boolean | undefined;
749
+ hideAddress?: boolean | undefined;
722
750
  }, {
723
751
  cardId: string;
724
752
  entryPoint: "cardDetails";
725
753
  cardOnly?: boolean | undefined;
754
+ hideAddress?: boolean | undefined;
726
755
  }>, z.ZodObject<{
727
756
  entryPoint: z.ZodLiteral<"accountDetails">;
728
757
  }, "strip", z.ZodTypeAny, {
@@ -789,6 +818,12 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
789
818
  entryPoint: "makePayment";
790
819
  }, {
791
820
  entryPoint: "makePayment";
821
+ }>, z.ZodObject<{
822
+ entryPoint: z.ZodLiteral<"devTools">;
823
+ }, "strip", z.ZodTypeAny, {
824
+ entryPoint: "devTools";
825
+ }, {
826
+ entryPoint: "devTools";
792
827
  }>]>, z.ZodObject<{
793
828
  referer: z.ZodOptional<z.ZodNullable<z.ZodString>>;
794
829
  }, "strip", z.ZodTypeAny, {
@@ -91,6 +91,7 @@ export declare class CapitalOSError extends Error {
91
91
  declare type CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {
92
92
  renderingContext: T;
93
93
  methods?: Partial<IframeConnectionMethods>;
94
+ sizeWidth?: boolean;
94
95
  };
95
96
 
96
97
  export declare type CapitalOsRenderingContext = {
@@ -200,7 +201,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
200
201
  name: string;
201
202
  logoUrl: string | null;
202
203
  }>, "many">;
203
- physicalCard: z_2.ZodNullable<z_2.ZodObject<{
204
+ physicalCard: z_2.ZodNullable<z_2.ZodObject<z_2.objectUtil.extendShape<{
204
205
  status: z_2.ZodEnum<["active", "disabled", "canceled"]>;
205
206
  shipment: z_2.ZodObject<{
206
207
  address: z_2.ZodObject<{
@@ -260,8 +261,9 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
260
261
  trackingNumber: string | null;
261
262
  trackingUrl: string | null;
262
263
  }>;
264
+ }, {
263
265
  id: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
264
- }, "strip", z_2.ZodTypeAny, {
266
+ }>, "strip", z_2.ZodTypeAny, {
265
267
  status: "active" | "canceled" | "disabled";
266
268
  shipment: {
267
269
  status: "pending" | "canceled" | "rejected" | "returned" | "shipped";
@@ -300,6 +302,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
300
302
  };
301
303
  id?: string | null | undefined;
302
304
  }>>;
305
+ cardSpendPolicyId: z_2.ZodOptional<z_2.ZodNullable<z_2.ZodString>>;
303
306
  }, "strip", z_2.ZodTypeAny, {
304
307
  status: "active" | "inactive" | "canceled" | "frozen";
305
308
  id: string;
@@ -354,6 +357,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
354
357
  id?: string | null | undefined;
355
358
  } | null;
356
359
  nickname?: string | null | undefined;
360
+ cardSpendPolicyId?: string | null | undefined;
357
361
  }, {
358
362
  status: "active" | "inactive" | "canceled" | "frozen";
359
363
  id: string;
@@ -408,6 +412,7 @@ declare const cardApiDtoSchema: z_2.ZodObject<{
408
412
  id?: string | null | undefined;
409
413
  } | null;
410
414
  nickname?: string | null | undefined;
415
+ cardSpendPolicyId?: string | null | undefined;
411
416
  }>;
412
417
 
413
418
  /**
@@ -421,6 +426,7 @@ export declare type CardDetailsProps = CommonProps & {
421
426
  */
422
427
  cardId: string;
423
428
  cardOnly?: boolean | undefined;
429
+ hideAddress?: boolean | undefined;
424
430
  };
425
431
 
426
432
  /**
@@ -457,6 +463,23 @@ export declare type CommonProps = {
457
463
 
458
464
  export declare function decodeOneTimeToken(token: string): any;
459
465
 
466
+ /**
467
+ * Renders the CapitalOS Dev Tools experience.
468
+ * Allows for simulating transactions, etc.
469
+ */
470
+ declare function DevTools(props: DevToolsProps): JSX.Element;
471
+ export { DevTools }
472
+ export { DevTools as DevTools_alias_1 }
473
+
474
+ export declare function DevToolsButton({ onClick, isLoading }: DevToolsButtonProps): JSX.Element;
475
+
476
+ declare interface DevToolsButtonProps {
477
+ onClick?: () => void;
478
+ isLoading?: boolean;
479
+ }
480
+
481
+ export declare type DevToolsProps = CommonProps;
482
+
460
483
  /**
461
484
  * Renders the CapitalOS Dispute Transaction experience.
462
485
  */
@@ -519,6 +542,9 @@ export declare type IframeConnectionMethods = {
519
542
  makePayment?: {
520
543
  onDone?: () => void;
521
544
  };
545
+ devTools?: {
546
+ onClose?: () => void;
547
+ };
522
548
  };
523
549
 
524
550
  export declare const IframeResizer: React_2.ForwardRefExoticComponent<Omit<IFrameOptions, "closedCallback" | "scrollCallback" | "resizedCallback" | "messageCallback" | "initCallback"> & {
@@ -715,14 +741,17 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
715
741
  entryPoint: z.ZodLiteral<"cardDetails">;
716
742
  cardId: z.ZodString;
717
743
  cardOnly: z.ZodOptional<z.ZodBoolean>;
744
+ hideAddress: z.ZodOptional<z.ZodBoolean>;
718
745
  }, "strip", z.ZodTypeAny, {
719
746
  cardId: string;
720
747
  entryPoint: "cardDetails";
721
748
  cardOnly?: boolean | undefined;
749
+ hideAddress?: boolean | undefined;
722
750
  }, {
723
751
  cardId: string;
724
752
  entryPoint: "cardDetails";
725
753
  cardOnly?: boolean | undefined;
754
+ hideAddress?: boolean | undefined;
726
755
  }>, z.ZodObject<{
727
756
  entryPoint: z.ZodLiteral<"accountDetails">;
728
757
  }, "strip", z.ZodTypeAny, {
@@ -789,6 +818,12 @@ declare const renderingContextSchema: z.ZodIntersection<z.ZodDiscriminatedUnion<
789
818
  entryPoint: "makePayment";
790
819
  }, {
791
820
  entryPoint: "makePayment";
821
+ }>, z.ZodObject<{
822
+ entryPoint: z.ZodLiteral<"devTools">;
823
+ }, "strip", z.ZodTypeAny, {
824
+ entryPoint: "devTools";
825
+ }, {
826
+ entryPoint: "devTools";
792
827
  }>]>, z.ZodObject<{
793
828
  referer: z.ZodOptional<z.ZodNullable<z.ZodString>>;
794
829
  }, "strip", z.ZodTypeAny, {
package/dist/esm/index.js CHANGED
@@ -1,2 +1,11 @@
1
- "use client";var Y=Object.defineProperty,Z=Object.defineProperties;var ee=Object.getOwnPropertyDescriptors;var w=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var N=(e,t,n)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&N(e,n,t[n]);if(w)for(var n of w(t))B.call(t,n)&&N(e,n,t[n]);return e},c=(e,t)=>Z(e,ee(t));var E=(e,t)=>{var n={};for(var o in e)j.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&w)for(var o of w(e))t.indexOf(o)<0&&B.call(e,o)&&(n[o]=e[o]);return n};var W=(e,t,n)=>new Promise((o,r)=>{var i=p=>{try{a(n.next(p))}catch(m){r(m)}},s=p=>{try{a(n.throw(p))}catch(m){r(m)}},a=p=>p.done?o(p.value):Promise.resolve(p.value).then(i,s);a((n=n.apply(e,t)).next())});import u,{useMemo as f}from"react";import D,{useEffect as Q,useMemo as De,useRef as X,useState as Le,useCallback as we}from"react";import z,{createContext as Ie,useContext as Ee,useState as v,useMemo as be,useCallback as _,useEffect as Oe}from"react";import Te,{useMemo as ke,useRef as Pe}from"react";var h=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},b={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},k=class extends h{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:b.unauthorized}),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as ae}from"penpal";import{useEffect as de,useMemo as ce,useRef as J}from"react";var K="1.0.0-rc.6";function ie(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function U(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new k}}function se(e){try{return decodeURIComponent(e)}catch(t){return e}}function V({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?c(d({},t),{referer:window.location.href}):null,i=r?ie(r):null,s=new URL(e.baseUrl),a=se(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,a):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(a)),s.searchParams.set("sdkVersion",K),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new k);return}}function A(e){let n=U(e).path;if(!n||typeof n!="string")throw new k;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var pe=1e4;function M({iframeRef:e,token:t,onError:n,methods:o}){de(()=>{if(!e.current)return;let r=ae({iframe:e.current,childOrigin:"*",debug:!0,timeout:pe,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function R({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=J(o),i=J(t);return ce(()=>{if(e)return V({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}import{iframeResizer as me}from"iframe-resizer";import le,{forwardRef as ue,useEffect as fe,useImperativeHandle as ge,useRef as he}from"react";var O=ue((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=ye(e),i=he(null);return fe(()=>{let s=i.current;return me(d({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),ge(t,()=>i.current),le.createElement("iframe",c(d({},o),{title:n,ref:i}))});O.displayName="IframeResizer";var Ce=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],xe=new Set(Ce);function ye(e){return Object.keys(e).reduce((n,o)=>(xe.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function $(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=Pe(null),s=ke(()=>A(t),[t]),p=R({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return M({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:m=>{r==null||r(new h(m))},tokenExchange:{onLongLivedToken:o}}}),Te.createElement(O,{src:p,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var q=Ie({isLoading:!1,invalidateToken:()=>{}}),ve=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=v(void 0),[i,s]=v(void 0),[a,p]=v(void 0),[m,L]=v(!1),[P,x]=v(void 0),T=_(()=>W(void 0,null,function*(){L(!0);try{let g=yield e();r(g),x(void 0);let F=U(g),C=new URL(F.path);C.pathname="",s(C.toString())}catch(g){x(g)}finally{L(!1)}}),[e]),I=_(()=>{p(void 0)},[]);Oe(()=>{a||T()},[a,T]);let y=_(g=>{p(g),r(void 0),x(void 0)},[]),S=be(()=>{if(a&&!i)throw new h({message:"baseUrl is required for long lived tokens",code:b.unauthorized});return{tokenData:a?{token:a,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:m,error:P,invalidateToken:I}},[a,m,P,I,i]);return z.createElement(z.Fragment,null,z.createElement(q.Provider,{value:S},n),o&&!a&&z.createElement($,{oneTimeToken:o,onExchangeComplete:y,enableLogging:t,onExchangeError:x}))},G=()=>Ee(q);function l(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:a,theme:p}=e,{tokenData:m,error:L,invalidateToken:P}=G(),[x,T]=Le(!1),I=X(null);Ae(L,r);let y=De(()=>t?A(t):m,[t,m]),S=we(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new h({message:"Token expired. Cannot automatically refresh when using token prop.",code:b.unauthorized}));return}P(),T(!1)},[t,P,o,r]);Q(()=>{t&&m&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,m,o]);let g=R({tokenData:y,renderingContext:s,theme:p,onError:r});if(M({iframeRef:I,token:y==null?void 0:y.token,onError:C=>{r==null||r(C),T(!0)},methods:d({onLoad:()=>T(!0),onError:C=>{let H=new h(C);r==null||r(H)},onTokenExpired:S},a)}),!y||!g)return D.createElement(D.Fragment,null,i||null);let F=s.entryPoint!=="insightsWidget";return D.createElement(D.Fragment,null,!x&&i,D.createElement(O,{src:g,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:I,hidden:!x,onResized:C=>{if(!F)return;let H=`${parseInt(C.height)+12}px`;C.iframe.style.height=H}}))}function Ae(e,t){let n=X(!1);Q(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function Me(e){let t="cardsApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}var At=Me;function Mt(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=E(i,["cardholder","onDone","onCancel"]);let s="createCard",a=f(()=>({entryPoint:s,cardholder:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createCard:{onDone:t,onCancel:n}}}))}function Rt(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=E(i,["transactionId","onDone","onCancel"]);let s="createDispute",a=f(()=>({entryPoint:s,transactionId:e}),[e]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{createDispute:{onDone:t,onCancel:n}}}))}function zt(e){let t="billPayApp",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function St(e){let t="cardDetails",n=f(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ft(e){let t="accountDetails",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ht(e){let t="accountActions",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function Ut(e){let t="insightsDashboard",n=f(()=>({entryPoint:t}),[t]);return u.createElement(l,c(d({},e),{renderingContext:n}))}function _t(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=f(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return u.createElement(l,c(d({},e),{renderingContext:s}))}function Nt(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=E(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",a=f(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return u.createElement(l,c(d({},o),{renderingContext:a,methods:{onboarding:{onDone:e}}}))}function jt(n){var o=n,{onDone:e}=o,t=E(o,["onDone"]);let r="makePayment",i=f(()=>({entryPoint:r}),[r]);return u.createElement(l,c(d({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}export{Ht as AccountActions,Ft as AccountDetails,At as App,zt as BillPayApp,ve as CapitalOsAuthenticationProvider,St as CardDetails,Me as CardsApp,Rt as DisputeTransaction,Ut as InsightsDashboard,_t as InsightsWidget,Mt as IssueCard,jt as MakePayment,Nt as Onboarding};
1
+ "use client";var ie=Object.defineProperty,se=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var R=Object.getOwnPropertySymbols;var J=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable;var V=(e,t,o)=>t in e?ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,a=(e,t)=>{for(var o in t||(t={}))J.call(t,o)&&V(e,o,t[o]);if(R)for(var o of R(t))$.call(t,o)&&V(e,o,t[o]);return e},p=(e,t)=>se(e,ae(t));var I=(e,t)=>{var o={};for(var n in e)J.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(e!=null&&R)for(var n of R(e))t.indexOf(n)<0&&$.call(e,n)&&(o[n]=e[n]);return o};var q=(e,t,o)=>new Promise((n,r)=>{var i=c=>{try{d(o.next(c))}catch(f){r(f)}},s=c=>{try{d(o.throw(c))}catch(f){r(f)}},d=c=>c.done?n(c.value):Promise.resolve(c.value).then(i,s);d((o=o.apply(e,t)).next())});import l,{useMemo as u}from"react";import L,{useEffect as te,useMemo as Fe,useRef as oe,useState as Re,useCallback as He}from"react";import _,{createContext as we,useContext as Me,useState as D,useMemo as Ae,useCallback as j,useEffect as Se}from"react";import Oe,{useMemo as De,useRef as Le}from"react";var g=class extends Error{constructor({message:t,code:o}){super(t),this.name="CapitalOSError",this.code=o}},E={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},b=class extends g{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:E.unauthorized}),this.name="CapitalOSInvalidTokenError"}};import{connectToChild as fe}from"penpal";import{useEffect as ge,useMemo as he,useRef as Q}from"react";var Z="1.0.0-rc.8";function le(e){let t=JSON.stringify(e),o=btoa(t);return encodeURIComponent(o)}function W(e){try{let t=decodeURIComponent(e),o=atob(t);return JSON.parse(o)}catch(t){throw new b}}function ue(e){try{return decodeURIComponent(e)}catch(t){return e}}function G({tokenData:e,renderingContext:t,theme:o,onError:n}){try{let r=t?p(a({},t),{referer:window.location.href}):null,i=r?le(r):null,s=new URL(e.baseUrl),d=ue(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,d):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(d)),s.searchParams.set("sdkVersion",Z),i&&s.searchParams.set("renderingContext",i),o&&s.searchParams.set("theme",o),s.toString()}catch(r){n==null||n(new b);return}}function H(e){let o=W(e).path;if(!o||typeof o!="string")throw new b;return{token:e,tokenType:"oneTime",baseUrl:o,paramKey:"token",paramLocation:"search"}}var Ce=1e4;function B({iframeRef:e,token:t,onError:o,methods:n}){ge(()=>{if(!e.current)return;let r=fe({iframe:e.current,childOrigin:"*",debug:!0,timeout:Ce,methods:n});return r.promise.catch(i=>{o==null||o(i)}),()=>{r.destroy()}},[t,e])}function U({tokenData:e,renderingContext:t,theme:o,onError:n}){let r=Q(n),i=Q(t);return he(()=>{if(e)return G({tokenData:e,renderingContext:i.current,theme:o,onError:r.current})},[e,o,r,i])}import{iframeResizer as xe}from"iframe-resizer";import ye,{forwardRef as Te,useEffect as ke,useImperativeHandle as Pe,useRef as be}from"react";var O=Te((e,t)=>{let o=e.title||"iframe",{iframeHTMLAttributes:n,resizerOptions:r}=Ee(e),i=be(null);return ke(()=>{let s=i.current;return xe(a({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),Pe(t,()=>i.current),ye.createElement("iframe",p(a({},n),{title:o,ref:i}))});O.displayName="IframeResizer";var ve=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],Ie=new Set(ve);function Ee(e){return Object.keys(e).reduce((o,n)=>{let r=e[n];return Ie.has(n)?r!==void 0&&(o.resizerOptions[n]=e[n]):o.iframeHTMLAttributes[n]=e[n],o},{resizerOptions:{},iframeHTMLAttributes:{}})}function X(e){let{oneTimeToken:t,enableLogging:o,onExchangeComplete:n,onExchangeError:r}=e,i=Le(null),s=De(()=>H(t),[t]),c=U({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return B({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:f=>{r==null||r(new g(f))},tokenExchange:{onLongLivedToken:n}}}),Oe.createElement(O,{src:c,checkOrigin:!1,style:{display:"none"},log:!!o,ref:i})}var Y=we({isLoading:!1,invalidateToken:()=>{}}),ze=({getToken:e,enableLogging:t,children:o})=>{let[n,r]=D(void 0),[i,s]=D(void 0),[d,c]=D(void 0),[f,C]=D(!1),[A,x]=D(void 0),v=j(()=>q(void 0,null,function*(){C(!0);try{let h=yield e();r(h),x(void 0);let z=W(h),F=new URL(z.path);F.pathname="",s(F.toString())}catch(h){x(h)}finally{C(!1)}}),[e]),k=j(()=>{c(void 0)},[]);Se(()=>{d||v()},[d,v]);let S=j(h=>{c(h),r(void 0),x(void 0)},[]),y=Ae(()=>{if(d&&!i)throw new g({message:"baseUrl is required for long lived tokens",code:E.unauthorized});return{tokenData:d?{token:d,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:f,error:A,invalidateToken:k}},[d,f,A,k,i]);return _.createElement(_.Fragment,null,_.createElement(Y.Provider,{value:y},o),n&&!d&&_.createElement(X,{oneTimeToken:n,onExchangeComplete:S,enableLogging:t,onExchangeError:x}))},ee=()=>Me(Y);function m(e){let{token:t,className:o,enableLogging:n,onError:r,loadingComponent:i,renderingContext:s,methods:d,theme:c,sizeWidth:f}=e,{tokenData:C,error:A,invalidateToken:x}=ee(),[v,k]=Re(!1),S=oe(null);Be(A,r);let y=Fe(()=>t?H(t):C,[t,C]),h=He(()=>{if(n&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new g({message:"Token expired. Cannot automatically refresh when using token prop.",code:E.unauthorized}));return}x(),k(!1)},[t,x,n,r]);te(()=>{t&&C&&n&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,C,n]);let z=U({tokenData:y,renderingContext:s,theme:c,onError:r});if(B({iframeRef:S,token:y==null?void 0:y.token,onError:P=>{r==null||r(P),k(!0)},methods:a({onLoad:()=>{k(!0)},onError:P=>{let N=new g(P);r==null||r(N)},onTokenExpired:h},d)}),!y||!z)return L.createElement(L.Fragment,null,i||null);let F=s.entryPoint!=="insightsWidget";return L.createElement(L.Fragment,null,!v&&i,L.createElement(O,{src:z,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:o,log:!!n,ref:S,hidden:!v,onResized:P=>{if(!F)return;let N=`${parseInt(P.height)+12}px`;P.iframe.style.height=N},sizeWidth:f}))}function Be(e,t){let o=oe(!1);te(()=>{e&&!o.current&&(t==null||t(e),o.current=!0)},[e,t])}import M,{useMemo as Ue}from"react";import{useState as _e}from"react";import T,{useState as ne}from"react";var w={bugButton:{position:"fixed",left:"12px",bottom:"12px",margin:"12px",padding:"4px",display:"inline-flex",alignItems:"center",borderRadius:"9999px",border:"1px solid transparent",backgroundColor:"#2563eb",color:"white",opacity:.4,boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)",cursor:"pointer",zIndex:50,transition:"opacity 0.3s ease-in-out"},bugButtonHover:{backgroundColor:"#1d4ed8",opacity:1},bugButtonFocus:{outline:"none",boxShadow:"0 0 0 2px white, 0 0 0 4px #3b82f6"},bugIcon:{width:"20px",height:"20px"},loadingButton:{cursor:"default",opacity:1,animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}},re=()=>T.createElement("svg",{style:w.bugIcon,xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor"},T.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 12.75c1.148 0 2.278.08 3.383.237 1.037.146 1.866.966 1.866 2.013 0 3.728-2.35 6.75-5.25 6.75S6.75 18.728 6.75 15c0-1.046.83-1.867 1.866-2.013A24.204 24.204 0 0 1 12 12.75Zm0 0c2.883 0 5.647.508 8.207 1.44a23.91 23.91 0 0 1-1.152 6.06M12 12.75c-2.883 0-5.647.508-8.208 1.44.125 2.104.52 4.136 1.153 6.06M12 12.75a2.25 2.25 0 0 0 2.248-2.354M12 12.75a2.25 2.25 0 0 1-2.248-2.354M12 8.25c.995 0 1.971-.08 2.922-.236.403-.066.74-.358.795-.762a3.778 3.778 0 0 0-.399-2.25M12 8.25c-.995 0-1.97-.08-2.922-.236-.402-.066-.74-.358-.795-.762a3.734 3.734 0 0 1 .4-2.253M12 8.25a2.25 2.25 0 0 0-2.248 2.146M12 8.25a2.25 2.25 0 0 1 2.248 2.146M8.683 5a6.032 6.032 0 0 1-1.155-1.002c.07-.63.27-1.222.574-1.747m.581 2.749A3.75 3.75 0 0 1 15.318 5m0 0c.427-.283.815-.62 1.155-.999a4.471 4.471 0 0 0-.575-1.752M4.921 6a24.048 24.048 0 0 0-.392 3.314c1.668.546 3.416.914 5.223 1.082M19.08 6c.205 1.08.337 2.187.392 3.314a23.882 23.882 0 0 1-5.223 1.082"}));function K({onClick:e,isLoading:t=!1}){let[o,n]=ne(!1),[r,i]=ne(!1),s=a(a(a(a({},w.bugButton),t&&w.loadingButton),!t&&o&&w.bugButtonHover),!t&&r&&w.bugButtonFocus);return t?T.createElement("div",{style:s},T.createElement("style",null,`
2
+ @keyframes pulse {
3
+ 0%, 100% {
4
+ opacity: 1;
5
+ }
6
+ 50% {
7
+ opacity: 0.4;
8
+ }
9
+ }
10
+ `),T.createElement(re,null)):T.createElement("button",{id:"dev-tools-button",onClick:e,type:"button",style:s,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),onFocus:()=>i(!0),onBlur:()=>i(!1)},T.createElement(re,null))}var Ne={panel:{position:"fixed",bottom:"20px",left:"20px",zIndex:50}};function We(e){let t="devTools",o=Ue(()=>({entryPoint:t}),[t]),[n,r]=_e(!1);return M.createElement("aside",{"aria-label":"CapitalOS dev tools"},!n&&M.createElement(K,{onClick:()=>r(!n)}),n&&M.createElement("div",{style:Ne.panel},M.createElement(m,p(a({},e),{renderingContext:o,methods:{devTools:{onClose:()=>r(!1)}},enableLogging:!0,sizeWidth:!0,loadingComponent:M.createElement(K,{isLoading:!0})}))))}function je(e){let t="cardsApp",o=u(()=>({entryPoint:t}),[t]);return l.createElement(m,p(a({},e),{renderingContext:o}))}var Xt=je;function Yt(r){var i=r,{cardholder:e,onDone:t,onCancel:o}=i,n=I(i,["cardholder","onDone","onCancel"]);let s="createCard",d=u(()=>({entryPoint:s,cardholder:e}),[e]);return l.createElement(m,p(a({},n),{renderingContext:d,methods:{createCard:{onDone:t,onCancel:o}}}))}function eo(r){var i=r,{transactionId:e,onDone:t,onCancel:o}=i,n=I(i,["transactionId","onDone","onCancel"]);let s="createDispute",d=u(()=>({entryPoint:s,transactionId:e}),[e]);return l.createElement(m,p(a({},n),{renderingContext:d,methods:{createDispute:{onDone:t,onCancel:o}}}))}function to(e){let t="billPayApp",o=u(()=>({entryPoint:t}),[t]);return l.createElement(m,p(a({},e),{renderingContext:o}))}function oo(e){let t="cardDetails",o=u(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly,hideAddress:e.hideAddress}),[t,e.cardId,e.cardOnly]);return l.createElement(m,p(a({},e),{renderingContext:o}))}function no(e){let t="accountDetails",o=u(()=>({entryPoint:t}),[t]);return l.createElement(m,p(a({},e),{renderingContext:o}))}function ro(e){let t="accountActions",o=u(()=>({entryPoint:t}),[t]);return l.createElement(m,p(a({},e),{renderingContext:o}))}function io(e){let t="insightsDashboard",o=u(()=>({entryPoint:t}),[t]);return l.createElement(m,p(a({},e),{renderingContext:o}))}function so(e){let t="insightsWidget",{widget:o,hideTitle:n,height:r,width:i}=e,s=u(()=>({entryPoint:t,widget:o,hideTitle:n,height:r,width:i}),[t,o,n,r,i]);return l.createElement(m,p(a({},e),{renderingContext:s}))}function ao(r){var i=r,{onDone:e,entryPoint:t,exitPoint:o}=i,n=I(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",d=u(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:o}),[s,t,o]);return l.createElement(m,p(a({},n),{renderingContext:d,methods:{onboarding:{onDone:e}}}))}function po(o){var n=o,{onDone:e}=n,t=I(n,["onDone"]);let r="makePayment",i=u(()=>({entryPoint:r}),[r]);return l.createElement(m,p(a({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}export{ro as AccountActions,no as AccountDetails,Xt as App,to as BillPayApp,ze as CapitalOsAuthenticationProvider,oo as CardDetails,je as CardsApp,We as DevTools,eo as DisputeTransaction,io as InsightsDashboard,so as InsightsWidget,Yt as IssueCard,po as MakePayment,ao as Onboarding};
2
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../src/context/capital-os-authentication-context.tsx","../../src/common/token-exchange-iframe.tsx","../../src/error.ts","../../src/hooks.ts","../../package.json","../../src/utils.ts","../../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.6\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"2yBAEA,OAAOA,GAAS,WAAAC,MAAe,QCF/B,OAAOC,GAAS,aAAAC,EAAW,WAAAC,GAAS,UAAAC,EAAQ,YAAAC,GAAU,eAAAC,OAAmB,QCEzE,OAAOC,GAAS,iBAAAC,GAAe,cAAAC,GAAY,YAAAC,EAAU,WAAAC,GAAS,eAAAC,EAAa,aAAAC,OAAiB,QCF5F,OAAOC,IAAS,WAAAC,GAAS,UAAAC,OAAc,QCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KAAOC,CACd,CACF,EAEaC,EAA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useCallback","React","createContext","useContext","useState","useMemo","useCallback","useEffect","React","useMemo","useRef","CapitalOSError","message","code","ErrorCode","InvalidTokenError","connectToChild","useEffect","useMemo","useRef","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","useEffect","connection","connectToChild","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","useRef","renderingContextRef","useMemo","buildIframeUrl","iframeResizer","React","forwardRef","useEffect","useImperativeHandle","useRef","IframeResizer","forwardRef","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","useRef","useEffect","iframe","iframeResizer","__spreadValues","useImperativeHandle","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","useRef","tokenData","useMemo","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","createContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","useState","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","useCallback","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","useEffect","onExchangeComplete","jwtToken","contextValue","useMemo","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","useContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","useState","iframeRef","useRef","useErrorHandling","tokenData","useMemo","tokenDataFromOneTimeToken","handleTokenExpired","useCallback","CapitalOSError","ErrorCode","useEffect","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
1
+ {"version":3,"sources":["../../src/index.tsx","../../src/capital-os.tsx","../../src/context/capital-os-authentication-context.tsx","../../src/common/token-exchange-iframe.tsx","../../src/error.ts","../../src/hooks.ts","../../package.json","../../src/utils.ts","../../src/iframe-resizer.tsx","../../src/dev-tools.tsx","../../src/components/dev-tools-button.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport { DevTools } from './dev-tools'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n hideAddress?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly, hideAddress: props.hideAddress }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Dev Tools\nexport { DevTools }\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n sizeWidth?: boolean\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n sizeWidth,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => {\n setIsLoaded(true)\n },\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n sizeWidth={sizeWidth}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n devTools?: {\n onClose?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.8\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = (Object.keys(props) as Array<keyof IframeResizerProps>).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n const value = props[key]\n if (resizerOptionsSet.has(key)) {\n if (value !== undefined) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n }\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n","import React, { useMemo } from 'react'\nimport { useState } from 'react'\nimport { CSSProperties } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { DevToolsButton } from './components/dev-tools-button'\nimport { EntryPoint } from './external-types'\nimport { CommonProps } from './types'\n\nconst styles: Record<string, CSSProperties> = {\n panel: {\n position: 'fixed',\n bottom: '20px',\n left: '20px',\n zIndex: 50,\n },\n}\n\n// #region Dev Tools\nexport type DevToolsProps = CommonProps\n\n/**\n * Renders the CapitalOS Dev Tools experience.\n * Allows for simulating transactions, etc.\n */\nexport function DevTools(props: DevToolsProps) {\n const entryPoint: EntryPoint = 'devTools'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n const [isOpen, setIsOpen] = useState(false)\n\n return (\n <aside aria-label=\"CapitalOS dev tools\">\n {!isOpen && <DevToolsButton onClick={() => setIsOpen(!isOpen)} />}\n {isOpen && (\n <div style={styles['panel']}>\n <CapitalOS\n {...props}\n renderingContext={renderingContext}\n methods={{ devTools: { onClose: () => setIsOpen(false) } }}\n enableLogging={true}\n sizeWidth={true}\n loadingComponent={<DevToolsButton isLoading />}\n />\n </div>\n )}\n </aside>\n )\n}\n","import React, { useState } from 'react'\nimport { CSSProperties } from 'react'\n\nconst styles: Record<string, CSSProperties> = {\n bugButton: {\n position: 'fixed',\n left: '12px',\n bottom: '12px',\n margin: '12px',\n padding: '4px',\n display: 'inline-flex',\n alignItems: 'center',\n borderRadius: '9999px',\n border: '1px solid transparent',\n backgroundColor: '#2563eb',\n color: 'white',\n opacity: 0.4,\n boxShadow: '0 1px 3px 0 rgb(0 0 0 / 0.1)',\n cursor: 'pointer',\n zIndex: 50,\n transition: 'opacity 0.3s ease-in-out',\n },\n bugButtonHover: {\n backgroundColor: '#1d4ed8',\n opacity: 1,\n },\n bugButtonFocus: {\n outline: 'none',\n boxShadow: '0 0 0 2px white, 0 0 0 4px #3b82f6',\n },\n bugIcon: {\n width: '20px',\n height: '20px',\n },\n loadingButton: {\n cursor: 'default',\n opacity: 1,\n animation: 'pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite',\n },\n}\n\nconst BugIcon = () => (\n <svg\n style={styles['bugIcon']}\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth=\"1.5\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M12 12.75c1.148 0 2.278.08 3.383.237 1.037.146 1.866.966 1.866 2.013 0 3.728-2.35 6.75-5.25 6.75S6.75 18.728 6.75 15c0-1.046.83-1.867 1.866-2.013A24.204 24.204 0 0 1 12 12.75Zm0 0c2.883 0 5.647.508 8.207 1.44a23.91 23.91 0 0 1-1.152 6.06M12 12.75c-2.883 0-5.647.508-8.208 1.44.125 2.104.52 4.136 1.153 6.06M12 12.75a2.25 2.25 0 0 0 2.248-2.354M12 12.75a2.25 2.25 0 0 1-2.248-2.354M12 8.25c.995 0 1.971-.08 2.922-.236.403-.066.74-.358.795-.762a3.778 3.778 0 0 0-.399-2.25M12 8.25c-.995 0-1.97-.08-2.922-.236-.402-.066-.74-.358-.795-.762a3.734 3.734 0 0 1 .4-2.253M12 8.25a2.25 2.25 0 0 0-2.248 2.146M12 8.25a2.25 2.25 0 0 1 2.248 2.146M8.683 5a6.032 6.032 0 0 1-1.155-1.002c.07-.63.27-1.222.574-1.747m.581 2.749A3.75 3.75 0 0 1 15.318 5m0 0c.427-.283.815-.62 1.155-.999a4.471 4.471 0 0 0-.575-1.752M4.921 6a24.048 24.048 0 0 0-.392 3.314c1.668.546 3.416.914 5.223 1.082M19.08 6c.205 1.08.337 2.187.392 3.314a23.882 23.882 0 0 1-5.223 1.082\"\n />\n </svg>\n)\n\ninterface DevToolsButtonProps {\n onClick?: () => void\n isLoading?: boolean\n}\n\nexport function DevToolsButton({ onClick, isLoading = false }: DevToolsButtonProps) {\n const [isHovered, setIsHovered] = useState(false)\n const [isFocused, setIsFocused] = useState(false)\n\n const buttonStyle = {\n ...styles['bugButton'],\n ...(isLoading && styles['loadingButton']),\n ...(!isLoading && isHovered && styles['bugButtonHover']),\n ...(!isLoading && isFocused && styles['bugButtonFocus']),\n }\n\n if (isLoading) {\n return (\n <div style={buttonStyle}>\n <style>\n {`\n @keyframes pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.4;\n }\n }\n `}\n </style>\n <BugIcon />\n </div>\n )\n }\n\n return (\n <button\n id=\"dev-tools-button\"\n onClick={onClick}\n type=\"button\"\n style={buttonStyle}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n >\n <BugIcon />\n </button>\n )\n}\n"],"mappings":"+yBAEA,OAAOA,GAAS,WAAAC,MAAe,QCF/B,OAAOC,GAAS,aAAAC,GAAW,WAAAC,GAAS,UAAAC,GAAQ,YAAAC,GAAU,eAAAC,OAAmB,QCEzE,OAAOC,GAAS,iBAAAC,GAAe,cAAAC,GAAY,YAAAC,EAAU,WAAAC,GAAS,eAAAC,EAAa,aAAAC,OAAiB,QCF5F,OAAOC,IAAS,WAAAC,GAAS,UAAAC,OAAc,QCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,EAAyC,CACnE,MAAMD,CAAO,EACb,KAAK,KAAO,iBACZ,KAAK,KAAOC,CACd,CACF,EAEaC,EAAY,CACvB,aAAc,eACd,uBAAwB,yBACxB,wBAAyB,0BACzB,eAAgB,gBAClB,EAOaC,EAAN,cAAgCJ,CAAe,CACpD,YAAYC,EAAkB,CAC5B,MAAM,CAAE,QAAS,iBAAiBA,GAAA,KAAAA,EAAW,EAAE,GAAI,KAAME,EAAU,YAAa,CAAC,EACjF,KAAK,KAAO,4BACd,CACF,EC7BA,OAAS,kBAAAE,OAAsB,SAC/B,OAAS,aAAAC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AAF,EAAY,qBAAAqB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACtB,EAAYqB,EAAsBC,CAAmB,CACxD,EAEA,OAAOnB,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcR,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G,CAcO,SAAS2B,GAAY9B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA7Q9B,EA6Q4BF,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,EAAmBC,EAAQ,KAAO,CAAE,WAAAF,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAOG,EAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcR,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["React","useMemo","React","useEffect","useMemo","useRef","useState","useCallback","React","createContext","useContext","useState","useMemo","useCallback","useEffect","React","useMemo","useRef","CapitalOSError","message","code","ErrorCode","InvalidTokenError","connectToChild","useEffect","useMemo","useRef","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","useEffect","connection","connectToChild","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","useRef","renderingContextRef","useMemo","buildIframeUrl","iframeResizer","React","forwardRef","useEffect","useImperativeHandle","useRef","IframeResizer","forwardRef","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","useRef","useEffect","iframe","iframeResizer","__spreadValues","useImperativeHandle","React","__spreadProps","resizerOptionsSet","acc","key","value","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","useRef","tokenData","useMemo","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","createContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","useState","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","useCallback","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","useEffect","onExchangeComplete","jwtToken","contextValue","useMemo","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","useContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","sizeWidth","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","useState","iframeRef","useRef","useErrorHandling","tokenData","useMemo","tokenDataFromOneTimeToken","handleTokenExpired","useCallback","CapitalOSError","ErrorCode","useEffect","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","React","useMemo","useState","React","useState","styles","BugIcon","React","DevToolsButton","onClick","isLoading","isHovered","setIsHovered","useState","isFocused","setIsFocused","buttonStyle","__spreadValues","styles","DevTools","props","entryPoint","renderingContext","useMemo","isOpen","setIsOpen","useState","React","DevToolsButton","CapitalOS","__spreadProps","__spreadValues","CardsApp","props","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","useMemo","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
package/dist/index.js CHANGED
@@ -1,2 +1,11 @@
1
- "use strict";"use client";var ne=Object.create;var D=Object.defineProperty,oe=Object.defineProperties,re=Object.getOwnPropertyDescriptor,ie=Object.getOwnPropertyDescriptors,se=Object.getOwnPropertyNames,z=Object.getOwnPropertySymbols,ae=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable;var W=(e,t,n)=>t in e?D(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,p=(e,t)=>{for(var n in t||(t={}))j.call(t,n)&&W(e,n,t[n]);if(z)for(var n of z(t))K.call(t,n)&&W(e,n,t[n]);return e},l=(e,t)=>oe(e,ie(t));var L=(e,t)=>{var n={};for(var o in e)j.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(e!=null&&z)for(var o of z(e))t.indexOf(o)<0&&K.call(e,o)&&(n[o]=e[o]);return n};var de=(e,t)=>{for(var n in t)D(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of se(t))!j.call(e,r)&&r!==n&&D(e,r,{get:()=>t[r],enumerable:!(o=re(t,r))||o.enumerable});return e};var w=(e,t,n)=>(n=e!=null?ne(ae(e)):{},V(t||!e||!e.__esModule?D(n,"default",{value:e,enumerable:!0}):n,e)),ce=e=>V(D({},"__esModule",{value:!0}),e);var J=(e,t,n)=>new Promise((o,r)=>{var i=u=>{try{d(n.next(u))}catch(f){r(f)}},s=u=>{try{d(n.throw(u))}catch(f){r(f)}},d=u=>u.done?o(u.value):Promise.resolve(u.value).then(i,s);d((n=n.apply(e,t)).next())});var Me={};de(Me,{AccountActions:()=>ve,AccountDetails:()=>Oe,App:()=>ke,BillPayApp:()=>Ee,CapitalOsAuthenticationProvider:()=>Z,CardDetails:()=>be,CardsApp:()=>te,DisputeTransaction:()=>Ie,InsightsDashboard:()=>De,InsightsWidget:()=>Le,IssueCard:()=>Pe,MakePayment:()=>Ae,Onboarding:()=>we});module.exports=ce(Me);var a=w(require("react"));var m=w(require("react"));var c=w(require("react"));var b=w(require("react"));var C=class extends Error{constructor({message:t,code:n}){super(t),this.name="CapitalOSError",this.code=n}},A={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},E=class extends C{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:A.unauthorized}),this.name="CapitalOSInvalidTokenError"}};var G=require("penpal"),P=require("react");var $="1.0.0-rc.6";function fe(e){let t=JSON.stringify(e),n=btoa(t);return encodeURIComponent(n)}function B(e){try{let t=decodeURIComponent(e),n=atob(t);return JSON.parse(n)}catch(t){throw new E}}function ge(e){try{return decodeURIComponent(e)}catch(t){return e}}function q({tokenData:e,renderingContext:t,theme:n,onError:o}){try{let r=t?l(p({},t),{referer:window.location.href}):null,i=r?fe(r):null,s=new URL(e.baseUrl),d=ge(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,d):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(d)),s.searchParams.set("sdkVersion",$),i&&s.searchParams.set("renderingContext",i),n&&s.searchParams.set("theme",n),s.toString()}catch(r){o==null||o(new E);return}}function S(e){let n=B(e).path;if(!n||typeof n!="string")throw new E;return{token:e,tokenType:"oneTime",baseUrl:n,paramKey:"token",paramLocation:"search"}}var he=1e4;function F({iframeRef:e,token:t,onError:n,methods:o}){(0,P.useEffect)(()=>{if(!e.current)return;let r=(0,G.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:he,methods:o});return r.promise.catch(i=>{n==null||n(i)}),()=>{r.destroy()}},[t,e])}function H({tokenData:e,renderingContext:t,theme:n,onError:o}){let r=(0,P.useRef)(o),i=(0,P.useRef)(t);return(0,P.useMemo)(()=>{if(e)return q({tokenData:e,renderingContext:i.current,theme:n,onError:r.current})},[e,n,r,i])}var Q=require("iframe-resizer"),x=w(require("react"));var M=(0,x.forwardRef)((e,t)=>{let n=e.title||"iframe",{iframeHTMLAttributes:o,resizerOptions:r}=ye(e),i=(0,x.useRef)(null);return(0,x.useEffect)(()=>{let s=i.current;return(0,Q.iframeResizer)(p({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,x.useImperativeHandle)(t,()=>i.current),x.default.createElement("iframe",l(p({},o),{title:n,ref:i}))});M.displayName="IframeResizer";var Ce=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],xe=new Set(Ce);function ye(e){return Object.keys(e).reduce((n,o)=>(xe.has(o)?n.resizerOptions[o]=e[o]:n.iframeHTMLAttributes[o]=e[o],n),{resizerOptions:{},iframeHTMLAttributes:{}})}function X(e){let{oneTimeToken:t,enableLogging:n,onExchangeComplete:o,onExchangeError:r}=e,i=(0,b.useRef)(null),s=(0,b.useMemo)(()=>S(t),[t]),u=H({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return F({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:f=>{r==null||r(new C(f))},tokenExchange:{onLongLivedToken:o}}}),b.default.createElement(M,{src:u,checkOrigin:!1,style:{display:"none"},log:!!n,ref:i})}var Y=(0,c.createContext)({isLoading:!1,invalidateToken:()=>{}}),Z=({getToken:e,enableLogging:t,children:n})=>{let[o,r]=(0,c.useState)(void 0),[i,s]=(0,c.useState)(void 0),[d,u]=(0,c.useState)(void 0),[f,R]=(0,c.useState)(!1),[O,T]=(0,c.useState)(void 0),I=(0,c.useCallback)(()=>J(void 0,null,function*(){R(!0);try{let h=yield e();r(h),T(void 0);let _=B(h),y=new URL(_.path);y.pathname="",s(y.toString())}catch(h){T(h)}finally{R(!1)}}),[e]),v=(0,c.useCallback)(()=>{u(void 0)},[]);(0,c.useEffect)(()=>{d||I()},[d,I]);let k=(0,c.useCallback)(h=>{u(h),r(void 0),T(void 0)},[]),U=(0,c.useMemo)(()=>{if(d&&!i)throw new C({message:"baseUrl is required for long lived tokens",code:A.unauthorized});return{tokenData:d?{token:d,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:f,error:O,invalidateToken:v}},[d,f,O,v,i]);return c.default.createElement(c.default.Fragment,null,c.default.createElement(Y.Provider,{value:U},n),o&&!d&&c.default.createElement(X,{oneTimeToken:o,onExchangeComplete:k,enableLogging:t,onExchangeError:T}))},ee=()=>(0,c.useContext)(Y);function g(e){let{token:t,className:n,enableLogging:o,onError:r,loadingComponent:i,renderingContext:s,methods:d,theme:u}=e,{tokenData:f,error:R,invalidateToken:O}=ee(),[T,I]=(0,m.useState)(!1),v=(0,m.useRef)(null);Te(R,r);let k=(0,m.useMemo)(()=>t?S(t):f,[t,f]),U=(0,m.useCallback)(()=>{if(o&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new C({message:"Token expired. Cannot automatically refresh when using token prop.",code:A.unauthorized}));return}O(),I(!1)},[t,O,o,r]);(0,m.useEffect)(()=>{t&&f&&o&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,f,o]);let h=H({tokenData:k,renderingContext:s,theme:u,onError:r});if(F({iframeRef:v,token:k==null?void 0:k.token,onError:y=>{r==null||r(y),I(!0)},methods:p({onLoad:()=>I(!0),onError:y=>{let N=new C(y);r==null||r(N)},onTokenExpired:U},d)}),!k||!h)return m.default.createElement(m.default.Fragment,null,i||null);let _=s.entryPoint!=="insightsWidget";return m.default.createElement(m.default.Fragment,null,!T&&i,m.default.createElement(M,{src:h,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:n,log:!!o,ref:v,hidden:!T,onResized:y=>{if(!_)return;let N=`${parseInt(y.height)+12}px`;y.iframe.style.height=N}}))}function Te(e,t){let n=(0,m.useRef)(!1);(0,m.useEffect)(()=>{e&&!n.current&&(t==null||t(e),n.current=!0)},[e,t])}function te(e){let t="cardsApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}var ke=te;function Pe(r){var i=r,{cardholder:e,onDone:t,onCancel:n}=i,o=L(i,["cardholder","onDone","onCancel"]);let s="createCard",d=(0,a.useMemo)(()=>({entryPoint:s,cardholder:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createCard:{onDone:t,onCancel:n}}}))}function Ie(r){var i=r,{transactionId:e,onDone:t,onCancel:n}=i,o=L(i,["transactionId","onDone","onCancel"]);let s="createDispute",d=(0,a.useMemo)(()=>({entryPoint:s,transactionId:e}),[e]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{createDispute:{onDone:t,onCancel:n}}}))}function Ee(e){let t="billPayApp",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function be(e){let t="cardDetails",n=(0,a.useMemo)(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly}),[t,e.cardId,e.cardOnly]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Oe(e){let t="accountDetails",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function ve(e){let t="accountActions",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function De(e){let t="insightsDashboard",n=(0,a.useMemo)(()=>({entryPoint:t}),[t]);return a.default.createElement(g,l(p({},e),{renderingContext:n}))}function Le(e){let t="insightsWidget",{widget:n,hideTitle:o,height:r,width:i}=e,s=(0,a.useMemo)(()=>({entryPoint:t,widget:n,hideTitle:o,height:r,width:i}),[t,n,o,r,i]);return a.default.createElement(g,l(p({},e),{renderingContext:s}))}function we(r){var i=r,{onDone:e,entryPoint:t,exitPoint:n}=i,o=L(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",d=(0,a.useMemo)(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:n}),[s,t,n]);return a.default.createElement(g,l(p({},o),{renderingContext:d,methods:{onboarding:{onDone:e}}}))}function Ae(n){var o=n,{onDone:e}=o,t=L(o,["onDone"]);let r="makePayment",i=(0,a.useMemo)(()=>({entryPoint:r}),[r]);return a.default.createElement(g,l(p({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}0&&(module.exports={AccountActions,AccountDetails,App,BillPayApp,CapitalOsAuthenticationProvider,CardDetails,CardsApp,DisputeTransaction,InsightsDashboard,InsightsWidget,IssueCard,MakePayment,Onboarding});
1
+ "use strict";"use client";var ce=Object.create;var M=Object.defineProperty,me=Object.defineProperties,le=Object.getOwnPropertyDescriptor,ue=Object.getOwnPropertyDescriptors,fe=Object.getOwnPropertyNames,_=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,Z=Object.prototype.propertyIsEnumerable;var q=(e,t,o)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,a=(e,t)=>{for(var o in t||(t={}))V.call(t,o)&&q(e,o,t[o]);if(_)for(var o of _(t))Z.call(t,o)&&q(e,o,t[o]);return e},m=(e,t)=>me(e,ue(t));var A=(e,t)=>{var o={};for(var n in e)V.call(e,n)&&t.indexOf(n)<0&&(o[n]=e[n]);if(e!=null&&_)for(var n of _(e))t.indexOf(n)<0&&Z.call(e,n)&&(o[n]=e[n]);return o};var he=(e,t)=>{for(var o in t)M(e,o,{get:t[o],enumerable:!0})},G=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of fe(t))!V.call(e,r)&&r!==o&&M(e,r,{get:()=>t[r],enumerable:!(n=le(t,r))||n.enumerable});return e};var v=(e,t,o)=>(o=e!=null?ce(ge(e)):{},G(t||!e||!e.__esModule?M(o,"default",{value:e,enumerable:!0}):o,e)),Ce=e=>G(M({},"__esModule",{value:!0}),e);var Q=(e,t,o)=>new Promise((n,r)=>{var i=u=>{try{p(o.next(u))}catch(h){r(h)}},s=u=>{try{p(o.throw(u))}catch(h){r(h)}},p=u=>u.done?n(u.value):Promise.resolve(u.value).then(i,s);p((o=o.apply(e,t)).next())});var Ne={};he(Ne,{AccountActions:()=>Re,AccountDetails:()=>Fe,App:()=>we,BillPayApp:()=>Se,CapitalOsAuthenticationProvider:()=>re,CardDetails:()=>ze,CardsApp:()=>pe,DevTools:()=>de,DisputeTransaction:()=>Ae,InsightsDashboard:()=>He,InsightsWidget:()=>Be,IssueCard:()=>Me,MakePayment:()=>_e,Onboarding:()=>Ue});module.exports=Ce(Ne);var d=v(require("react"));var l=v(require("react"));var c=v(require("react"));var L=v(require("react"));var C=class extends Error{constructor({message:t,code:o}){super(t),this.name="CapitalOSError",this.code=o}},S={unauthorized:"unauthorized",invalid_account_status:"invalid_account_status",unsupported_entry_point:"unsupported_entry_point",internal_error:"internal_error"},D=class extends C{constructor(t){super({message:`Invalid token ${t!=null?t:""}`,code:S.unauthorized}),this.name="CapitalOSInvalidTokenError"}};var ee=require("penpal"),I=require("react");var X="1.0.0-rc.8";function Pe(e){let t=JSON.stringify(e),o=btoa(t);return encodeURIComponent(o)}function J(e){try{let t=decodeURIComponent(e),o=atob(t);return JSON.parse(o)}catch(t){throw new D}}function be(e){try{return decodeURIComponent(e)}catch(t){return e}}function Y({tokenData:e,renderingContext:t,theme:o,onError:n}){try{let r=t?m(a({},t),{referer:window.location.href}):null,i=r?Pe(r):null,s=new URL(e.baseUrl),p=be(e.token);return e.paramLocation==="search"?s.searchParams.set(e.paramKey,p):e.paramLocation==="hash"&&(s.hash=e.paramKey+"="+encodeURIComponent(p)),s.searchParams.set("sdkVersion",X),i&&s.searchParams.set("renderingContext",i),o&&s.searchParams.set("theme",o),s.toString()}catch(r){n==null||n(new D);return}}function N(e){let o=J(e).path;if(!o||typeof o!="string")throw new D;return{token:e,tokenType:"oneTime",baseUrl:o,paramKey:"token",paramLocation:"search"}}var ve=1e4;function W({iframeRef:e,token:t,onError:o,methods:n}){(0,I.useEffect)(()=>{if(!e.current)return;let r=(0,ee.connectToChild)({iframe:e.current,childOrigin:"*",debug:!0,timeout:ve,methods:n});return r.promise.catch(i=>{o==null||o(i)}),()=>{r.destroy()}},[t,e])}function j({tokenData:e,renderingContext:t,theme:o,onError:n}){let r=(0,I.useRef)(n),i=(0,I.useRef)(t);return(0,I.useMemo)(()=>{if(e)return Y({tokenData:e,renderingContext:i.current,theme:o,onError:r.current})},[e,o,r,i])}var te=require("iframe-resizer"),x=v(require("react"));var z=(0,x.forwardRef)((e,t)=>{let o=e.title||"iframe",{iframeHTMLAttributes:n,resizerOptions:r}=Oe(e),i=(0,x.useRef)(null);return(0,x.useEffect)(()=>{let s=i.current;return(0,te.iframeResizer)(a({},r),s),()=>s.iFrameResizer&&s.iFrameResizer.removeListeners()}),(0,x.useImperativeHandle)(t,()=>i.current),x.default.createElement("iframe",m(a({},n),{title:o,ref:i}))});z.displayName="IframeResizer";var Ie=["autoResize","bodyBackground","bodyMargin","bodyPadding","checkOrigin","inPageLinks","heightCalculationMethod","interval","log","maxHeight","maxWidth","minHeight","minWidth","resizeFrom","scrolling","sizeHeight","sizeWidth","warningTimeout","tolerance","widthCalculationMethod","onClosed","onInit","onMessage","onResized","onScroll"],Ee=new Set(Ie);function Oe(e){return Object.keys(e).reduce((o,n)=>{let r=e[n];return Ee.has(n)?r!==void 0&&(o.resizerOptions[n]=e[n]):o.iframeHTMLAttributes[n]=e[n],o},{resizerOptions:{},iframeHTMLAttributes:{}})}function oe(e){let{oneTimeToken:t,enableLogging:o,onExchangeComplete:n,onExchangeError:r}=e,i=(0,L.useRef)(null),s=(0,L.useMemo)(()=>N(t),[t]),u=j({tokenData:s,onError:r,renderingContext:{entryPoint:"tokenExchange"}});return W({iframeRef:i,token:t,onError:r,methods:{onLoad:()=>{},onError:h=>{r==null||r(new C(h))},tokenExchange:{onLongLivedToken:n}}}),L.default.createElement(z,{src:u,checkOrigin:!1,style:{display:"none"},log:!!o,ref:i})}var ne=(0,c.createContext)({isLoading:!1,invalidateToken:()=>{}}),re=({getToken:e,enableLogging:t,children:o})=>{let[n,r]=(0,c.useState)(void 0),[i,s]=(0,c.useState)(void 0),[p,u]=(0,c.useState)(void 0),[h,k]=(0,c.useState)(!1),[R,P]=(0,c.useState)(void 0),w=(0,c.useCallback)(()=>Q(void 0,null,function*(){k(!0);try{let y=yield e();r(y),P(void 0);let B=J(y),U=new URL(B.path);U.pathname="",s(U.toString())}catch(y){P(y)}finally{k(!1)}}),[e]),E=(0,c.useCallback)(()=>{u(void 0)},[]);(0,c.useEffect)(()=>{p||w()},[p,w]);let H=(0,c.useCallback)(y=>{u(y),r(void 0),P(void 0)},[]),b=(0,c.useMemo)(()=>{if(p&&!i)throw new C({message:"baseUrl is required for long lived tokens",code:S.unauthorized});return{tokenData:p?{token:p,tokenType:"longLived",baseUrl:i,paramKey:"access_token",paramLocation:"hash"}:void 0,isLoading:h,error:R,invalidateToken:E}},[p,h,R,E,i]);return c.default.createElement(c.default.Fragment,null,c.default.createElement(ne.Provider,{value:b},o),n&&!p&&c.default.createElement(oe,{oneTimeToken:n,onExchangeComplete:H,enableLogging:t,onExchangeError:P}))},ie=()=>(0,c.useContext)(ne);function f(e){let{token:t,className:o,enableLogging:n,onError:r,loadingComponent:i,renderingContext:s,methods:p,theme:u,sizeWidth:h}=e,{tokenData:k,error:R,invalidateToken:P}=ie(),[w,E]=(0,l.useState)(!1),H=(0,l.useRef)(null);De(R,r);let b=(0,l.useMemo)(()=>t?N(t):k,[t,k]),y=(0,l.useCallback)(()=>{if(n&&console.log("CapitalOS: Token expired, invalidating..."),t){r==null||r(new C({message:"Token expired. Cannot automatically refresh when using token prop.",code:S.unauthorized}));return}P(),E(!1)},[t,P,n,r]);(0,l.useEffect)(()=>{t&&k&&n&&console.warn("CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence")},[t,k,n]);let B=j({tokenData:b,renderingContext:s,theme:u,onError:r});if(W({iframeRef:H,token:b==null?void 0:b.token,onError:O=>{r==null||r(O),E(!0)},methods:a({onLoad:()=>{E(!0)},onError:O=>{let K=new C(O);r==null||r(K)},onTokenExpired:y},p)}),!b||!B)return l.default.createElement(l.default.Fragment,null,i||null);let U=s.entryPoint!=="insightsWidget";return l.default.createElement(l.default.Fragment,null,!w&&i,l.default.createElement(z,{src:B,allow:"clipboard-write",checkOrigin:!1,style:{width:"1px",height:"0px",minWidth:"100%"},className:o,log:!!n,ref:H,hidden:!w,onResized:O=>{if(!U)return;let K=`${parseInt(O.height)+12}px`;O.iframe.style.height=K},sizeWidth:h}))}function De(e,t){let o=(0,l.useRef)(!1);(0,l.useEffect)(()=>{e&&!o.current&&(t==null||t(e),o.current=!0)},[e,t])}var T=v(require("react")),ae=require("react");var g=v(require("react"));var F={bugButton:{position:"fixed",left:"12px",bottom:"12px",margin:"12px",padding:"4px",display:"inline-flex",alignItems:"center",borderRadius:"9999px",border:"1px solid transparent",backgroundColor:"#2563eb",color:"white",opacity:.4,boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)",cursor:"pointer",zIndex:50,transition:"opacity 0.3s ease-in-out"},bugButtonHover:{backgroundColor:"#1d4ed8",opacity:1},bugButtonFocus:{outline:"none",boxShadow:"0 0 0 2px white, 0 0 0 4px #3b82f6"},bugIcon:{width:"20px",height:"20px"},loadingButton:{cursor:"default",opacity:1,animation:"pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite"}},se=()=>g.default.createElement("svg",{style:F.bugIcon,xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:"1.5",stroke:"currentColor"},g.default.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 12.75c1.148 0 2.278.08 3.383.237 1.037.146 1.866.966 1.866 2.013 0 3.728-2.35 6.75-5.25 6.75S6.75 18.728 6.75 15c0-1.046.83-1.867 1.866-2.013A24.204 24.204 0 0 1 12 12.75Zm0 0c2.883 0 5.647.508 8.207 1.44a23.91 23.91 0 0 1-1.152 6.06M12 12.75c-2.883 0-5.647.508-8.208 1.44.125 2.104.52 4.136 1.153 6.06M12 12.75a2.25 2.25 0 0 0 2.248-2.354M12 12.75a2.25 2.25 0 0 1-2.248-2.354M12 8.25c.995 0 1.971-.08 2.922-.236.403-.066.74-.358.795-.762a3.778 3.778 0 0 0-.399-2.25M12 8.25c-.995 0-1.97-.08-2.922-.236-.402-.066-.74-.358-.795-.762a3.734 3.734 0 0 1 .4-2.253M12 8.25a2.25 2.25 0 0 0-2.248 2.146M12 8.25a2.25 2.25 0 0 1 2.248 2.146M8.683 5a6.032 6.032 0 0 1-1.155-1.002c.07-.63.27-1.222.574-1.747m.581 2.749A3.75 3.75 0 0 1 15.318 5m0 0c.427-.283.815-.62 1.155-.999a4.471 4.471 0 0 0-.575-1.752M4.921 6a24.048 24.048 0 0 0-.392 3.314c1.668.546 3.416.914 5.223 1.082M19.08 6c.205 1.08.337 2.187.392 3.314a23.882 23.882 0 0 1-5.223 1.082"}));function $({onClick:e,isLoading:t=!1}){let[o,n]=(0,g.useState)(!1),[r,i]=(0,g.useState)(!1),s=a(a(a(a({},F.bugButton),t&&F.loadingButton),!t&&o&&F.bugButtonHover),!t&&r&&F.bugButtonFocus);return t?g.default.createElement("div",{style:s},g.default.createElement("style",null,`
2
+ @keyframes pulse {
3
+ 0%, 100% {
4
+ opacity: 1;
5
+ }
6
+ 50% {
7
+ opacity: 0.4;
8
+ }
9
+ }
10
+ `),g.default.createElement(se,null)):g.default.createElement("button",{id:"dev-tools-button",onClick:e,type:"button",style:s,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),onFocus:()=>i(!0),onBlur:()=>i(!1)},g.default.createElement(se,null))}var Le={panel:{position:"fixed",bottom:"20px",left:"20px",zIndex:50}};function de(e){let t="devTools",o=(0,T.useMemo)(()=>({entryPoint:t}),[t]),[n,r]=(0,ae.useState)(!1);return T.default.createElement("aside",{"aria-label":"CapitalOS dev tools"},!n&&T.default.createElement($,{onClick:()=>r(!n)}),n&&T.default.createElement("div",{style:Le.panel},T.default.createElement(f,m(a({},e),{renderingContext:o,methods:{devTools:{onClose:()=>r(!1)}},enableLogging:!0,sizeWidth:!0,loadingComponent:T.default.createElement($,{isLoading:!0})}))))}function pe(e){let t="cardsApp",o=(0,d.useMemo)(()=>({entryPoint:t}),[t]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}var we=pe;function Me(r){var i=r,{cardholder:e,onDone:t,onCancel:o}=i,n=A(i,["cardholder","onDone","onCancel"]);let s="createCard",p=(0,d.useMemo)(()=>({entryPoint:s,cardholder:e}),[e]);return d.default.createElement(f,m(a({},n),{renderingContext:p,methods:{createCard:{onDone:t,onCancel:o}}}))}function Ae(r){var i=r,{transactionId:e,onDone:t,onCancel:o}=i,n=A(i,["transactionId","onDone","onCancel"]);let s="createDispute",p=(0,d.useMemo)(()=>({entryPoint:s,transactionId:e}),[e]);return d.default.createElement(f,m(a({},n),{renderingContext:p,methods:{createDispute:{onDone:t,onCancel:o}}}))}function Se(e){let t="billPayApp",o=(0,d.useMemo)(()=>({entryPoint:t}),[t]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}function ze(e){let t="cardDetails",o=(0,d.useMemo)(()=>({entryPoint:t,cardId:e.cardId,cardOnly:e.cardOnly,hideAddress:e.hideAddress}),[t,e.cardId,e.cardOnly]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}function Fe(e){let t="accountDetails",o=(0,d.useMemo)(()=>({entryPoint:t}),[t]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}function Re(e){let t="accountActions",o=(0,d.useMemo)(()=>({entryPoint:t}),[t]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}function He(e){let t="insightsDashboard",o=(0,d.useMemo)(()=>({entryPoint:t}),[t]);return d.default.createElement(f,m(a({},e),{renderingContext:o}))}function Be(e){let t="insightsWidget",{widget:o,hideTitle:n,height:r,width:i}=e,s=(0,d.useMemo)(()=>({entryPoint:t,widget:o,hideTitle:n,height:r,width:i}),[t,o,n,r,i]);return d.default.createElement(f,m(a({},e),{renderingContext:s}))}function Ue(r){var i=r,{onDone:e,entryPoint:t,exitPoint:o}=i,n=A(i,["onDone","entryPoint","exitPoint"]);let s="onboarding",p=(0,d.useMemo)(()=>({entryPoint:s,onboardingEntryPoint:t,onboardingExitPoint:o}),[s,t,o]);return d.default.createElement(f,m(a({},n),{renderingContext:p,methods:{onboarding:{onDone:e}}}))}function _e(o){var n=o,{onDone:e}=n,t=A(n,["onDone"]);let r="makePayment",i=(0,d.useMemo)(()=>({entryPoint:r}),[r]);return d.default.createElement(f,m(a({},t),{renderingContext:i,methods:{makePayment:{onDone:e}}}))}0&&(module.exports={AccountActions,AccountDetails,App,BillPayApp,CapitalOsAuthenticationProvider,CardDetails,CardsApp,DevTools,DisputeTransaction,InsightsDashboard,InsightsWidget,IssueCard,MakePayment,Onboarding});
2
11
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.tsx","../src/capital-os.tsx","../src/context/capital-os-authentication-context.tsx","../src/common/token-exchange-iframe.tsx","../src/error.ts","../src/hooks.ts","../package.json","../src/utils.ts","../src/iframe-resizer.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => setIsLoaded(true),\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.6\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = Object.keys(props).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n if (resizerOptionsSet.has(key)) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n"],"mappings":"2xCAAA,IAAA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AAO,CAAE,GAAG,CAC9G,CAcO,SAAS0B,GAAY7B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA3Q9B,EA2Q4BF,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,KAAmB,WAAQ,KAAO,CAAE,WAAAD,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAO,EAAAE,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["src_exports","__export","AccountActions","AccountDetails","App","BillPayApp","CapitalOsAuthenticationProvider","CardDetails","CardsApp","DisputeTransaction","InsightsDashboard","InsightsWidget","IssueCard","MakePayment","Onboarding","__toCommonJS","import_react","import_react","import_react","import_react","CapitalOSError","message","code","ErrorCode","InvalidTokenError","import_penpal","import_react","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","renderingContextRef","buildIframeUrl","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","tokenData","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","onExchangeComplete","jwtToken","contextValue","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","iframeRef","useErrorHandling","tokenData","tokenDataFromOneTimeToken","handleTokenExpired","CapitalOSError","ErrorCode","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","CardsApp","props","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
1
+ {"version":3,"sources":["../src/index.tsx","../src/capital-os.tsx","../src/context/capital-os-authentication-context.tsx","../src/common/token-exchange-iframe.tsx","../src/error.ts","../src/hooks.ts","../package.json","../src/utils.ts","../src/iframe-resizer.tsx","../src/dev-tools.tsx","../src/components/dev-tools-button.tsx"],"sourcesContent":["'use client'\n\nimport React, { useMemo } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { CapitalOsAuthenticationProvider } from './context/capital-os-authentication-context'\nimport { DevTools } from './dev-tools'\nimport type { EntryPoint, IssueCardDefaultValues } from './external-types'\nimport type { Account, CommonProps } from './types'\n\n// #region App\n/**\n * Renders the CapitalOS CardsApp.\n */\nexport function CardsApp(props: CommonProps) {\n const entryPoint: EntryPoint = 'cardsApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// maintain backwards compatibility\n\n/** @deprecated Use {@link CardsApp} instead */\nconst App = CardsApp\n\nexport { App }\n\n// #region Issue Card\nexport type IssueCardProps = CommonProps & {\n /**\n * Default values to prefill the form with.\n *\n * Either provide a userId, in which case the default values will be taken from that user's profile, or provide the cardholder's details directly.\n */\n cardholder?: IssueCardDefaultValues\n\n /**\n * Callback to invoke when the card was created successfully.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the card creation was cancelled by the user.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Issue Card experience.\n */\nexport function IssueCard({ cardholder, onDone, onCancel, ...restOfProps }: IssueCardProps) {\n const entryPoint: EntryPoint = 'createCard'\n const renderingContext = useMemo(\n () => ({\n entryPoint,\n cardholder,\n }),\n [cardholder],\n )\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createCard: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Dispute Transaction\nexport type DisputeTransactionProps = CommonProps & {\n /**\n * The ID of the transaction to dispute.\n */\n transactionId: string\n\n /**\n * Callback to invoke when the dispute was successfully submitted.\n */\n onDone: () => void\n\n /**\n * Callback to invoke when the user cancels the dispute submission.\n */\n onCancel: () => void\n}\n\n/**\n * Renders the CapitalOS Dispute Transaction experience.\n */\nexport function DisputeTransaction({ transactionId, onDone, onCancel, ...restOfProps }: DisputeTransactionProps) {\n const entryPoint: EntryPoint = 'createDispute'\n const renderingContext = useMemo(() => ({ entryPoint, transactionId }), [transactionId])\n\n return (\n <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ createDispute: { onDone, onCancel } }} />\n )\n}\n// #endregion\n\n// #region Bill Payment Dashboard\nexport type BillPayAppProps = CommonProps\n\n/**\n * Renders the CapitalOS Bill Payment Dashboard experience.\n */\nexport function BillPayApp(props: BillPayAppProps) {\n const entryPoint: EntryPoint = 'billPayApp'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Card Details\nexport type CardDetailsProps = CommonProps & {\n /**\n * The ID of the card to manage.\n */\n cardId: string\n cardOnly?: boolean | undefined\n hideAddress?: boolean | undefined\n}\n\n/**\n * Renders the CapitalOS Manage Card experience.\n */\nexport function CardDetails(props: CardDetailsProps) {\n const entryPoint: EntryPoint = 'cardDetails'\n const renderingContext = useMemo(\n () => ({ entryPoint, cardId: props.cardId, cardOnly: props.cardOnly, hideAddress: props.hideAddress }),\n [entryPoint, props.cardId, props.cardOnly],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Details\nexport type AccountDetailsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Details experience.\n */\nexport function AccountDetails(props: AccountDetailsProps) {\n const entryPoint: EntryPoint = 'accountDetails'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Account Actions\nexport type AccountActionsProps = CommonProps\n\n/**\n * Renders the CapitalOS Account Actions experience.\n */\nexport function AccountActions(props: AccountActionsProps) {\n const entryPoint: EntryPoint = 'accountActions'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Dashboard\nexport type InsightsDashboardProps = CommonProps\n\n/**\n * Renders the CapitalOS Insights Dashboard experience\n */\nexport function InsightsDashboard(props: InsightsDashboardProps) {\n const entryPoint: EntryPoint = 'insightsDashboard'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Insights Widget\nexport type InsightsWidgetProps = CommonProps & {\n /**\n * The specific widget to render.\n * naming convention:\n * 1. Over-time Widgets\n * over-time-{metric}-by-{dimension}-per-{time-granularity}\n * 2. Top/Ranking Widgets\n * top-{entities}-by-{metric}-{timeframe}\n * 3. Comparison Widgets\n * comparison-{metric}-{primary-timeframe}-vs-{secondary-timeframe}\n */\n widget:\n | 'over-time-spend-by-card-per-month'\n | 'over-time-spend-by-category-per-month'\n | 'top-cards-by-spend-this-month'\n | 'top-categories-by-spend-this-month'\n | 'top-transactions-by-amount-this-month'\n | 'comparison-spend-this-month-vs-last-month'\n /**\n * Whether to hide the title of the widget.\n */\n hideTitle?: boolean | undefined\n /**\n * The height of the widget.\n */\n height?: number | undefined\n /**\n * The width of the widget.\n */\n width?: number | undefined\n}\n\n/**\n * Renders a specific CapitalOS Insights Widget\n */\nexport function InsightsWidget(props: InsightsWidgetProps) {\n const entryPoint: EntryPoint = 'insightsWidget'\n const { widget, hideTitle, height, width } = props\n const renderingContext = useMemo(\n () => ({ entryPoint, widget, hideTitle, height, width }),\n [entryPoint, widget, hideTitle, height, width],\n )\n\n return <CapitalOS {...props} renderingContext={renderingContext} />\n}\n// #endregion\n\n// #region Onboarding\ntype AllowedExitPoints = {\n welcome: 'application' | 'activation'\n application: 'application' | 'activation'\n}\n\ntype OnboardingEntryPoint = keyof AllowedExitPoints\ntype OnboardingProps<T extends keyof AllowedExitPoints> = CommonProps & {\n entryPoint?: T\n exitPoint?: AllowedExitPoints[T]\n onDone: (account: Account) => void\n}\n\nexport function Onboarding<T extends OnboardingEntryPoint>({\n onDone,\n entryPoint: onboardingEntryPoint,\n exitPoint: onboardingExitPoint,\n ...restOfProps\n}: OnboardingProps<T>) {\n // This component uses 'entryPoint' in two distinct ways:\n // 1. As a prop to control the user's starting/ending stages of onboarding\n // 2. For internal rendering context to determine which client component to display\n const entryPoint: EntryPoint = 'onboarding'\n const renderingContext = useMemo(\n () => ({ entryPoint, onboardingEntryPoint, onboardingExitPoint }),\n [entryPoint, onboardingEntryPoint, onboardingExitPoint],\n )\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ onboarding: { onDone } }} />\n}\n// #endregion\n\n// #region Make a payment\nexport type MakePaymentProps = CommonProps & {\n /**\n * Callback to invoke when the payment was made successfully.\n */\n onDone: () => void\n}\n\n/**\n * Renders the CapitalOS Make a Payment experience.\n */\nexport function MakePayment({ onDone, ...restOfProps }: MakePaymentProps) {\n const entryPoint: EntryPoint = 'makePayment'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n return <CapitalOS {...restOfProps} renderingContext={renderingContext} methods={{ makePayment: { onDone } }} />\n}\n// #endregion\n\n// #region Dev Tools\nexport { DevTools }\n// #endregion\n\n// #region Authentication provider\nexport { CapitalOsAuthenticationProvider }\n// #endregion\n","import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'\n\nimport { useCapitalOsAuthContext } from './context/capital-os-authentication-context'\nimport { CapitalOSError, ErrorCode } from './error'\nimport { IframeConnectionMethods, useIframeConnection, useIframeUrl } from './hooks'\nimport { IframeResizer } from './iframe-resizer'\nimport { CommonProps, CapitalOsRenderingContext, TokenData } from './types'\nimport { tokenDataFromOneTimeToken } from './utils'\n\ntype CapitalOsProps<T extends CapitalOsRenderingContext> = CommonProps & {\n renderingContext: T\n methods?: Partial<IframeConnectionMethods>\n sizeWidth?: boolean\n}\n\n/**\n * The internal component that handles all the heavy lifting of connecting to the iframe and rendering the app.\n * all user facing components are basically a syntactic sugar on top of this.\n */\nexport function CapitalOS<T extends CapitalOsRenderingContext>(props: CapitalOsProps<T>) {\n const {\n token: tokenProp,\n className,\n enableLogging,\n onError,\n loadingComponent: LoadingComponent,\n renderingContext,\n methods,\n theme,\n sizeWidth,\n } = props\n const { tokenData: contextTokenData, error, invalidateToken } = useCapitalOsAuthContext()\n // represents the state of whether all required react queries returned and the page should be visible\n const [isLoaded, setIsLoaded] = useState(false)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n useErrorHandling(error, onError)\n\n const tokenData: TokenData | undefined = useMemo(\n () => (tokenProp ? tokenDataFromOneTimeToken(tokenProp) : contextTokenData),\n [tokenProp, contextTokenData],\n )\n\n // Handle token expiration by invalidating the token\n // The context's useEffect will automatically handle the refresh\n const handleTokenExpired = useCallback(() => {\n if (enableLogging) {\n // eslint-disable-next-line no-console\n console.log('CapitalOS: Token expired, invalidating...')\n }\n\n // If we're using tokenProp, we can't refresh automatically\n if (tokenProp) {\n onError?.(\n new CapitalOSError({\n message: 'Token expired. Cannot automatically refresh when using token prop.',\n code: ErrorCode.unauthorized,\n }),\n )\n return\n }\n\n // Use the invalidateToken function from the context\n // This will clear the token and the authentication context's useEffect will handle the refresh\n invalidateToken()\n\n // The iframe will be reloaded automatically when tokenData changes\n setIsLoaded(false)\n }, [tokenProp, invalidateToken, enableLogging, onError])\n\n useEffect(() => {\n if (tokenProp && contextTokenData && enableLogging) {\n // eslint-disable-next-line no-console\n console.warn(\n 'CapitalOS: token was provided both from provider and from the token prop. the prop will take precedence',\n )\n }\n }, [tokenProp, contextTokenData, enableLogging])\n\n const url = useIframeUrl({ tokenData, renderingContext, theme, onError })\n\n useIframeConnection({\n iframeRef,\n token: tokenData?.token,\n onError: (error) => {\n onError?.(error)\n // when connection fails it's probably a handshake timeout with the iframe. we will stop showing the loader\n // since the fact we failed communication doesn't necessarily mean the iframe didn't load\n setIsLoaded(true)\n },\n methods: {\n onLoad: () => {\n setIsLoaded(true)\n },\n onError: (error) => {\n const err = new CapitalOSError(error)\n onError?.(err)\n },\n onTokenExpired: handleTokenExpired,\n ...methods,\n },\n })\n\n if (!tokenData || !url) {\n return <>{LoadingComponent || null}</>\n }\n\n // insightsWidget does not need additional padding. also - it supports a height property that needs to be respected.\n const shouldAddPaddingBottom = renderingContext.entryPoint !== 'insightsWidget'\n\n return (\n <>\n {/* show loader as long as we're not loaded */}\n {!isLoaded && LoadingComponent}\n {/* hide the iframe as long as we're not loaded */}\n <IframeResizer\n src={url}\n allow=\"clipboard-write\"\n checkOrigin={false}\n style={{ width: '1px', height: '0px', minWidth: '100%' }}\n className={className}\n log={!!enableLogging}\n ref={iframeRef}\n hidden={!isLoaded}\n // Add a constant offset to the height of the iframe to account for css shadows.\n // This is useful for tooltips that are rendered with shadows below them that extend beyond the bottom of the tooltip.\n onResized={(data) => {\n if (!shouldAddPaddingBottom) {\n return\n }\n\n // typing is wrong here. this is a string.\n const newHeight = `${parseInt(data.height as unknown as string) + 12}px`\n data.iframe.style.height = newHeight\n }}\n sizeWidth={sizeWidth}\n />\n </>\n )\n}\n\n/**\n * Makes sure component only fires the error event once.\n * @param error - The error to handle.\n * @param onError - The function to call when the error occurs.\n */\nfunction useErrorHandling(error: Error | null | undefined, onError?: (error: Error) => void) {\n const errorFired = useRef(false)\n\n useEffect(() => {\n if (error && !errorFired.current) {\n onError?.(error)\n errorFired.current = true\n }\n }, [error, onError])\n}\n","'use client'\n\nimport React, { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react'\n\nimport { TokenExchangeIframe } from '../common/token-exchange-iframe'\nimport { CapitalOSError, ErrorCode } from '../error'\nimport { TokenData, TokenParamKey, TokenParamLocation, TokenType } from '../types'\nimport { decodeOneTimeToken } from '../utils'\n\ntype CapitalOsAuthenticationContextType = {\n tokenData?: TokenData | undefined\n isLoading: boolean\n error?: Error | undefined\n /**\n * Invalidates the current token..\n * This is used when the iframe signals that the token has expired.\n * The authentication flow will automatically refresh the token after invalidation.\n */\n invalidateToken: () => void\n}\n\ntype ProviderProps = {\n getToken: () => Promise<string>\n enableLogging?: boolean | undefined\n children: React.ReactNode\n}\n\nconst CapitalOsAuthenticationContext = createContext<CapitalOsAuthenticationContextType>({\n isLoading: false,\n invalidateToken: () => {},\n})\n\nexport const CapitalOsAuthenticationProvider: React.FC<ProviderProps> = ({ getToken, enableLogging, children }) => {\n const [oneTimeToken, setOneTimeToken] = useState<string | undefined>(undefined)\n const [baseUrl, setBaseUrl] = useState<string | undefined>(undefined)\n const [longLivedToken, setLongLivedToken] = useState<string | undefined>(undefined)\n const [isLoading, setIsLoading] = useState(false)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n const refreshOneTimeToken = useCallback(async () => {\n setIsLoading(true)\n try {\n const newToken = await getToken()\n setOneTimeToken(newToken)\n setError(undefined)\n const tokenObject = decodeOneTimeToken(newToken)\n const url = new URL(tokenObject.path)\n // we don't need the /login part of the path since long lived tokens don't go through the login flow.\n url.pathname = ''\n setBaseUrl(url.toString())\n } catch (error) {\n setError(error as Error)\n } finally {\n setIsLoading(false)\n }\n }, [getToken])\n\n // Add invalidateToken method\n const invalidateToken = useCallback(() => {\n setLongLivedToken(undefined)\n }, [])\n\n // On mount, if no long-lived token is available, refresh to get a one-time token.\n useEffect(() => {\n if (!longLivedToken) {\n refreshOneTimeToken()\n }\n }, [longLivedToken, refreshOneTimeToken])\n\n const onExchangeComplete = useCallback((jwtToken: string) => {\n setLongLivedToken(jwtToken)\n setOneTimeToken(undefined)\n setError(undefined)\n }, [])\n\n const contextValue: CapitalOsAuthenticationContextType = useMemo(() => {\n if (longLivedToken && !baseUrl) {\n throw new CapitalOSError({\n message: 'baseUrl is required for long lived tokens',\n code: ErrorCode.unauthorized,\n })\n }\n const tokenData: TokenData | undefined = longLivedToken\n ? ({\n token: longLivedToken,\n tokenType: TokenType.longLived,\n baseUrl: baseUrl!,\n paramKey: TokenParamKey.accessToken,\n paramLocation: TokenParamLocation.hash,\n } as const)\n : undefined\n\n return {\n tokenData,\n isLoading,\n error,\n invalidateToken,\n }\n }, [longLivedToken, isLoading, error, invalidateToken, baseUrl])\n\n return (\n <>\n <CapitalOsAuthenticationContext.Provider value={contextValue}>{children}</CapitalOsAuthenticationContext.Provider>\n {oneTimeToken && !longLivedToken && (\n <TokenExchangeIframe\n oneTimeToken={oneTimeToken}\n onExchangeComplete={onExchangeComplete}\n enableLogging={enableLogging}\n onExchangeError={setError}\n />\n )}\n </>\n )\n}\n\nexport const useCapitalOsAuthContext = () => useContext(CapitalOsAuthenticationContext)\n","import React, { useMemo, useRef } from 'react'\n\nimport { CapitalOSError } from '../error'\nimport { useIframeConnection, useIframeUrl } from '../hooks'\nimport { IframeResizer } from '../iframe-resizer'\nimport { tokenDataFromOneTimeToken } from '../utils'\n\nexport interface TokenExchangeIframeProps {\n oneTimeToken: string\n enableLogging?: boolean | undefined\n onExchangeComplete: (jwtToken: string) => void\n onExchangeError?: (error: Error) => void\n}\n\n/**\n * The component is hidden from the user and is only used to exchange a one-time token for a JWT in the authentication context.\n *\n * The token exchange process works as follows:\n * 1. Component renders a hidden iframe with the one-time token in the URL\n * 2. The iframe loads with the long-lived token as part of its url redirect response and establishes a secure connection with the parent window\n * 3. The iframe passes the long-lived token to the parent via postMessage\n * 4. onExchangeComplete callback is triggered with the new JWT\n *\n * If any errors occur during this process, they are passed to onExchangeError.\n */\nexport function TokenExchangeIframe(props: TokenExchangeIframeProps) {\n const { oneTimeToken, enableLogging, onExchangeComplete, onExchangeError } = props\n\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n const tokenData = useMemo(() => tokenDataFromOneTimeToken(oneTimeToken), [oneTimeToken])\n\n const renderingContext = {\n entryPoint: 'tokenExchange',\n } as const\n\n const url = useIframeUrl({\n tokenData,\n onError: onExchangeError,\n renderingContext,\n })\n\n useIframeConnection({\n iframeRef,\n token: oneTimeToken,\n onError: onExchangeError,\n methods: {\n onLoad: () => {},\n onError: (error) => {\n onExchangeError?.(new CapitalOSError(error))\n },\n tokenExchange: {\n onLongLivedToken: onExchangeComplete,\n },\n },\n })\n\n // Render the hidden iframe.\n return (\n <IframeResizer\n src={url}\n checkOrigin={false}\n style={{ display: 'none' }} // Hidden from view\n log={!!enableLogging}\n ref={iframeRef}\n />\n )\n}\n","/**\n * Base class for all SDK errors\n */\nexport class CapitalOSError extends Error {\n code: ErrorCode\n constructor({ message, code }: { message: string; code: ErrorCode }) {\n super(message)\n this.name = 'CapitalOSError'\n this.code = code\n }\n}\n\nexport const ErrorCode = {\n unauthorized: 'unauthorized',\n invalid_account_status: 'invalid_account_status',\n unsupported_entry_point: 'unsupported_entry_point',\n internal_error: 'internal_error',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/**\n * Represents an error that occurs when an invalid token is encountered.\n */\nexport class InvalidTokenError extends CapitalOSError {\n constructor(message?: string) {\n super({ message: `Invalid token ${message ?? ''}`, code: ErrorCode.unauthorized })\n this.name = 'CapitalOSInvalidTokenError'\n }\n}\n\nexport class TokenRefreshError extends CapitalOSError {\n constructor(originalError?: Error) {\n super({\n message: `Failed to refresh token: ${originalError?.message}`,\n code: ErrorCode.unauthorized,\n })\n this.name = 'CapitalOSTokenRefreshError'\n }\n}\n","import { connectToChild } from 'penpal'\nimport { useEffect, useMemo, useRef } from 'react'\n\nimport { ErrorCode } from './error'\nimport { Account, ThemeColorScheme, CapitalOsRenderingContext, TokenData } from './types'\nimport { buildIframeUrl } from './utils'\n\nconst IFRAME_CONNECTION_TIMEOUT_MILLISECONDS = 10_000\n\n/**\n * An error type providing a reason code and message.\n * Penpal only passes plain objects, so this does not inherit from Error.\n */\nexport type RawErrorDetails = {\n code: ErrorCode\n message: string\n}\n\nexport type IframeConnectionMethods = {\n onLoad: () => void\n onError: (error: RawErrorDetails) => void\n /**\n * Called when the iframe detects that the JWT token has expired.\n * This triggers the token refresh flow, which will obtain a new token\n * and reload the iframe with the fresh token.\n */\n onTokenExpired?: () => void\n createCard?: {\n onDone?: () => void\n onCancel?: () => void\n }\n createDispute?: {\n onDone?: () => void\n onCancel?: () => void\n }\n onboarding?: {\n onDone?: (account: Account) => void\n }\n tokenExchange?: {\n onLongLivedToken?: (jwtToken: string) => void\n }\n makePayment?: {\n onDone?: () => void\n }\n devTools?: {\n onClose?: () => void\n }\n}\n\n/**\n * connects to child iframe and returns whether the iframe is loaded or not.\n * token was added to the list of dependencies to make sure that the connection is re-established when the token changes.\n */\nexport function useIframeConnection({\n iframeRef,\n token,\n onError,\n methods,\n}: {\n iframeRef: React.RefObject<HTMLIFrameElement>\n token: string | undefined\n onError: ((error: Error) => void) | undefined | null\n methods: IframeConnectionMethods\n}) {\n // connect to child iframe\n useEffect(() => {\n if (!iframeRef.current) {\n return\n }\n\n const connection = connectToChild({\n iframe: iframeRef.current,\n childOrigin: '*',\n debug: true,\n timeout: IFRAME_CONNECTION_TIMEOUT_MILLISECONDS,\n methods,\n })\n\n connection.promise.catch((error) => {\n onError?.(error)\n })\n\n return () => {\n connection.destroy()\n }\n }, [token, iframeRef])\n}\n\nexport function useIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData | undefined\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n // We assume that onError and renderingContext do not change over the lifetime of the component.\n // We put it in a ref to avoid causing unnecessary re-renders.\n const onErrorRef = useRef(onError)\n const renderingContextRef = useRef(renderingContext)\n\n return useMemo(() => {\n if (!tokenData) {\n return undefined\n }\n return buildIframeUrl({\n tokenData,\n renderingContext: renderingContextRef.current,\n theme,\n onError: onErrorRef.current,\n })\n // wrapped rendering context in a ref since we do not want to reload the iframe unless the token changes.\n }, [tokenData, theme, onErrorRef, renderingContextRef])\n}\n","{\n \"name\": \"@capitalos/react\",\n \"version\": \"1.0.0-rc.8\",\n \"description\": \"integrate CapitalOS into your react app\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/esm/index.js\",\n \"types\": \"dist/_tsup-dts-rollup.d.ts\",\n \"scripts\": {\n \"build\": \" pnpm lint && tsup src/index.tsx --experimental-dts --minify --format esm,cjs --clean --no-splitting --sourcemap --legacy-output --out-dir dist\",\n \"dev\": \"pnpm build --watch\",\n \"prepublishOnly\": \"pnpm build\",\n \"lint\": \"eslint . --ext .ts,.tsx --fix\",\n \"lint-ci\": \"eslint . --ext .ts,.tsx\"\n },\n \"keywords\": [\n \"capitalos\",\n \"react\"\n ],\n \"homepage\": \"https://docs.capitalos.com/docs/using-react-client-library\",\n \"author\": \"CapitalOS\",\n \"license\": \"MIT\",\n \"files\": [\n \"dist\",\n \"package.json\"\n ],\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.27.12\",\n \"@microsoft/api-extractor\": \"^7.39.5\",\n \"@trivago/prettier-plugin-sort-imports\": \"^4.3.0\",\n \"@types/iframe-resizer\": \"^3.5.13\",\n \"@types/react\": \"18.0.20\",\n \"@typescript-eslint/eslint-plugin\": \"^7.2.0\",\n \"@typescript-eslint/parser\": \"^7.2.0\",\n \"eslint\": \"^8.57.0\",\n \"eslint-config-prettier\": \"^9.1.0\",\n \"eslint-plugin-prettier\": \"^5.1.3\",\n \"eslint-plugin-react\": \"^7.34.0\",\n \"prettier\": \"^3.2.5\",\n \"react\": \"16.8.0\",\n \"tsup\": \"^8.1.0\",\n \"typescript\": \"^5.6.2\"\n },\n \"dependencies\": {\n \"iframe-resizer\": \"^4.3.9\",\n \"penpal\": \"^6.2.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=16.8.0\"\n }\n}\n","import { version as sdkVersion } from '../package.json'\nimport { InvalidTokenError } from './error'\nimport {\n ThemeColorScheme,\n CapitalOsRenderingContext,\n TokenData,\n TokenType,\n TokenParamKey,\n TokenParamLocation,\n} from './types'\n\n/**\n * Encodes the rendering context as base64 and then URI encodes it.\n */\nexport function encodeRenderingContext<T>(renderingContext: NonNullable<T>) {\n const renderingContextJson = JSON.stringify(renderingContext)\n const renderingContextBase64 = btoa(renderingContextJson)\n const renderingContextEncoded = encodeURIComponent(renderingContextBase64)\n\n return renderingContextEncoded\n}\n\nexport function decodeOneTimeToken(token: string) {\n try {\n const urlDecodedToken = decodeURIComponent(token)\n const base64DecodedToken = atob(urlDecodedToken)\n return JSON.parse(base64DecodedToken)\n } catch (error) {\n throw new InvalidTokenError()\n }\n}\n\n/**\n * Safely decodes a URL component, handling potential errors\n */\nexport function safeDecodeURIComponent(str: string): string {\n try {\n return decodeURIComponent(str)\n } catch (e) {\n // If decoding fails, it might not have been encoded, so return original\n return str\n }\n}\n\n/**\n * Builds the iframe url from token data, rendering context, and theme.\n */\nexport function buildIframeUrl({\n tokenData,\n renderingContext,\n theme,\n onError,\n}: {\n tokenData: TokenData\n renderingContext: CapitalOsRenderingContext\n theme?: ThemeColorScheme | undefined\n onError?: ((error: Error) => void) | undefined\n}) {\n try {\n const enrichedRenderingContext = renderingContext\n ? {\n ...renderingContext,\n referer: window.location.href,\n }\n : null\n\n const encodedRenderingContext = enrichedRenderingContext ? encodeRenderingContext(enrichedRenderingContext) : null\n\n const url = new URL(tokenData.baseUrl)\n\n // Always safely decode the token before setting it since search params url encode the token and we do not want to double encode it.\n // in dev, since we're using 2 separate server for client and server, we have a redirect which prevents the double encoding.\n const decodedToken = safeDecodeURIComponent(tokenData.token)\n\n if (tokenData.paramLocation === 'search') {\n url.searchParams.set(tokenData.paramKey, decodedToken)\n } else if (tokenData.paramLocation === 'hash') {\n url.hash = tokenData.paramKey + '=' + encodeURIComponent(decodedToken)\n }\n\n url.searchParams.set('sdkVersion', sdkVersion)\n\n if (encodedRenderingContext) {\n url.searchParams.set('renderingContext', encodedRenderingContext)\n }\n\n if (theme) {\n url.searchParams.set('theme', theme)\n }\n\n const urlString = url.toString()\n return urlString\n } catch (error) {\n // communicate a general error about the token being invalid to the parent component, no matter which internal error we encountered during token parsing.\n onError?.(new InvalidTokenError())\n return undefined\n }\n}\n\nexport function tokenDataFromOneTimeToken(oneTimeToken: string): TokenData {\n const tokenObject = decodeOneTimeToken(oneTimeToken)\n const path = tokenObject.path\n if (!path || typeof path !== 'string') {\n throw new InvalidTokenError()\n }\n\n const tokenData: TokenData = {\n token: oneTimeToken,\n tokenType: TokenType.oneTime,\n baseUrl: path,\n paramKey: TokenParamKey.token,\n paramLocation: TokenParamLocation.search,\n }\n\n return tokenData\n}\n","import {\n IFrameOptions as BrokenIframeOptions,\n IFrameComponent,\n IFrameMessageData,\n IFrameResizedData,\n IFrameScrollData,\n iframeResizer,\n} from 'iframe-resizer'\nimport React, { IframeHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'\n\n// the events were renamed but package maintainers didn't update the types.\ntype IFrameOptions = Omit<\n BrokenIframeOptions,\n 'closedCallback' | 'scrollCallback' | 'resizedCallback' | 'messageCallback' | 'initCallback'\n> & {\n onClosed?(iframeId: string): void\n onInit?(iframe: IFrameComponent): void\n onMessage?(data: IFrameMessageData): void\n onResized?(data: IFrameResizedData): void\n onScroll?(data: IFrameScrollData): boolean\n}\n\ntype IframeResizerProps = IFrameOptions & IframeHTMLAttributes<HTMLIFrameElement>\ntype EnrichedHtmlIframeElement = HTMLIFrameElement & { iFrameResizer: { removeListeners: () => void } }\n\nexport const IframeResizer = forwardRef((props: IframeResizerProps, ref: React.Ref<HTMLIFrameElement>) => {\n const title = props.title || 'iframe'\n const { iframeHTMLAttributes, resizerOptions } = splitProps(props)\n const iframeRef = useRef<HTMLIFrameElement>(null)\n\n useEffect(() => {\n // effects run after render, so the ref is guaranteed to be set (unless the component conditionally renders the iframe, which is not the case)\n const iframe = iframeRef.current as EnrichedHtmlIframeElement\n\n iframeResizer({ ...resizerOptions }, iframe)\n\n return () => iframe.iFrameResizer && iframe.iFrameResizer.removeListeners()\n })\n\n // make the ref provided as a prop point to the same place as the internal iframe ref.\n useImperativeHandle(ref, () => iframeRef.current as HTMLIFrameElement)\n\n return <iframe {...iframeHTMLAttributes} title={title} ref={iframeRef} />\n})\n\nIframeResizer.displayName = 'IframeResizer'\n\nconst resizerOptions = [\n 'autoResize',\n 'bodyBackground',\n 'bodyMargin',\n 'bodyPadding',\n 'checkOrigin',\n 'inPageLinks',\n 'heightCalculationMethod',\n 'interval',\n 'log',\n 'maxHeight',\n 'maxWidth',\n 'minHeight',\n 'minWidth',\n 'resizeFrom',\n 'scrolling',\n 'sizeHeight',\n 'sizeWidth',\n 'warningTimeout',\n 'tolerance',\n 'widthCalculationMethod',\n 'onClosed',\n 'onInit',\n 'onMessage',\n 'onResized',\n 'onScroll',\n]\n\nconst resizerOptionsSet = new Set(resizerOptions)\n\n/**\n * split props into the resizer library options and the native iframe attributes.\n * the code is contains many type assertions because typescript doesn't handle reduce well.\n */\nfunction splitProps(props: IframeResizerProps) {\n const split = (Object.keys(props) as Array<keyof IframeResizerProps>).reduce<{\n resizerOptions: IFrameOptions\n iframeHTMLAttributes: IframeHTMLAttributes<HTMLIFrameElement>\n }>(\n (acc, key) => {\n const value = props[key]\n if (resizerOptionsSet.has(key)) {\n if (value !== undefined) {\n acc.resizerOptions[key as keyof IFrameOptions] = props[key as keyof typeof props]\n }\n } else {\n acc.iframeHTMLAttributes[key as keyof IframeHTMLAttributes<HTMLIFrameElement>] =\n props[key as keyof typeof props]\n }\n return acc\n },\n { resizerOptions: {}, iframeHTMLAttributes: {} },\n )\n\n return split\n}\n","import React, { useMemo } from 'react'\nimport { useState } from 'react'\nimport { CSSProperties } from 'react'\n\nimport { CapitalOS } from './capital-os'\nimport { DevToolsButton } from './components/dev-tools-button'\nimport { EntryPoint } from './external-types'\nimport { CommonProps } from './types'\n\nconst styles: Record<string, CSSProperties> = {\n panel: {\n position: 'fixed',\n bottom: '20px',\n left: '20px',\n zIndex: 50,\n },\n}\n\n// #region Dev Tools\nexport type DevToolsProps = CommonProps\n\n/**\n * Renders the CapitalOS Dev Tools experience.\n * Allows for simulating transactions, etc.\n */\nexport function DevTools(props: DevToolsProps) {\n const entryPoint: EntryPoint = 'devTools'\n const renderingContext = useMemo(() => ({ entryPoint }), [entryPoint])\n\n const [isOpen, setIsOpen] = useState(false)\n\n return (\n <aside aria-label=\"CapitalOS dev tools\">\n {!isOpen && <DevToolsButton onClick={() => setIsOpen(!isOpen)} />}\n {isOpen && (\n <div style={styles['panel']}>\n <CapitalOS\n {...props}\n renderingContext={renderingContext}\n methods={{ devTools: { onClose: () => setIsOpen(false) } }}\n enableLogging={true}\n sizeWidth={true}\n loadingComponent={<DevToolsButton isLoading />}\n />\n </div>\n )}\n </aside>\n )\n}\n","import React, { useState } from 'react'\nimport { CSSProperties } from 'react'\n\nconst styles: Record<string, CSSProperties> = {\n bugButton: {\n position: 'fixed',\n left: '12px',\n bottom: '12px',\n margin: '12px',\n padding: '4px',\n display: 'inline-flex',\n alignItems: 'center',\n borderRadius: '9999px',\n border: '1px solid transparent',\n backgroundColor: '#2563eb',\n color: 'white',\n opacity: 0.4,\n boxShadow: '0 1px 3px 0 rgb(0 0 0 / 0.1)',\n cursor: 'pointer',\n zIndex: 50,\n transition: 'opacity 0.3s ease-in-out',\n },\n bugButtonHover: {\n backgroundColor: '#1d4ed8',\n opacity: 1,\n },\n bugButtonFocus: {\n outline: 'none',\n boxShadow: '0 0 0 2px white, 0 0 0 4px #3b82f6',\n },\n bugIcon: {\n width: '20px',\n height: '20px',\n },\n loadingButton: {\n cursor: 'default',\n opacity: 1,\n animation: 'pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite',\n },\n}\n\nconst BugIcon = () => (\n <svg\n style={styles['bugIcon']}\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth=\"1.5\"\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M12 12.75c1.148 0 2.278.08 3.383.237 1.037.146 1.866.966 1.866 2.013 0 3.728-2.35 6.75-5.25 6.75S6.75 18.728 6.75 15c0-1.046.83-1.867 1.866-2.013A24.204 24.204 0 0 1 12 12.75Zm0 0c2.883 0 5.647.508 8.207 1.44a23.91 23.91 0 0 1-1.152 6.06M12 12.75c-2.883 0-5.647.508-8.208 1.44.125 2.104.52 4.136 1.153 6.06M12 12.75a2.25 2.25 0 0 0 2.248-2.354M12 12.75a2.25 2.25 0 0 1-2.248-2.354M12 8.25c.995 0 1.971-.08 2.922-.236.403-.066.74-.358.795-.762a3.778 3.778 0 0 0-.399-2.25M12 8.25c-.995 0-1.97-.08-2.922-.236-.402-.066-.74-.358-.795-.762a3.734 3.734 0 0 1 .4-2.253M12 8.25a2.25 2.25 0 0 0-2.248 2.146M12 8.25a2.25 2.25 0 0 1 2.248 2.146M8.683 5a6.032 6.032 0 0 1-1.155-1.002c.07-.63.27-1.222.574-1.747m.581 2.749A3.75 3.75 0 0 1 15.318 5m0 0c.427-.283.815-.62 1.155-.999a4.471 4.471 0 0 0-.575-1.752M4.921 6a24.048 24.048 0 0 0-.392 3.314c1.668.546 3.416.914 5.223 1.082M19.08 6c.205 1.08.337 2.187.392 3.314a23.882 23.882 0 0 1-5.223 1.082\"\n />\n </svg>\n)\n\ninterface DevToolsButtonProps {\n onClick?: () => void\n isLoading?: boolean\n}\n\nexport function DevToolsButton({ onClick, isLoading = false }: DevToolsButtonProps) {\n const [isHovered, setIsHovered] = useState(false)\n const [isFocused, setIsFocused] = useState(false)\n\n const buttonStyle = {\n ...styles['bugButton'],\n ...(isLoading && styles['loadingButton']),\n ...(!isLoading && isHovered && styles['bugButtonHover']),\n ...(!isLoading && isFocused && styles['bugButtonFocus']),\n }\n\n if (isLoading) {\n return (\n <div style={buttonStyle}>\n <style>\n {`\n @keyframes pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.4;\n }\n }\n `}\n </style>\n <BugIcon />\n </div>\n )\n }\n\n return (\n <button\n id=\"dev-tools-button\"\n onClick={onClick}\n type=\"button\"\n style={buttonStyle}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n >\n <BugIcon />\n </button>\n )\n}\n"],"mappings":"2xCAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,oBAAAE,GAAA,mBAAAC,GAAA,QAAAC,GAAA,eAAAC,GAAA,oCAAAC,GAAA,gBAAAC,GAAA,aAAAC,GAAA,aAAAC,GAAA,uBAAAC,GAAA,sBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,gBAAAC,GAAA,eAAAC,KAAA,eAAAC,GAAAhB,IAEA,IAAAiB,EAA+B,oBCF/B,IAAAC,EAAyE,oBCEzE,IAAAC,EAA4F,oBCF5F,IAAAC,EAAuC,oBCGhC,IAAMC,EAAN,cAA6B,KAAM,CAExC,YAAY,CAAE,QAAAC,EAAS,KAAAC,CAAK,E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AAK,CAC/C,EAEA,OAAO,EAAAhB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcI,GAAd,CAAqB,iBAAkBR,GAAkB,CACnE,CAgBO,SAASkB,GAA2C1B,EAKpC,CALoC,IAAAC,EAAAD,EACzD,QAAAG,EACA,WAAYwB,EACZ,UAAWC,CAlPb,EA+O2D3B,EAItDI,EAAAC,EAJsDL,EAItD,CAHH,SACA,aACA,cAMA,IAAMM,EAAyB,aACzBC,KAAmB,WACvB,KAAO,CAAE,WAAAD,EAAY,qBAAAoB,EAAsB,oBAAAC,CAAoB,GAC/D,CAACrB,EAAYoB,EAAsBC,CAAmB,CACxD,EAEA,OAAO,EAAAnB,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,WAAY,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC9G,CAcO,SAAS0B,GAAY7B,EAA8C,CAA9C,IAAAC,EAAAD,EAAE,QAAAG,CA7Q9B,EA6Q4BF,EAAaI,EAAAC,EAAbL,EAAa,CAAX,WAC5B,IAAMM,EAAyB,cACzBC,KAAmB,WAAQ,KAAO,CAAE,WAAAD,CAAW,GAAI,CAACA,CAAU,CAAC,EAErE,OAAO,EAAAE,QAAA,cAACC,EAAAC,EAAAC,EAAA,GAAcP,GAAd,CAA2B,iBAAkBG,EAAkB,QAAS,CAAE,YAAa,CAAE,OAAAL,CAAO,CAAE,GAAG,CAC/G","names":["src_exports","__export","AccountActions","AccountDetails","App","BillPayApp","CapitalOsAuthenticationProvider","CardDetails","CardsApp","DevTools","DisputeTransaction","InsightsDashboard","InsightsWidget","IssueCard","MakePayment","Onboarding","__toCommonJS","import_react","import_react","import_react","import_react","CapitalOSError","message","code","ErrorCode","InvalidTokenError","import_penpal","import_react","version","encodeRenderingContext","renderingContext","renderingContextJson","renderingContextBase64","decodeOneTimeToken","token","urlDecodedToken","base64DecodedToken","error","InvalidTokenError","safeDecodeURIComponent","str","e","buildIframeUrl","tokenData","theme","onError","enrichedRenderingContext","__spreadProps","__spreadValues","encodedRenderingContext","url","decodedToken","version","tokenDataFromOneTimeToken","oneTimeToken","path","IFRAME_CONNECTION_TIMEOUT_MILLISECONDS","useIframeConnection","iframeRef","token","onError","methods","connection","error","useIframeUrl","tokenData","renderingContext","theme","onErrorRef","renderingContextRef","buildIframeUrl","import_iframe_resizer","import_react","IframeResizer","props","ref","title","iframeHTMLAttributes","resizerOptions","splitProps","iframeRef","iframe","__spreadValues","React","__spreadProps","resizerOptionsSet","acc","key","value","TokenExchangeIframe","props","oneTimeToken","enableLogging","onExchangeComplete","onExchangeError","iframeRef","tokenData","tokenDataFromOneTimeToken","url","useIframeUrl","useIframeConnection","error","CapitalOSError","React","IframeResizer","CapitalOsAuthenticationContext","CapitalOsAuthenticationProvider","getToken","enableLogging","children","oneTimeToken","setOneTimeToken","baseUrl","setBaseUrl","longLivedToken","setLongLivedToken","isLoading","setIsLoading","error","setError","refreshOneTimeToken","__async","newToken","tokenObject","decodeOneTimeToken","url","invalidateToken","onExchangeComplete","jwtToken","contextValue","CapitalOSError","ErrorCode","React","TokenExchangeIframe","useCapitalOsAuthContext","CapitalOS","props","tokenProp","className","enableLogging","onError","LoadingComponent","renderingContext","methods","theme","sizeWidth","contextTokenData","error","invalidateToken","useCapitalOsAuthContext","isLoaded","setIsLoaded","iframeRef","useErrorHandling","tokenData","tokenDataFromOneTimeToken","handleTokenExpired","CapitalOSError","ErrorCode","url","useIframeUrl","useIframeConnection","__spreadValues","err","React","shouldAddPaddingBottom","IframeResizer","data","newHeight","errorFired","import_react","import_react","styles","BugIcon","React","DevToolsButton","onClick","isLoading","isHovered","setIsHovered","isFocused","setIsFocused","buttonStyle","__spreadValues","styles","DevTools","props","entryPoint","renderingContext","isOpen","setIsOpen","React","DevToolsButton","CapitalOS","__spreadProps","__spreadValues","CardsApp","props","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","App","IssueCard","_a","_b","cardholder","onDone","onCancel","restOfProps","__objRest","entryPoint","renderingContext","React","CapitalOS","__spreadProps","__spreadValues","DisputeTransaction","transactionId","BillPayApp","props","CardDetails","AccountDetails","AccountActions","InsightsDashboard","InsightsWidget","widget","hideTitle","height","width","Onboarding","onboardingEntryPoint","onboardingExitPoint","MakePayment"]}
@@ -19,4 +19,5 @@ export { AccountActionsProps } from '../_tsup-dts-rollup';
19
19
  export { InsightsDashboardProps } from '../_tsup-dts-rollup';
20
20
  export { InsightsWidgetProps } from '../_tsup-dts-rollup';
21
21
  export { MakePaymentProps } from '../_tsup-dts-rollup';
22
+ export { DevTools_alias_1 as DevTools } from '../_tsup-dts-rollup';
22
23
  export { CapitalOsAuthenticationProvider } from '../_tsup-dts-rollup';
@@ -19,4 +19,5 @@ export { AccountActionsProps } from '../_tsup-dts-rollup';
19
19
  export { InsightsDashboardProps } from '../_tsup-dts-rollup';
20
20
  export { InsightsWidgetProps } from '../_tsup-dts-rollup';
21
21
  export { MakePaymentProps } from '../_tsup-dts-rollup';
22
+ export { DevTools_alias_1 as DevTools } from '../_tsup-dts-rollup';
22
23
  export { CapitalOsAuthenticationProvider } from '../_tsup-dts-rollup';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capitalos/react",
3
- "version": "1.0.0-rc.6",
3
+ "version": "1.0.0-rc.8",
4
4
  "description": "integrate CapitalOS into your react app",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/esm/index.js",