@tryfinch/react-connect
Version:
Finch SDK for embedding Finch Connect in API React Single Page Applications (SPA)
164 lines (159 loc) • 7.66 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');
const POST_MESSAGE_NAME = 'finch-auth-message-v2';
const BASE_FINCH_CONNECT_URI = 'https://connect.tryfinch.com';
const DEFAULT_FINCH_REDIRECT_URI = 'https://tryfinch.com';
const FINCH_CONNECT_IFRAME_ID = 'finch-connect-iframe';
const constructAuthUrl = (connectOptions) => {
const { state, apiConfig } = connectOptions;
const CONNECT_URL = (apiConfig === null || apiConfig === void 0 ? void 0 : apiConfig.connectUrl) || BASE_FINCH_CONNECT_URI;
const REDIRECT_URL = (apiConfig === null || apiConfig === void 0 ? void 0 : apiConfig.redirectUrl) || DEFAULT_FINCH_REDIRECT_URI;
const authUrl = new URL(`${CONNECT_URL}/authorize`);
if ('sessionId' in connectOptions) {
const { sessionId, products } = connectOptions;
authUrl.searchParams.append('session', sessionId);
if (products)
authUrl.searchParams.append('products', products.join(' '));
}
else {
const { clientId, payrollProvider, category, products, manual, sandbox, clientName, connectionId, } = connectOptions;
if (clientId)
authUrl.searchParams.append('client_id', clientId);
if (payrollProvider)
authUrl.searchParams.append('payroll_provider', payrollProvider);
if (category)
authUrl.searchParams.append('category', category);
if (clientName)
authUrl.searchParams.append('client_name', clientName);
if (connectionId)
authUrl.searchParams.append('connection_id', connectionId);
authUrl.searchParams.append('products', (products !== null && products !== void 0 ? products : []).join(' '));
if (manual)
authUrl.searchParams.append('manual', String(manual));
if (sandbox)
authUrl.searchParams.append('sandbox', String(sandbox));
}
authUrl.searchParams.append('app_type', 'spa');
authUrl.searchParams.append('redirect_uri', REDIRECT_URL);
/** The host URL of the SDK. This is used to store the referrer for postMessage purposes */
authUrl.searchParams.append('sdk_host_url', window.location.origin);
authUrl.searchParams.append('mode', 'employer');
if (state)
authUrl.searchParams.append('state', state);
// replace with actual SDK version by rollup
authUrl.searchParams.append('sdk_version', 'react-3.15.0');
return authUrl.href;
};
const noop = () => {
// intentionally empty
};
const BASE_DEFAULTS = {
onSuccess: noop,
onError: noop,
onClose: noop,
state: null,
zIndex: 999,
};
const DEFAULT_OPTIONS_WITH_CLIENT_ID = Object.assign(Object.assign({}, BASE_DEFAULTS), { clientId: '', category: null, manual: false, payrollProvider: null, products: [], clientName: undefined, sandbox: false });
const DEFAULT_OPTIONS_WITH_SESSION_ID = Object.assign(Object.assign({}, BASE_DEFAULTS), { sessionId: '' });
let isUseFinchConnectInitialized = false;
const useFinchConnect = (options) => {
if (!('sessionId' in options) && !('clientId' in options)) {
throw new Error('must specify either sessionId or clientId in options for useFinchConnect');
}
if ('sessionId' in options && 'clientId' in options) {
throw new Error('cannot specify both sessionId and clientId in options for useFinchConnect');
}
const isHookMounted = react.useRef(false);
react.useEffect(() => {
if (!isHookMounted.current) {
if (isUseFinchConnectInitialized) {
console.error('One useFinchConnect hook has already been registered. Please ensure to only call useFinchConnect once to avoid your event callbacks getting called more than once. You can pass in override options to the open function if you so require.');
}
else {
isUseFinchConnectInitialized = true;
}
isHookMounted.current = true;
}
}, []);
const combinedOptions = 'sessionId' in options
? Object.assign(Object.assign({}, DEFAULT_OPTIONS_WITH_SESSION_ID), options) : Object.assign(Object.assign({}, DEFAULT_OPTIONS_WITH_CLIENT_ID), options);
const open = (overrides) => {
const openOptions = Object.assign(Object.assign({}, combinedOptions), overrides);
if (!document.getElementById(FINCH_CONNECT_IFRAME_ID)) {
const iframe = document.createElement('iframe');
iframe.src = constructAuthUrl(openOptions);
iframe.frameBorder = '0';
iframe.id = FINCH_CONNECT_IFRAME_ID;
iframe.style.position = 'fixed';
iframe.style.zIndex = openOptions.zIndex.toString();
iframe.style.height = '100%';
iframe.style.width = '100%';
iframe.style.top = '0';
iframe.style.backgroundColor = 'none transparent';
iframe.style.border = 'none';
iframe.allow = 'clipboard-write; clipboard-read';
document.body.prepend(iframe);
document.body.style.overflow = 'hidden';
}
};
const close = () => {
var _a;
const frameToRemove = document.getElementById(FINCH_CONNECT_IFRAME_ID);
if (frameToRemove) {
(_a = frameToRemove.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(frameToRemove);
document.body.style.overflow = 'inherit';
}
};
react.useEffect(() => {
function handleFinchAuth(event) {
var _a, _b, _c, _d;
const CONNECT_URL = ((_a = combinedOptions.apiConfig) === null || _a === void 0 ? void 0 : _a.connectUrl) || BASE_FINCH_CONNECT_URI;
if (!event.data)
return;
if (event.data.name !== POST_MESSAGE_NAME)
return;
if (!event.origin.startsWith(CONNECT_URL))
return;
if (event.data.kind !== 'error')
close();
switch (event.data.kind) {
case 'closed':
combinedOptions.onClose();
break;
case 'error':
if ((_b = event.data.error) === null || _b === void 0 ? void 0 : _b.shouldClose)
close();
combinedOptions.onError({
errorMessage: (_c = event.data.error) === null || _c === void 0 ? void 0 : _c.message,
errorType: (_d = event.data.error) === null || _d === void 0 ? void 0 : _d.type,
});
break;
case 'success':
combinedOptions.onSuccess({
code: event.data.code,
state: event.data.state,
idpRedirectUri: event.data.idpRedirectUri,
});
break;
default: {
// This case should never happen, if it does it should be reported to us
combinedOptions.onError({
errorMessage: `Report to developers@tryfinch.com: unable to handle window.postMessage for: ${JSON.stringify(event.data)}`,
});
}
}
}
window.addEventListener('message', handleFinchAuth);
return () => {
window.removeEventListener('message', handleFinchAuth);
isUseFinchConnectInitialized = false;
};
}, [combinedOptions.onClose, combinedOptions.onError, combinedOptions.onSuccess]);
return {
open,
};
};
exports.useFinchConnect = useFinchConnect;
//# sourceMappingURL=index.js.map
;