@templafy/delivery-connector-library 1.0.0-PullRequest53004.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { AuthenticateCompleteMessage, CanUploadMessage } from "./utils/MessagePassings";
2
+ declare global {
3
+ interface External {
4
+ OAuth2Callback: (state: string) => void;
5
+ }
6
+ interface Window {
7
+ chrome?: {
8
+ webview?: {
9
+ hostObjects: {
10
+ sync: {
11
+ bridge: {
12
+ ExecuteMethod: (methodName: "OAuth2Callback", invocationId: string, args: [string]) => Promise<void>;
13
+ };
14
+ };
15
+ };
16
+ };
17
+ };
18
+ }
19
+ }
20
+ export declare namespace Templafy {
21
+ /**
22
+ * @return A promise that will resolve with the documentURL once the user clicks the `save` button.
23
+ * */
24
+ const getDocumentUrl: (timeoutMs?: number) => Promise<string>;
25
+ /**
26
+ * Initializes the connector. This call must be completed before any of the other API's can be used.
27
+ * */
28
+ const initialize: () => Promise<void>;
29
+ /**
30
+ * @param params {ShouldAuthenticateParams}
31
+ * */
32
+ const sendShouldAuthenticate: (params: ShouldAuthenticateParams) => void;
33
+ /**
34
+ * @param {number} timeoutMs timeout for waiting for authenticationResult. Defaults to 200000 ms.
35
+ * */
36
+ const getAuthenticationState: <T>(timeoutMs?: number) => Promise<{
37
+ authenticationState: T;
38
+ authenticationSuccessful: boolean;
39
+ }>;
40
+ /**
41
+ * Sets that the next action is to show the content of the Delivery Controller
42
+ * */
43
+ const sendRequireInput: () => void;
44
+ /**
45
+ * Sets that the next action is to show the content of the Delivery Controller, but allowing the user to immediately proceed
46
+ * */
47
+ const sendRequestOptionalInput: () => void;
48
+ /**
49
+ * Shows an error to the user
50
+ * */
51
+ const sendError: (message: string) => void;
52
+ /**
53
+ * Reports to Templafy that the authentication was completed. This call can only be used from the authentication pop-up.
54
+ * Allows for arbitrary data to be sent from the pop-up to the window hosted inside the Templafy page.
55
+ * @param {Omit<AuthenticateCompleteMessage, "type">} message
56
+ * */
57
+ const sendAuthenticationComplete: (message: Omit<AuthenticateCompleteMessage, "type">) => Promise<void>;
58
+ /**
59
+ * Clears the next action. This implicitly disables the button.
60
+ * */
61
+ const sendClearButton: () => void;
62
+ /**
63
+ * Reports to Templafy that the upload of a document has completed.
64
+ * @param {string} documentLocation the location that is to be opened by templafy. Should be a URL that points to the uploaded document.
65
+ * */
66
+ const sendUploadComplete: (documentLocation: string) => void;
67
+ /**
68
+ * Reports to Templafy that the page hosted in the iframe is ready to receive the documentURL.
69
+ * This is meant for waiting for user input.
70
+ * @param {Omit<CanUploadMessage, "type">} canUploadMessage
71
+ * */
72
+ const sendCanUpload: (canUploadMessage?: Omit<CanUploadMessage, "type">) => void;
73
+ }
74
+ interface ShouldAuthenticateParams {
75
+ /**
76
+ * Whether or not Templafy should show a pop-up to authenticate the user.
77
+ * */
78
+ shouldAuthenticate: boolean;
79
+ /**
80
+ * The URL for the popup that is to be opened.
81
+ * */
82
+ authenticationUrl: string;
83
+ }
84
+ export {};
package/index.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Templafy = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var Host_1 = require("./utils/Host");
6
+ var defaultTimeoutMs = 200000;
7
+ var Templafy;
8
+ (function (Templafy) {
9
+ var _this = this;
10
+ /**
11
+ * @return A promise that will resolve with the documentURL once the user clicks the `save` button.
12
+ * */
13
+ Templafy.getDocumentUrl = function (timeoutMs) {
14
+ if (timeoutMs === void 0) { timeoutMs = defaultTimeoutMs; }
15
+ return tslib_1.__awaiter(_this, void 0, void 0, function () {
16
+ var documentUrl;
17
+ return tslib_1.__generator(this, function (_a) {
18
+ switch (_a.label) {
19
+ case 0: return [4 /*yield*/, Host_1.waitForPostMessage("deliverDocument", timeoutMs)];
20
+ case 1:
21
+ documentUrl = (_a.sent()).documentUrl;
22
+ return [2 /*return*/, documentUrl];
23
+ }
24
+ });
25
+ });
26
+ };
27
+ /**
28
+ * Initializes the connector. This call must be completed before any of the other API's can be used.
29
+ * */
30
+ Templafy.initialize = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
31
+ return tslib_1.__generator(this, function (_a) {
32
+ switch (_a.label) {
33
+ case 0: return [4 /*yield*/, Host_1.initializeHost()];
34
+ case 1:
35
+ _a.sent();
36
+ return [2 /*return*/];
37
+ }
38
+ });
39
+ }); };
40
+ /**
41
+ * @param params {ShouldAuthenticateParams}
42
+ * */
43
+ Templafy.sendShouldAuthenticate = function (params) {
44
+ Host_1.sendPostMessageToParent(tslib_1.__assign({ type: "shouldAuthenticate" }, params));
45
+ };
46
+ /**
47
+ * @param {number} timeoutMs timeout for waiting for authenticationResult. Defaults to 200000 ms.
48
+ * */
49
+ Templafy.getAuthenticationState = function (timeoutMs) {
50
+ if (timeoutMs === void 0) { timeoutMs = defaultTimeoutMs; }
51
+ return tslib_1.__awaiter(_this, void 0, void 0, function () {
52
+ var _a, state, authenticationSuccessful;
53
+ return tslib_1.__generator(this, function (_b) {
54
+ switch (_b.label) {
55
+ case 0: return [4 /*yield*/, Host_1.waitForPostMessage("authenticateComplete", timeoutMs)];
56
+ case 1:
57
+ _a = _b.sent(), state = _a.state, authenticationSuccessful = _a.authenticationSuccessful;
58
+ return [2 /*return*/, { authenticationState: state, authenticationSuccessful: authenticationSuccessful }];
59
+ }
60
+ });
61
+ });
62
+ };
63
+ /**
64
+ * Sets that the next action is to show the content of the Delivery Controller
65
+ * */
66
+ Templafy.sendRequireInput = function () {
67
+ Host_1.sendPostMessageToParent({ type: "requireInput" });
68
+ };
69
+ /**
70
+ * Sets that the next action is to show the content of the Delivery Controller, but allowing the user to immediately proceed
71
+ * */
72
+ Templafy.sendRequestOptionalInput = function () {
73
+ Host_1.sendPostMessageToParent({ type: "requestOptionalInput" });
74
+ };
75
+ /**
76
+ * Shows an error to the user
77
+ * */
78
+ Templafy.sendError = function (message) {
79
+ Host_1.sendPostMessageToParent({ type: "error", message: message });
80
+ };
81
+ /**
82
+ * Reports to Templafy that the authentication was completed. This call can only be used from the authentication pop-up.
83
+ * Allows for arbitrary data to be sent from the pop-up to the window hosted inside the Templafy page.
84
+ * @param {Omit<AuthenticateCompleteMessage, "type">} message
85
+ * */
86
+ Templafy.sendAuthenticationComplete = function (message) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
87
+ var bridgeClientId;
88
+ var _a;
89
+ return tslib_1.__generator(this, function (_b) {
90
+ switch (_b.label) {
91
+ case 0:
92
+ if (!((_a = window.chrome) === null || _a === void 0 ? void 0 : _a.webview)) return [3 /*break*/, 1];
93
+ bridgeClientId = "client_v2_" + Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
94
+ window.chrome.webview.hostObjects.sync.bridge.ExecuteMethod("OAuth2Callback", bridgeClientId, [JSON.stringify(message)]);
95
+ return [3 /*break*/, 4];
96
+ case 1:
97
+ if (!("OAuth2Callback" in window.external)) return [3 /*break*/, 2];
98
+ window.external.OAuth2Callback(JSON.stringify(message));
99
+ return [3 /*break*/, 4];
100
+ case 2: return [4 /*yield*/, Host_1.initializeHost()];
101
+ case 3:
102
+ _b.sent();
103
+ Host_1.sendPostMessageFunctionOpener(tslib_1.__assign({ type: "authenticateComplete" }, message));
104
+ _b.label = 4;
105
+ case 4: return [2 /*return*/];
106
+ }
107
+ });
108
+ }); };
109
+ /**
110
+ * Clears the next action. This implicitly disables the button.
111
+ * */
112
+ Templafy.sendClearButton = function () {
113
+ Host_1.sendPostMessageToParent({ type: "clearNext" });
114
+ };
115
+ /**
116
+ * Reports to Templafy that the upload of a document has completed.
117
+ * @param {string} documentLocation the location that is to be opened by templafy. Should be a URL that points to the uploaded document.
118
+ * */
119
+ Templafy.sendUploadComplete = function (documentLocation) {
120
+ Host_1.sendPostMessageToParent({ type: "doneUploading", documentLocation: documentLocation });
121
+ };
122
+ /**
123
+ * Reports to Templafy that the page hosted in the iframe is ready to receive the documentURL.
124
+ * This is meant for waiting for user input.
125
+ * @param {Omit<CanUploadMessage, "type">} canUploadMessage
126
+ * */
127
+ Templafy.sendCanUpload = function (canUploadMessage) {
128
+ if (canUploadMessage === void 0) { canUploadMessage = {}; }
129
+ Host_1.sendPostMessageToParent(tslib_1.__assign(tslib_1.__assign({}, canUploadMessage), { type: "canUpload" }));
130
+ };
131
+ })(Templafy = exports.Templafy || (exports.Templafy = {}));
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@templafy/delivery-connector-library",
3
+ "version": "1.0.0-PullRequest53004.70",
4
+ "description": "Allows external vendors to create custom delivery options for documents created within Templafy. This allows Templafy users to authenticate with, choose a save location in, and save created documents directly to an external system.",
5
+ "homepage": "https://www.templafy.com/",
6
+ "bugs": "https://github.com/templafy/DeliveryConnectorLibrary/issues",
7
+ "repository": "github:templafy/DeliveryConnectorLibrary",
8
+ "license": "MIT",
9
+ "main": "index.js",
10
+ "scripts": {
11
+ "build": "tsc && cp package.json ./build/package.json || copy package.json build\\package.json",
12
+ "start-react-example": "cd ./examples/react && yarn && yarn start",
13
+ "start-typescript-example": "cd ./examples/typescript && yarn && yarn start",
14
+ "run-react-example": "yarn build && yarn run start-react-example",
15
+ "run-typescript-example": "yarn build && yarn run start-typescript-example"
16
+ },
17
+ "types": "index.d.ts",
18
+ "files": [
19
+ "."
20
+ ],
21
+ "peerDependencies": {
22
+ "react": "^16.9.0"
23
+ },
24
+ "devDependencies": {
25
+ "@testing-library/jest-dom": "4.1.0",
26
+ "@testing-library/react": "9.2.0",
27
+ "@types/jest": "24.0.12",
28
+ "@types/react": "16.9.0",
29
+ "cross-env": "6.0.3",
30
+ "husky": "4.3.8",
31
+ "jest-junit-reporter": "1.1.0",
32
+ "react": "16.12.0",
33
+ "sass": "1.25.0",
34
+ "ts-node": "8.1.0",
35
+ "tslib": "1.9.3",
36
+ "typescript": "3.9.7"
37
+ },
38
+ "browserslist": [
39
+ ">0.2%",
40
+ "not dead",
41
+ "not ie <= 11",
42
+ "not op_mini all"
43
+ ],
44
+ "engines": {
45
+ "node": ">=10.12.0"
46
+ }
47
+ }
package/react.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Initializes the connector. This call must be completed before any of the other API's can be used.
3
+ * @return {UseInitializeResult<TAuthState, TContentType>}
4
+ * */
5
+ export declare const useInitialize: <TAuthState, TContentType = {}>() => UseInitializeResult<TAuthState, TContentType>;
6
+ /**
7
+ *
8
+ * The user will be navigated to the URL provided.
9
+ * @return {string | null} documentLink
10
+ * */
11
+ export declare const useDocumentUrl: () => {
12
+ documentUrl: string | null;
13
+ };
14
+ /**
15
+ * Reports to Templafy that the authentication was completed. This call can only be used from the authentication pop-up.
16
+ * Allows for arbitrary data to be sent from the pop-up to the window hosted inside the Templafy page.
17
+ * @param {Omit<AuthenticateCompleteMessage, "type">} message
18
+ * */
19
+ export declare const sendAuthenticationComplete: (message: Pick<import("./utils/MessagePassings").AuthenticateCompleteMessage, "state" | "authenticationSuccessful">) => Promise<void>;
20
+ interface UseInitializeResult<TAuthState, TContentType> {
21
+ /**
22
+ * Whether or not the initialization of the library is complete.
23
+ * */
24
+ isInitialized: boolean;
25
+ /**
26
+ * The authentication-state set by the authentication pop-up.
27
+ * */
28
+ authenticationState: AuthenticationState<TAuthState> | null;
29
+ /**
30
+ * The content sent by the app connector.
31
+ */
32
+ content: TContentType | null;
33
+ }
34
+ interface AuthenticationState<TAuthState> {
35
+ /**
36
+ * State passed by the authentication popup
37
+ * */
38
+ authenticationState: TAuthState;
39
+ /**
40
+ * Whether the last authentication attempt reported success.
41
+ * */
42
+ authenticationSuccessful: boolean;
43
+ }
44
+ export {};
package/react.js ADDED
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendAuthenticationComplete = exports.useDocumentUrl = exports.useInitialize = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var Host_1 = require("./utils/Host");
6
+ var react_1 = require("react");
7
+ var MessageHandlerHook_1 = require("./utils/MessageHandlerHook");
8
+ var index_1 = require("./index");
9
+ function initialize(setIsInitialized) {
10
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
11
+ var message;
12
+ return tslib_1.__generator(this, function (_a) {
13
+ switch (_a.label) {
14
+ case 0: return [4 /*yield*/, Host_1.initializeHost()];
15
+ case 1:
16
+ message = _a.sent();
17
+ setIsInitialized(true);
18
+ return [2 /*return*/, message];
19
+ }
20
+ });
21
+ });
22
+ }
23
+ /**
24
+ * Initializes the connector. This call must be completed before any of the other API's can be used.
25
+ * @return {UseInitializeResult<TAuthState, TContentType>}
26
+ * */
27
+ exports.useInitialize = function () {
28
+ var _a = tslib_1.__read(react_1.useState(false), 2), isInitialized = _a[0], setIsInitialized = _a[1];
29
+ var _b = tslib_1.__read(react_1.useState(null), 2), authenticationState = _b[0], setAuthenticationState = _b[1];
30
+ var _c = tslib_1.__read(react_1.useState(null), 2), content = _c[0], setContent = _c[1];
31
+ react_1.useEffect(function () {
32
+ var handleInitialize = function () { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
33
+ var message;
34
+ return tslib_1.__generator(this, function (_a) {
35
+ switch (_a.label) {
36
+ case 0: return [4 /*yield*/, initialize(setIsInitialized)];
37
+ case 1:
38
+ message = _a.sent();
39
+ if (message.type === "acknowledge" && message.content) {
40
+ setContent(message.content);
41
+ }
42
+ return [2 /*return*/];
43
+ }
44
+ });
45
+ }); };
46
+ handleInitialize();
47
+ }, []);
48
+ MessageHandlerHook_1.useHandleMessages(function (_a) {
49
+ var data = _a.data;
50
+ if (data.type !== "authenticateComplete") {
51
+ return;
52
+ }
53
+ setAuthenticationState({
54
+ authenticationState: data.state,
55
+ authenticationSuccessful: data.authenticationSuccessful
56
+ });
57
+ }, [setAuthenticationState]);
58
+ return { authenticationState: authenticationState, isInitialized: isInitialized, content: content };
59
+ };
60
+ /**
61
+ *
62
+ * The user will be navigated to the URL provided.
63
+ * @return {string | null} documentLink
64
+ * */
65
+ exports.useDocumentUrl = function () {
66
+ var _a = tslib_1.__read(react_1.useState(null), 2), documentUrl = _a[0], setDocumentUrl = _a[1];
67
+ MessageHandlerHook_1.useHandleMessages(function (ev) {
68
+ if (ev.data.type === "deliverDocument") {
69
+ setDocumentUrl(ev.data.documentUrl);
70
+ }
71
+ });
72
+ return { documentUrl: documentUrl };
73
+ };
74
+ /**
75
+ * Reports to Templafy that the authentication was completed. This call can only be used from the authentication pop-up.
76
+ * Allows for arbitrary data to be sent from the pop-up to the window hosted inside the Templafy page.
77
+ * @param {Omit<AuthenticateCompleteMessage, "type">} message
78
+ * */
79
+ exports.sendAuthenticationComplete = index_1.Templafy.sendAuthenticationComplete;
@@ -0,0 +1,4 @@
1
+ export declare const getValidOriginRegExp: () => RegExp;
2
+ export declare const setAllowedOrigins: (origins: string[]) => void;
3
+ export declare const windowMap: Map<Window, string>;
4
+ export declare function updateRelationship(source: Window | MessagePort | ServiceWorker | null, origin: string): void;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.updateRelationship = exports.windowMap = exports.setAllowedOrigins = exports.getValidOriginRegExp = void 0;
4
+ var OriginValidation_1 = require("./OriginValidation");
5
+ exports.getValidOriginRegExp = function () { return validOriginRegExp; };
6
+ exports.setAllowedOrigins = function (origins) {
7
+ validOriginRegExp = OriginValidation_1.generateRegExpFromUrls(origins);
8
+ };
9
+ var defaultAllowedOrigins = [
10
+ "https://*.templafy.com",
11
+ "https://*.hive.templafy.com"
12
+ ];
13
+ var validOriginRegExp = OriginValidation_1.generateRegExpFromUrls(defaultAllowedOrigins);
14
+ exports.windowMap = new Map();
15
+ exports.windowMap.set(window, window.location.origin);
16
+ function updateRelationship(source, origin) {
17
+ exports.windowMap.set(source, origin);
18
+ }
19
+ exports.updateRelationship = updateRelationship;
@@ -0,0 +1,4 @@
1
+ export declare const sendPostMessageToParent: (message: import("./MessagePassings").PostMessageMessage) => void;
2
+ export declare const sendPostMessageFunctionOpener: (message: import("./MessagePassings").PostMessageMessage) => void;
3
+ export declare function initializeHost(): Promise<import("./MessagePassings").PostMessageMessage>;
4
+ export declare const waitForPostMessage: <T extends import("./MessagePassings").PostMessageMessage>(type: "error" | "acknowledge" | "authenticateComplete" | "canUpload" | "clearNext" | "doneUploading" | "deliverDocument" | "initialize" | "requestOptionalInput" | "requireInput" | "shouldAuthenticate", timeoutMs: number) => Promise<T>;
package/utils/Host.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.waitForPostMessage = exports.initializeHost = exports.sendPostMessageFunctionOpener = exports.sendPostMessageToParent = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var MessagePassings_1 = require("./MessagePassings");
6
+ exports.sendPostMessageToParent = MessagePassings_1.getSendPostMessageFunction(window.parent);
7
+ exports.sendPostMessageFunctionOpener = MessagePassings_1.getSendPostMessageFunction(window.opener);
8
+ var wildcardSendPostMessageFunctionOpener = MessagePassings_1.getSendPostMessageFunction(window.opener, function () { return "*"; });
9
+ var wildcardSendPostMessageFunctionParent = MessagePassings_1.getSendPostMessageFunction(window.parent, function () { return "*"; });
10
+ function initializeHost() {
11
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
12
+ return tslib_1.__generator(this, function (_a) {
13
+ switch (_a.label) {
14
+ case 0:
15
+ wildcardSendPostMessageFunctionOpener({ type: "initialize" });
16
+ wildcardSendPostMessageFunctionParent({ type: "initialize" });
17
+ return [4 /*yield*/, exports.waitForPostMessage("acknowledge", 200000)];
18
+ case 1: return [2 /*return*/, _a.sent()];
19
+ }
20
+ });
21
+ });
22
+ }
23
+ exports.initializeHost = initializeHost;
24
+ exports.waitForPostMessage = MessagePassings_1.getPostMessageAwaiter();
@@ -0,0 +1,2 @@
1
+ import { PostMessageHandler, PostMessageMessage } from "./MessagePassings";
2
+ export declare const useHandleMessages: <T extends PostMessageMessage>(messageHandler: PostMessageHandler<T>, additionalDependencies?: unknown[]) => void;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useHandleMessages = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var react_1 = require("react");
6
+ var MessagePassings_1 = require("./MessagePassings");
7
+ exports.useHandleMessages = function (messageHandler, additionalDependencies) {
8
+ if (additionalDependencies === void 0) { additionalDependencies = []; }
9
+ react_1.useEffect(function () {
10
+ var originFilteredMessageHandler = MessagePassings_1.getOriginFilteredMessageHandler(messageHandler);
11
+ window.addEventListener("message", originFilteredMessageHandler);
12
+ return function () {
13
+ window.removeEventListener("message", originFilteredMessageHandler);
14
+ };
15
+ }, tslib_1.__spread([messageHandler], additionalDependencies));
16
+ };
@@ -0,0 +1,54 @@
1
+ export declare type PostMessageHandler<T extends PostMessageMessage> = (ev: TemplafyMessageEvent<T>) => void;
2
+ export interface AcknowledgeMessage {
3
+ type: "acknowledge";
4
+ content?: unknown;
5
+ }
6
+ export interface AuthenticateCompleteMessage {
7
+ type: "authenticateComplete";
8
+ state: unknown;
9
+ authenticationSuccessful: boolean;
10
+ }
11
+ export interface CanUploadMessage {
12
+ type: "canUpload";
13
+ locationDisplayName?: string;
14
+ }
15
+ export interface ClearNextMessage {
16
+ type: "clearNext";
17
+ }
18
+ export interface DoneUploadingMessage {
19
+ type: "doneUploading";
20
+ documentLocation: string;
21
+ }
22
+ export interface DeliverDocumentMessage {
23
+ type: "deliverDocument";
24
+ documentUrl: string;
25
+ }
26
+ export interface ErrorMessage {
27
+ type: "error";
28
+ message: string;
29
+ }
30
+ export interface InitializeMessage {
31
+ type: "initialize";
32
+ }
33
+ export interface RequestOptionalInputMessage {
34
+ type: "requestOptionalInput";
35
+ }
36
+ export interface RequireInputMessage {
37
+ type: "requireInput";
38
+ }
39
+ export declare type ShouldAuthenticateMessage = {
40
+ type: "shouldAuthenticate";
41
+ shouldAuthenticate: false;
42
+ } | {
43
+ type: "shouldAuthenticate";
44
+ authenticationUrl: string;
45
+ shouldAuthenticate: true;
46
+ };
47
+ export declare type PostMessageMessage = AcknowledgeMessage | AuthenticateCompleteMessage | CanUploadMessage | ClearNextMessage | DeliverDocumentMessage | DoneUploadingMessage | ErrorMessage | InitializeMessage | RequestOptionalInputMessage | RequireInputMessage | ShouldAuthenticateMessage;
48
+ export declare const getSendPostMessageFunction: (targetWindow: Window | undefined, getOrigin?: () => string | undefined) => (message: PostMessageMessage) => void;
49
+ export declare const getOriginFilteredMessageHandler: <T extends PostMessageMessage>(postMessageHandler: PostMessageHandler<T>) => (event: WindowEventMap["message"]) => void;
50
+ export declare const getPostMessageAwaiter: () => <T extends PostMessageMessage>(type: PostMessageMessage["type"], timeoutMs: number) => Promise<T>;
51
+ interface TemplafyMessageEvent<T extends PostMessageMessage> extends MessageEvent {
52
+ data: T;
53
+ }
54
+ export {};
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPostMessageAwaiter = exports.getOriginFilteredMessageHandler = exports.getSendPostMessageFunction = void 0;
4
+ var tslib_1 = require("tslib");
5
+ var PromiseUtils_1 = require("./PromiseUtils");
6
+ var GlobalVars_1 = require("./GlobalVars");
7
+ exports.getSendPostMessageFunction = function (targetWindow, getOrigin) {
8
+ if (getOrigin === void 0) { getOrigin = function () { return (targetWindow && GlobalVars_1.windowMap.get(targetWindow)); }; }
9
+ return function (message) {
10
+ var origin = getOrigin();
11
+ if (!origin) {
12
+ throw new Error("Call initialize before sending message.");
13
+ }
14
+ if (targetWindow) {
15
+ targetWindow.postMessage(message, origin);
16
+ }
17
+ };
18
+ };
19
+ exports.getOriginFilteredMessageHandler = function (postMessageHandler) {
20
+ return function (event) {
21
+ var validOriginRegExp = GlobalVars_1.getValidOriginRegExp();
22
+ if (!validOriginRegExp.test(event.origin)) {
23
+ return;
24
+ }
25
+ GlobalVars_1.updateRelationship(event.source, event.origin);
26
+ postMessageHandler(event);
27
+ };
28
+ };
29
+ exports.getPostMessageAwaiter = function () {
30
+ return function (type, timeoutMs) {
31
+ var _a = tslib_1.__read(PromiseUtils_1.getPromiseAndResolver(), 2), promise = _a[0], resolver = _a[1];
32
+ var messageEventHandler = exports.getOriginFilteredMessageHandler(function (_a) {
33
+ var data = _a.data;
34
+ if (data.type !== type) {
35
+ return;
36
+ }
37
+ resolver(data);
38
+ });
39
+ window.addEventListener("message", messageEventHandler);
40
+ var timeoutPromise = PromiseUtils_1.getPromiseRejectedAfter(timeoutMs);
41
+ var result = Promise.race([promise, timeoutPromise]);
42
+ result.finally(function () {
43
+ window.removeEventListener("message", messageEventHandler);
44
+ });
45
+ return result;
46
+ };
47
+ };
@@ -0,0 +1,2 @@
1
+ export declare function generateRegExpFromUrls(urls: string[]): RegExp;
2
+ export declare function generateRegExpFromUrl(url: string): string;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateRegExpFromUrl = exports.generateRegExpFromUrls = void 0;
4
+ function generateRegExpFromUrls(urls) {
5
+ var urlsRegex = "";
6
+ for (var i = 0; i < urls.length; i++) {
7
+ var isFirst = i === 0;
8
+ urlsRegex += isFirst ? "" : "|";
9
+ urlsRegex += generateRegExpFromUrl(urls[i]);
10
+ }
11
+ return new RegExp(urlsRegex);
12
+ }
13
+ exports.generateRegExpFromUrls = generateRegExpFromUrls;
14
+ function generateRegExpFromUrl(url) {
15
+ var urlRegex = "";
16
+ var urlParts = url.split(".");
17
+ for (var i = 0; i < urlParts.length; i++) {
18
+ var validSubdomainPartRegex = urlParts[i].replace("*", "[^/^.]+");
19
+ var isFirst = i === 0;
20
+ urlRegex += isFirst ? "" : "[.]";
21
+ urlRegex += validSubdomainPartRegex;
22
+ }
23
+ return "^" + urlRegex + "$";
24
+ }
25
+ exports.generateRegExpFromUrl = generateRegExpFromUrl;
@@ -0,0 +1,6 @@
1
+ declare type PromiseCallback<T, A> = (resolve: (result: T) => void, reject: (reason?: A) => void) => void;
2
+ export declare function createTimeoutPromise<T, A>(timeoutMessage: string, ms: number, arg: PromiseCallback<T, A>): Promise<T>;
3
+ export declare type PromiseResolver<T> = (data: T) => void;
4
+ export declare function getPromiseAndResolver<TResolveMessage>(): [Promise<TResolveMessage>, PromiseResolver<TResolveMessage>];
5
+ export declare function getPromiseRejectedAfter<T>(ms: number): Promise<T>;
6
+ export {};
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPromiseRejectedAfter = exports.getPromiseAndResolver = exports.createTimeoutPromise = void 0;
4
+ function createTimeoutPromise(timeoutMessage, ms, arg) {
5
+ return new Promise(function (resolve, reject) {
6
+ var timeout = setTimeout(function () {
7
+ reject(timeoutMessage);
8
+ }, ms);
9
+ var handleResolve = function (result) {
10
+ resolve(result);
11
+ clearTimeout(timeout);
12
+ };
13
+ arg(handleResolve, reject);
14
+ });
15
+ }
16
+ exports.createTimeoutPromise = createTimeoutPromise;
17
+ function getPromiseAndResolver() {
18
+ var promiseResolver;
19
+ var promise = new Promise(function (resolve) {
20
+ promiseResolver = resolve;
21
+ });
22
+ return [promise, promiseResolver];
23
+ }
24
+ exports.getPromiseAndResolver = getPromiseAndResolver;
25
+ function getPromiseRejectedAfter(ms) {
26
+ return createTimeoutPromise("", ms, function () { });
27
+ }
28
+ exports.getPromiseRejectedAfter = getPromiseRejectedAfter;