@chaindoc_io/embed-sdk 2.2.0 → 2.4.0
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/CHANGELOG.md +50 -0
- package/README.md +110 -0
- package/dist/embed-sdk.umd.js +5 -5
- package/dist/embed-sdk.umd.js.map +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +38 -2
- package/dist/index.d.ts +38 -2
- package/dist/index.mjs +6 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,56 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [2.4.0] - 2026-11-28
|
|
9
|
+
|
|
10
|
+
Backwards compatible: new error codes are typed, no option or event changes. The package itself changes nothing at
|
|
11
|
+
runtime. The signing window it opens is served from `embed.chaindoc.io`, the same for every SDK version; its one change
|
|
12
|
+
that a page can notice is under "Changed".
|
|
13
|
+
|
|
14
|
+
### Changed (the signing window)
|
|
15
|
+
- **A failure to start the identity check is no longer an `ERROR`.** When the KYC step cannot start for a reason the
|
|
16
|
+
signer can retry (the network, a server error, too many attempts, the provider's widget failing), the window says it in
|
|
17
|
+
its identity step and offers Try again; the session stays open and the page hears nothing. Before, the window ended
|
|
18
|
+
with an error screen and the page got `ERROR`. Refusals the server names (an expired session, `KYC_WAITS_FOR_A_UNIT`,
|
|
19
|
+
...) still end the flow with `ERROR`, and `KYC_REJECTED` is reported as below.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
- `EMBEDDED_DECLINE_REASON_REQUIRED` and `EMBEDDED_DECLINE_REASON_TOO_LONG` in `TYPED_EMBED_ERROR_CODES`: the signing window
|
|
23
|
+
reports them in `ERROR` when the server refuses a decline's reason. Types only; nothing changes at runtime.
|
|
24
|
+
- `SESSION_REVOKED` and `EMBEDDED_SESSION_IDENTITY_STALE` in `TYPED_EMBED_ERROR_CODES`: the signing window reports them in
|
|
25
|
+
`ERROR` when a session can no longer be opened (revoked by a re-addressing; its address changed hands). The other login
|
|
26
|
+
refusals keep their 1.0 codes (`SESSION_EXPIRED`, `SESSION_ALREADY_CONFIRMED`, `SESSION_NOT_FOUND`, …), which the server
|
|
27
|
+
now sends as its `errorKey`. Types only; nothing changes at runtime.
|
|
28
|
+
- `KYC_REJECTED` in `TYPED_EMBED_ERROR_CODES`: the signing window reports it in `ERROR` (once per session, with
|
|
29
|
+
`details.rejectType: "final"`) when the signer was refused identity verification for good and cannot sign. The window
|
|
30
|
+
shows its own final screen; the page hears `CANCEL` and `CLOSED` when the signer closes it. Types only; nothing changes at
|
|
31
|
+
runtime.
|
|
32
|
+
|
|
33
|
+
### Documentation
|
|
34
|
+
- `signatureKind: "qualified"` names the method (the signer's own certificate), not a legal verdict; the verdict is read on
|
|
35
|
+
the server. `SIGNING_METHOD_BELOW_REQUIREMENT` no longer claims the window cannot make a qualified signature: it can.
|
|
36
|
+
- `EMBEDDED_CONTRACT_NOT_SIGNABLE` means a contract that was never sent for signing (a contract whose request ended is
|
|
37
|
+
`EMBEDDED_SIGNING_REQUEST_CLOSED`). A refused signature can report any server `errorKey` verbatim.
|
|
38
|
+
|
|
39
|
+
## [2.3.0] - 2026-11-10
|
|
40
|
+
|
|
41
|
+
Backwards compatible: no existing event, option or type changes meaning; every new field is optional. The wire format is
|
|
42
|
+
documented under "Message protocol" in the README.
|
|
43
|
+
|
|
44
|
+
### Added
|
|
45
|
+
|
|
46
|
+
- **`SUCCESS` carries `result.kind`** (`document_signature`, `contract_signature`) and **`signatureKind`** (`simple`, `qualified`).
|
|
47
|
+
- **`DECLINED` event** and the `onDecline` callback, with the reason when the signer gave one. A decline does not call `onCancel`.
|
|
48
|
+
- **Typed error codes**: `NOT_YOUR_TURN`, `ACCOUNT_READ_ONLY`, `KYC_WAITS_FOR_A_UNIT`, `SIGNING_FIELDS_EMPTY`,
|
|
49
|
+
`SIGNING_METHOD_BELOW_REQUIREMENT`, `INTEGRATIONS_NOT_IN_PLAN`, `PAYMENT_PROVIDER_ERROR`, `PAYMENT_PROVIDER_NOT_CONFIGURED`
|
|
50
|
+
and the embedded payment-method refusals (`EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED`, `EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED`,
|
|
51
|
+
`EMBEDDED_SIGNING_REQUEST_CLOSED`, `EMBEDDED_CONTRACT_NOT_SIGNABLE`). `EmbedErrorCode` types them and still accepts any other string.
|
|
52
|
+
- Helpers `getSigningFieldProblems`, `isKnownEmbedErrorCode`, `isTypedEmbedErrorCode`.
|
|
53
|
+
|
|
54
|
+
### Changed
|
|
55
|
+
|
|
56
|
+
- `SignatureErrorData.code` is typed `EmbedErrorCode` (known codes plus `string`); still assignable from and to `string`.
|
|
57
|
+
|
|
8
58
|
## [2.2.0] - 2026-05-07
|
|
9
59
|
|
|
10
60
|
### Changed
|
package/README.md
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/@chaindoc_io/embed-sdk)
|
|
6
6
|
[](LICENSE)
|
|
7
7
|
|
|
8
|
+
What changed in November 2026 → server-sdk `docs/WHATS-CHANGED-2026-11.md`
|
|
9
|
+
|
|
8
10
|
## What is Chaindoc Embed SDK?
|
|
9
11
|
|
|
10
12
|
Chaindoc Embed SDK is a lightweight JavaScript library that allows you to seamlessly integrate document signing functionality into your web application. Instead of redirecting users to a separate signing page, you can embed the entire signing experience directly within your site using a modal dialog or inline container.
|
|
@@ -102,6 +104,114 @@ Opens a centered modal dialog with overlay - perfect for most use cases.
|
|
|
102
104
|
|
|
103
105
|
Embeds the signing flow directly into a container element on your page - ideal for multi-step forms or dedicated signing pages.
|
|
104
106
|
|
|
107
|
+
## Message protocol
|
|
108
|
+
|
|
109
|
+
The iframe app posts messages to the host page with `window.parent.postMessage(message, hostOrigin)`. The SDK accepts a
|
|
110
|
+
message only when `event.origin` is the iframe's origin, `event.source` is that iframe's window, and
|
|
111
|
+
`message.source === "chaindoc-embed"`. Every message is `{ source: "chaindoc-embed", type, data? }`.
|
|
112
|
+
|
|
113
|
+
### Iframe to SDK
|
|
114
|
+
|
|
115
|
+
| `type` | `data` | Since | SDK callback |
|
|
116
|
+
| --- | --- | --- | --- |
|
|
117
|
+
| `READY` | none | 1.0 | `onReady` |
|
|
118
|
+
| `RESIZE` | `{ height: number }` | 1.0 | none (sets iframe height) |
|
|
119
|
+
| `SUCCESS` | `SignatureSuccessData` (below) | 1.0, extended 2.3.0 | `onSuccess` |
|
|
120
|
+
| `DECLINED` | `DeclinedData` (below) | 2.3.0 | `onDecline` |
|
|
121
|
+
| `ERROR` | `SignatureErrorData` (below) | 1.0, codes extended 2.3.0 | `onError` |
|
|
122
|
+
| `CANCEL` | none | 1.0 | `onCancel` (not after `SUCCESS` or `DECLINED`) |
|
|
123
|
+
| `CLOSED` | none | 1.0 | `onClose`, removes the iframe |
|
|
124
|
+
| `RESEND_OTP` | `{ email: string, sentAt: string }` | 1.0 | `onResendOtp` |
|
|
125
|
+
| `REQUEST_FULLSCREEN` / `EXIT_FULLSCREEN` | none | 1.0 | none |
|
|
126
|
+
|
|
127
|
+
SDK to iframe (unchanged): `CLOSE` (no data), `THEME_CHANGE` with `{ theme: "light" | "dark" }`.
|
|
128
|
+
|
|
129
|
+
### `SUCCESS` data
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
{
|
|
133
|
+
sessionId: string;
|
|
134
|
+
documentId: string;
|
|
135
|
+
signatureId: string;
|
|
136
|
+
signedAt: string; // ISO 8601
|
|
137
|
+
result?: { kind: string }; // 2.3.0. What finished.
|
|
138
|
+
signatureKind?: string; // 2.3.0. How it was signed.
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
- `result.kind`: `"document_signature"` (a document or signature request was signed) or `"contract_signature"` (a
|
|
143
|
+
contract was signed). The iframe must send one of these; the SDK types a future kind as a plain string.
|
|
144
|
+
- `signatureKind`: `"simple"` (the platform's signature) or `"qualified"` (the signer's own certificate — a key file or a
|
|
145
|
+
smart card, opened in the signing window). It names the method, not a legal verdict: whether the signature is legally
|
|
146
|
+
qualified is the validator's verdict on that certificate, read on the server (`getRequestStatus`,
|
|
147
|
+
`signers[].qes.legalClass`).
|
|
148
|
+
- Both new fields are optional. An iframe older than 2.3.0 sends neither, and the SDK delivers the rest exactly as before.
|
|
149
|
+
|
|
150
|
+
### `DECLINED` data (2.3.0)
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
{
|
|
154
|
+
sessionId: string;
|
|
155
|
+
documentId?: string;
|
|
156
|
+
reason?: string; // what the signer typed; omit it when they gave none
|
|
157
|
+
declinedAt?: string; // ISO 8601
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Send `DECLINED` once, when the signer's decline was accepted by the server. Do not send `CANCEL` for the same decline
|
|
162
|
+
(the SDK suppresses a later `CANCEL`, but the iframe should not rely on it). The flow is not a success: no `SUCCESS`.
|
|
163
|
+
|
|
164
|
+
### `ERROR` data
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
{ code: string; message: string; details?: Record<string, unknown> }
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`code` is the server's `errorKey` verbatim for a typed refusal. The SDK passes any code through; an unknown code stays a
|
|
171
|
+
string (`EmbedErrorCode` is `KnownEmbedErrorCode | (string & Record<never, never>)`).
|
|
172
|
+
|
|
173
|
+
| `code` | Since | Meaning | `details` |
|
|
174
|
+
| --- | --- | --- | --- |
|
|
175
|
+
| `SESSION_EXPIRED`, `SESSION_NOT_FOUND`, `INVALID_OTP`, `OTP_EXPIRED`, `DOCUMENT_NOT_FOUND`, `ALREADY_SIGNED`, `NETWORK_ERROR`, `UNAUTHORIZED`, `RATE_LIMITED`, `SIGNATURE_LIMIT_EXCEEDED`, `SUBSCRIPTION_NOT_FOUND`, `USER_NOT_FOUND`, `EMAIL_MISMATCH`, `SESSION_ALREADY_CONFIRMED`, `NO_FILES_PROVIDED`, `SERVER_ERROR`, `UNKNOWN_ERROR` | 1.0 | unchanged | none |
|
|
176
|
+
| `NOT_YOUR_TURN` | 2.3.0 | an earlier signer has not signed yet | none |
|
|
177
|
+
| `ACCOUNT_READ_ONLY` | 2.3.0 | the sender's account is read only | none |
|
|
178
|
+
| `KYC_WAITS_FOR_A_UNIT` | 2.3.0 | identity check cannot start: no KYC unit available | none |
|
|
179
|
+
| `SIGNING_FIELDS_EMPTY` | 2.3.0 | fields the signer must fill are empty or invalid | `{ fields: { key: string, name: string, problem: "missing" \| "invalid" }[] }` |
|
|
180
|
+
| `SIGNING_METHOD_BELOW_REQUIREMENT` | 2.3.0 | the signer must sign with their own certificate and a simple signature was attempted (the window offers such a signer only the qualified way) | none |
|
|
181
|
+
| `INTEGRATIONS_NOT_IN_PLAN` | 2.3.0 | the account's plan has no integrations | none |
|
|
182
|
+
| `PAYMENT_PROVIDER_ERROR` | 2.3.0 | the payment provider failed | none |
|
|
183
|
+
| `PAYMENT_PROVIDER_NOT_CONFIGURED` | 2.3.0 | no payment provider is configured | none |
|
|
184
|
+
| `EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED` | 2.3.0 | the contract asks for no payment method | none |
|
|
185
|
+
| `EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED` | 2.3.0 | a payment method is already linked | none |
|
|
186
|
+
| `EMBEDDED_SIGNING_REQUEST_CLOSED` | 2.3.0 | the signing request is closed | `{ status: string }` (optional) |
|
|
187
|
+
| `EMBEDDED_CONTRACT_NOT_SIGNABLE` | 2.3.0 | the contract was never sent for signing | `{ status: string }` (optional) |
|
|
188
|
+
| `EMBEDDED_DECLINE_REASON_REQUIRED`, `EMBEDDED_DECLINE_REASON_TOO_LONG` | 2.4.0 | the server refused a decline's reason (the window always asks one and checks its length first) | none |
|
|
189
|
+
| `SESSION_REVOKED` | 2.4.0 | the link no longer opens: the sender re-addressed the signer and this session was revoked; issue a new session | none |
|
|
190
|
+
| `EMBEDDED_SESSION_IDENTITY_STALE` | 2.4.0 | the session's e-mail address now belongs to a different account than the one it was issued to; issue a new session | none |
|
|
191
|
+
| `KYC_REJECTED` | 2.4.0 | the signer was refused identity verification for good: they cannot sign this request (the window shows a final screen; Close ends it). Sent once per session. A resubmission the provider asks for is not this — its widget asks for it | `{ rejectType: "final" }` |
|
|
192
|
+
|
|
193
|
+
A failure to start the identity check that the signer can retry (the network, a server error, too many attempts) is not
|
|
194
|
+
an `ERROR`: the window says it in its identity step and offers Try again, and the session stays open. Refusals the server
|
|
195
|
+
names (an expired session, `KYC_WAITS_FOR_A_UNIT`, ...) still end the flow with `ERROR`.
|
|
196
|
+
|
|
197
|
+
A refused signature reports the server's own `errorKey` verbatim, so `code` may be a key outside this table (for example
|
|
198
|
+
`KYC_NOT_VERIFIED`, `SIGNER_ALREADY_ACTED`, `SIGNING_REQUEST_EXPIRED`); without a key it is `SERVER_ERROR`, `NETWORK_ERROR`,
|
|
199
|
+
`RATE_LIMITED`, `UNAUTHORIZED` or `UNKNOWN_ERROR`.
|
|
200
|
+
|
|
201
|
+
`getSigningFieldProblems(error)` reads the field list of `SIGNING_FIELDS_EMPTY` (null for another code; malformed
|
|
202
|
+
entries are dropped).
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
sdk.openSignatureFlow({
|
|
206
|
+
sessionId,
|
|
207
|
+
onSuccess: ({ result, signatureKind }) => console.log(result?.kind, signatureKind),
|
|
208
|
+
onDecline: ({ reason }) => console.log("declined", reason),
|
|
209
|
+
onError: (error) => {
|
|
210
|
+
if (error.code === "SIGNING_FIELDS_EMPTY") console.log(getSigningFieldProblems(error));
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
105
215
|
## Browser Support
|
|
106
216
|
|
|
107
217
|
- Chrome/Edge 90+
|
package/dist/embed-sdk.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ChaindocEmbed=(()=>{var
|
|
1
|
+
"use strict";var ChaindocEmbed=(()=>{var g=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var N=(i,e)=>{for(var t in e)g(i,t,{get:e[t],enumerable:!0})},M=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of R(e))!T.call(i,r)&&r!==t&&g(i,r,{get:()=>e[r],enumerable:!(n=O(e,r))||n.enumerable});return i};var L=i=>M(g({},"__esModule",{value:!0}),i);var A={};N(A,{ChaindocEmbed:()=>c,EmbedInstance:()=>a,LEGACY_EMBED_ERROR_CODES:()=>m,TYPED_EMBED_ERROR_CODES:()=>h,getSigningFieldProblems:()=>w,isKnownEmbedErrorCode:()=>I,isTypedEmbedErrorCode:()=>D});function E(i){switch(i){case"production":return"https://embed.chaindoc.io";case"staging":return"https://embed-demo.chaindoc.io";case"development":return"https://embed-demo.chaindoc.io";default:return"https://embed.chaindoc.io"}}function u(i){let e=E(i);try{return new URL(e).origin}catch{return e}}function f(i,e,t,n,r,s,l){let o=new URL(`/embed/sign/${e}`,i),p=t?.trim().toLowerCase();return p&&o.searchParams.set("email",p),n&&o.searchParams.set("mode",n),r&&o.searchParams.set("theme",r),s&&o.searchParams.set("lang",s),l!==void 0&&o.searchParams.set("closeOnEscape",String(l)),o.toString()}function S(i){if(typeof i=="string"){let e=document.querySelector(i);if(!e)throw new Error(`Container element not found: ${i}`);return e}return i}var d=class{constructor(e){this.debug=e}log(...e){this.debug&&console.log("[Chaindoc SDK]",...e)}warn(...e){this.debug&&console.warn("[Chaindoc SDK]",...e)}error(...e){this.debug&&console.error("[Chaindoc SDK]",...e)}};function v(i){return typeof i=="object"&&i!==null&&"source"in i&&i.source==="chaindoc-embed"}function b(i){return`
|
|
2
2
|
position: fixed;
|
|
3
3
|
top: 0;
|
|
4
4
|
left: 0;
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
border-radius: 12px;
|
|
21
21
|
overflow: hidden;
|
|
22
22
|
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
|
23
|
-
`.trim()}function
|
|
23
|
+
`.trim()}function _(i){let e=`
|
|
24
24
|
width: 100%;
|
|
25
25
|
border: none;
|
|
26
26
|
display: block;
|
|
@@ -31,10 +31,10 @@
|
|
|
31
31
|
`.trim():`
|
|
32
32
|
${e}
|
|
33
33
|
height: 0;
|
|
34
|
-
`.trim()}function
|
|
34
|
+
`.trim()}function C(){return`
|
|
35
35
|
position: relative;
|
|
36
36
|
width: 100%;
|
|
37
|
-
`.trim()}var
|
|
37
|
+
`.trim()}var a=class{constructor(e,t,n){this.overlay=null;this.modalContainer=null;this.container=null;this.previousOverflow="";this.isFullscreen=!1;this.previousIframeStyle=null;this.internalEventHandlers=new Map;this.config=e,this.logger=n,this.options=t,this.state={sessionId:this.options.sessionId,mode:this.options.mode||"modal",theme:this.options.theme||"light",isReady:!1,isClosed:!1,hasSucceeded:!1,hasDeclined:!1};let r=E(this.config.environment);this.allowedOrigin=u(this.config.environment);let s=f(r,this.options.sessionId,this.options.email,this.state.mode,this.state.theme,this.options.language,this.options.closeOnEscape);this.iframe=this.createIframe(s),this.messageListener=this.handleMessage.bind(this),window.addEventListener("message",this.messageListener),this.state.mode==="modal"?this.renderModal():this.renderInline(),this.logger.log("Instance created",{sessionId:this.state.sessionId,mode:this.state.mode})}createIframe(e){let t=document.createElement("iframe");return t.src=e,t.setAttribute("style",_(this.state.mode)),t.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"),t.setAttribute("allow","clipboard-write; camera; microphone; geolocation"),t}renderModal(){if(this.overlay=document.createElement("div"),this.overlay.setAttribute("style",b(this.options.zIndex??999999)),this.overlay.setAttribute("data-chaindoc-overlay","true"),this.modalContainer=document.createElement("div"),this.modalContainer.setAttribute("style",y(this.options.modalWidth,this.options.modalHeight)),this.modalContainer.appendChild(this.iframe),this.overlay.appendChild(this.modalContainer),this.options.closeOnClickOutside!==!1&&this.overlay.addEventListener("click",e=>{e.target===this.overlay&&(this.logger.log("Clicked outside modal - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())}),this.options.closeOnEscape!==!1){let e=t=>{t.key==="Escape"&&(this.logger.log("ESC key pressed - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())};document.addEventListener("keydown",e),this._internalOn("close",()=>{document.removeEventListener("keydown",e)})}this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",document.body.appendChild(this.overlay)}renderInline(){if(!this.options.container)throw new Error("Container is required for inline mode");this.container=S(this.options.container);let e=document.createElement("div");e.setAttribute("style",C()),e.setAttribute("data-chaindoc-inline","true"),e.appendChild(this.iframe),this.container.appendChild(e)}handleMessage(e){if(e.origin!==this.allowedOrigin||e.source!==this.iframe.contentWindow||!v(e.data))return;let t=e.data;switch(this.logger.log("Received message:",t.type,t),t.type){case"READY":this.state.isReady=!0,this.options.onReady?.();break;case"RESIZE":"data"in t&&!this.isFullscreen&&(this.iframe.style.height=`${t.data.height}px`);break;case"SUCCESS":this.state.hasSucceeded=!0,"data"in t&&this.options.onSuccess?.(t.data);break;case"ERROR":"data"in t&&this.options.onError?.(t.data);break;case"DECLINED":this.state.hasDeclined=!0,"data"in t&&this.options.onDecline?.(t.data);break;case"CANCEL":!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.();break;case"CLOSED":this.cleanup();break;case"RESEND_OTP":"data"in t&&this.options.onResendOtp?.(t.data);break;case"REQUEST_FULLSCREEN":this.enterFullscreen();break;case"EXIT_FULLSCREEN":this.exitFullscreen();break;default:this.logger.warn("Unknown message type:",t)}}enterFullscreen(){this.isFullscreen||this.state.isClosed||(this.logger.log("Entering fullscreen"),this.previousIframeStyle=this.iframe.getAttribute("style"),this.iframe.setAttribute("style",`
|
|
38
38
|
position: fixed;
|
|
39
39
|
top: 0;
|
|
40
40
|
left: 0;
|
|
@@ -48,5 +48,5 @@
|
|
|
48
48
|
padding: 0;
|
|
49
49
|
display: block;
|
|
50
50
|
z-index: 2147483647;
|
|
51
|
-
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var
|
|
51
|
+
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var c=class{constructor(e){this.instances=new Set;if(!e.publicKey)throw new Error("ChaindocEmbed: publicKey is required");if(!e.publicKey.startsWith("pk_"))throw new Error('ChaindocEmbed: publicKey must start with "pk_"');this.config={publicKey:e.publicKey,environment:e.environment||"production",debug:e.debug||!1},this.logger=new d(this.config.debug),this.logger.log("SDK initialized",this.config)}openSignatureFlow(e){if(!e.sessionId)throw new Error("openSignatureFlow: sessionId is required");if(!e.sessionId.startsWith("ses_"))throw new Error('openSignatureFlow: sessionId must start with "ses_"');if((e.mode||"modal")==="inline"&&!e.container)throw new Error("openSignatureFlow: container is required for inline mode");this.logger.log("Opening signature flow",e);let n=new a(this.config,e,this.logger);return this.instances.add(n),n._internalOn("close",()=>{this.instances.delete(n)}),n}destroy(){this.logger.log("Destroying SDK and all instances");for(let e of this.instances)e.close();this.instances.clear()}static get version(){return"2.4.0"}};var m=["SESSION_EXPIRED","SESSION_NOT_FOUND","INVALID_OTP","OTP_EXPIRED","DOCUMENT_NOT_FOUND","ALREADY_SIGNED","NETWORK_ERROR","UNAUTHORIZED","RATE_LIMITED","SIGNATURE_LIMIT_EXCEEDED","SUBSCRIPTION_NOT_FOUND","USER_NOT_FOUND","EMAIL_MISMATCH","SESSION_ALREADY_CONFIRMED","NO_FILES_PROVIDED","SERVER_ERROR","UNKNOWN_ERROR"],h=["NOT_YOUR_TURN","ACCOUNT_READ_ONLY","KYC_WAITS_FOR_A_UNIT","SIGNING_FIELDS_EMPTY","SIGNING_METHOD_BELOW_REQUIREMENT","INTEGRATIONS_NOT_IN_PLAN","PAYMENT_PROVIDER_ERROR","PAYMENT_PROVIDER_NOT_CONFIGURED","EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED","EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED","EMBEDDED_SIGNING_REQUEST_CLOSED","EMBEDDED_CONTRACT_NOT_SIGNABLE","EMBEDDED_DECLINE_REASON_REQUIRED","EMBEDDED_DECLINE_REASON_TOO_LONG","SESSION_REVOKED","EMBEDDED_SESSION_IDENTITY_STALE","KYC_REJECTED"],x=[...m,...h];function I(i){return typeof i=="string"&&x.includes(i)}function D(i){return typeof i=="string"&&h.includes(i)}function w(i){if(i.code!=="SIGNING_FIELDS_EMPTY")return null;let e=i.details?.fields;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let{key:r,name:s,problem:l}=n;typeof r!="string"||r===""||t.push({key:r,name:typeof s=="string"&&s!==""?s:r,problem:l==="invalid"?"invalid":"missing"})}return t}return L(A);})();
|
|
52
52
|
//# sourceMappingURL=embed-sdk.umd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts"],"sourcesContent":["/**\n * @chaindoc/embed-sdk\n *\n * JavaScript/TypeScript SDK for embedding Chaindoc document signing flow via iframe.\n *\n * @packageDocumentation\n */\n\nexport { ChaindocEmbed } from \"./ChaindocEmbed\";\nexport { EmbedInstance } from \"./EmbedInstance\";\nexport type {\n ChaindocEmbedConfig,\n SignatureFlowOptions,\n Environment,\n DisplayMode,\n Theme,\n Language,\n SignatureSuccessData,\n SignatureErrorData,\n ResendOtpData,\n IframeToSdkMessage,\n SdkToIframeMessage,\n} from \"./types\";\n","/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n"],"mappings":"icAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,kBAAAC,ICSO,SAASC,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,CACF,CAKO,SAASC,EACdD,EACAE,EACAC,EACAC,EACAC,EACAC,EACAC,EACQ,CAER,IAAMC,EAAM,IAAI,IAAI,eAAeN,CAAS,GAAIF,CAAO,EAEjDS,EAAkBN,GAAO,KAAK,EAAE,YAAY,EAClD,OAAIM,GACFD,EAAI,aAAa,IAAI,QAASC,CAAe,EAG3CL,GACFI,EAAI,aAAa,IAAI,OAAQJ,CAAI,EAG/BC,GACFG,EAAI,aAAa,IAAI,QAASH,CAAK,EAGjCC,GACFE,EAAI,aAAa,IAAI,OAAQF,CAAQ,EAGnCC,IAAkB,QACpBC,EAAI,aAAa,IAAI,gBAAiB,O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,KAAK,OAAO,IAAI,kCAAkC,EAElD,QAAWA,KAAY,KAAK,UAC1BA,EAAS,MAAM,EAGjB,KAAK,UAAU,MAAM,CACvB,CAKA,WAAW,SAAkB,CAC3B,MAAO,OACT,CACF","names":["src_exports","__export","ChaindocEmbed","EmbedInstance","getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts","../src/errors.ts"],"sourcesContent":["/**\n * @chaindoc/embed-sdk\n *\n * JavaScript/TypeScript SDK for embedding Chaindoc document signing flow via iframe.\n *\n * @packageDocumentation\n */\n\nexport { ChaindocEmbed } from \"./ChaindocEmbed\";\nexport { EmbedInstance } from \"./EmbedInstance\";\nexport type {\n ChaindocEmbedConfig,\n SignatureFlowOptions,\n Environment,\n DisplayMode,\n Theme,\n Language,\n SignatureSuccessData,\n SignatureErrorData,\n ResendOtpData,\n DeclinedData,\n SignatureResult,\n SignatureResultKind,\n SignatureKind,\n IframeToSdkMessage,\n SdkToIframeMessage,\n} from \"./types\";\nexport {\n LEGACY_EMBED_ERROR_CODES,\n TYPED_EMBED_ERROR_CODES,\n isKnownEmbedErrorCode,\n isTypedEmbedErrorCode,\n getSigningFieldProblems,\n} from \"./errors\";\nexport type {\n EmbedErrorCode,\n KnownEmbedErrorCode,\n LegacyEmbedErrorCode,\n TypedEmbedErrorCode,\n SigningFieldProblem,\n} from \"./errors\";\n","/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n hasDeclined: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'DECLINED':\n this.state.hasDeclined = true;\n if ('data' in message) {\n this.options.onDecline?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n","/**\n * Typed error codes of the embedded signing surface (added in 2.3.0).\n *\n * `SignatureErrorData.code` has always been a string. The codes below are the ones the embed reports for the\n * server's typed refusals (each is the backend's `errorKey`, verbatim). An unknown code still reaches `onError`\n * unchanged as a string: new server codes never break an integration.\n */\n\n/** Codes the embed reported before 2.3.0. */\nexport const LEGACY_EMBED_ERROR_CODES = [\n \"SESSION_EXPIRED\",\n \"SESSION_NOT_FOUND\",\n \"INVALID_OTP\",\n \"OTP_EXPIRED\",\n \"DOCUMENT_NOT_FOUND\",\n \"ALREADY_SIGNED\",\n \"NETWORK_ERROR\",\n \"UNAUTHORIZED\",\n \"RATE_LIMITED\",\n \"SIGNATURE_LIMIT_EXCEEDED\",\n \"SUBSCRIPTION_NOT_FOUND\",\n \"USER_NOT_FOUND\",\n \"EMAIL_MISMATCH\",\n \"SESSION_ALREADY_CONFIRMED\",\n \"NO_FILES_PROVIDED\",\n \"SERVER_ERROR\",\n \"UNKNOWN_ERROR\",\n] as const;\n\n/**\n * Typed refusals the embed names (new in 2.3.0). A refused signature reports the server's own `errorKey` verbatim, so a\n * code outside this list can still arrive (for example `KYC_NOT_VERIFIED`, `SIGNER_ALREADY_ACTED`, `SIGNING_REQUEST_EXPIRED`);\n * without a key it is `SERVER_ERROR`, `NETWORK_ERROR`, `RATE_LIMITED`, `UNAUTHORIZED` or `UNKNOWN_ERROR`. A session with\n * nothing to sign reports `EMBEDDED_SIGNING_REQUEST_CLOSED` (a contract's request ended) or `DOCUMENT_NOT_FOUND`.\n */\nexport const TYPED_EMBED_ERROR_CODES = [\n \"NOT_YOUR_TURN\",\n \"ACCOUNT_READ_ONLY\",\n \"KYC_WAITS_FOR_A_UNIT\",\n \"SIGNING_FIELDS_EMPTY\",\n \"SIGNING_METHOD_BELOW_REQUIREMENT\",\n \"INTEGRATIONS_NOT_IN_PLAN\",\n \"PAYMENT_PROVIDER_ERROR\",\n \"PAYMENT_PROVIDER_NOT_CONFIGURED\",\n \"EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED\",\n \"EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED\",\n \"EMBEDDED_SIGNING_REQUEST_CLOSED\",\n \"EMBEDDED_CONTRACT_NOT_SIGNABLE\",\n // A decline's own bounds, as the server says them: the window always asks a reason and checks its length first.\n \"EMBEDDED_DECLINE_REASON_REQUIRED\",\n \"EMBEDDED_DECLINE_REASON_TOO_LONG\",\n // The link no longer opens: the sender re-addressed the signer and this session was revoked; the session's address now\n // belongs to a different account than the one it was issued to. Issue a new session.\n \"SESSION_REVOKED\",\n \"EMBEDDED_SESSION_IDENTITY_STALE\",\n // The signer was refused identity verification for good (`details.rejectType: \"final\"`): they cannot sign this request.\n // Sent once per session, when the window first reads it; the window shows its own final screen and keeps Close.\n \"KYC_REJECTED\",\n] as const;\n\nexport type LegacyEmbedErrorCode = (typeof LEGACY_EMBED_ERROR_CODES)[number];\nexport type TypedEmbedErrorCode = (typeof TYPED_EMBED_ERROR_CODES)[number];\nexport type KnownEmbedErrorCode = LegacyEmbedErrorCode | TypedEmbedErrorCode;\n\n/**\n * Any error code. The known codes autocomplete; a code this SDK version does not know is still a `string`.\n */\nexport type EmbedErrorCode = KnownEmbedErrorCode | (string & Record<never, never>);\n\nconst KNOWN_CODES: readonly string[] = [\n ...LEGACY_EMBED_ERROR_CODES,\n ...TYPED_EMBED_ERROR_CODES,\n];\n\n/** True when `code` is one this SDK version knows by name. */\nexport function isKnownEmbedErrorCode(\n code: unknown,\n): code is KnownEmbedErrorCode {\n return typeof code === \"string\" && KNOWN_CODES.includes(code);\n}\n\n/** True when `code` is one of the typed refusals added in 2.3.0. */\nexport function isTypedEmbedErrorCode(\n code: unknown,\n): code is TypedEmbedErrorCode {\n return (\n typeof code === \"string\" &&\n (TYPED_EMBED_ERROR_CODES as readonly string[]).includes(code)\n );\n}\n\n/** One field a `SIGNING_FIELDS_EMPTY` refusal names. */\nexport interface SigningFieldProblem {\n /** Placement id of the field. */\n key: string;\n /** Field name for display (falls back to `key`). */\n name: string;\n /** `missing`: no value given; `invalid`: a value that does not fit the field. */\n problem: \"missing\" | \"invalid\";\n}\n\n/**\n * The fields a `SIGNING_FIELDS_EMPTY` error names, read from `error.details.fields`.\n * Returns `null` when the error is any other code. A malformed entry is dropped.\n */\nexport function getSigningFieldProblems(error: {\n code: string;\n details?: Record<string, unknown>;\n}): SigningFieldProblem[] | null {\n if (error.code !== \"SIGNING_FIELDS_EMPTY\") return null;\n const raw = error.details?.fields;\n if (!Array.isArray(raw)) return [];\n\n const problems: SigningFieldProblem[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const { key, name, problem } = entry as Record<string, unknown>;\n if (typeof key !== \"string\" || key === \"\") continue;\n problems.push({\n key,\n name: typeof name === \"string\" && name !== \"\" ? name : key,\n problem: problem === \"invalid\" ? \"invalid\" : \"missing\",\n });\n }\n return problems;\n}\n"],"mappings":"icAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,kBAAAC,EAAA,6BAAAC,EAAA,4BAAAC,EAAA,4BAAAC,EAAA,0BAAAC,EAAA,0BAAAC,ICSO,SAASC,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,CACF,CAKO,SAASC,EACdD,EACAE,E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AS,uBAAwB,OAAO,KAClD,IAAMC,EAAMD,EAAM,SAAS,OAC3B,GAAI,CAAC,MAAM,QAAQC,CAAG,EAAG,MAAO,CAAC,EAEjC,IAAMC,EAAkC,CAAC,EACzC,QAAWC,KAASF,EAAK,CACvB,GAAI,CAACE,GAAS,OAAOA,GAAU,SAAU,SACzC,GAAM,CAAE,IAAAC,EAAK,KAAAC,EAAM,QAAAC,CAAQ,EAAIH,EAC3B,OAAOC,GAAQ,UAAYA,IAAQ,IACvCF,EAAS,KAAK,CACZ,IAAAE,EACA,KAAM,OAAOC,GAAS,UAAYA,IAAS,GAAKA,EAAOD,EACvD,QAASE,IAAY,UAAY,UAAY,SAC/C,CAAC,CACH,CACA,OAAOJ,CACT","names":["src_exports","__export","ChaindocEmbed","EmbedInstance","LEGACY_EMBED_ERROR_CODES","TYPED_EMBED_ERROR_CODES","getSigningFieldProblems","isKnownEmbedErrorCode","isTypedEmbedErrorCode","getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance","LEGACY_EMBED_ERROR_CODES","TYPED_EMBED_ERROR_CODES","KNOWN_CODES","isKnownEmbedErrorCode","code","isTypedEmbedErrorCode","getSigningFieldProblems","error","raw","problems","entry","key","name","problem"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var g=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var N=(i,e)=>{for(var t in e)g(i,t,{get:e[t],enumerable:!0})},M=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of R(e))!T.call(i,r)&&r!==t&&g(i,r,{get:()=>e[r],enumerable:!(n=O(e,r))||n.enumerable});return i};var L=i=>M(g({},"__esModule",{value:!0}),i);var A={};N(A,{ChaindocEmbed:()=>c,EmbedInstance:()=>a,LEGACY_EMBED_ERROR_CODES:()=>m,TYPED_EMBED_ERROR_CODES:()=>h,getSigningFieldProblems:()=>w,isKnownEmbedErrorCode:()=>I,isTypedEmbedErrorCode:()=>D});module.exports=L(A);function E(i){switch(i){case"production":return"https://embed.chaindoc.io";case"staging":return"https://embed-demo.chaindoc.io";case"development":return"https://embed-demo.chaindoc.io";default:return"https://embed.chaindoc.io"}}function u(i){let e=E(i);try{return new URL(e).origin}catch{return e}}function f(i,e,t,n,r,s,l){let o=new URL(`/embed/sign/${e}`,i),p=t?.trim().toLowerCase();return p&&o.searchParams.set("email",p),n&&o.searchParams.set("mode",n),r&&o.searchParams.set("theme",r),s&&o.searchParams.set("lang",s),l!==void 0&&o.searchParams.set("closeOnEscape",String(l)),o.toString()}function S(i){if(typeof i=="string"){let e=document.querySelector(i);if(!e)throw new Error(`Container element not found: ${i}`);return e}return i}var d=class{constructor(e){this.debug=e}log(...e){this.debug&&console.log("[Chaindoc SDK]",...e)}warn(...e){this.debug&&console.warn("[Chaindoc SDK]",...e)}error(...e){this.debug&&console.error("[Chaindoc SDK]",...e)}};function v(i){return typeof i=="object"&&i!==null&&"source"in i&&i.source==="chaindoc-embed"}function b(i){return`
|
|
2
2
|
position: fixed;
|
|
3
3
|
top: 0;
|
|
4
4
|
left: 0;
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
border-radius: 12px;
|
|
21
21
|
overflow: hidden;
|
|
22
22
|
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
|
23
|
-
`.trim()}function
|
|
23
|
+
`.trim()}function _(i){let e=`
|
|
24
24
|
width: 100%;
|
|
25
25
|
border: none;
|
|
26
26
|
display: block;
|
|
@@ -31,10 +31,10 @@
|
|
|
31
31
|
`.trim():`
|
|
32
32
|
${e}
|
|
33
33
|
height: 0;
|
|
34
|
-
`.trim()}function
|
|
34
|
+
`.trim()}function C(){return`
|
|
35
35
|
position: relative;
|
|
36
36
|
width: 100%;
|
|
37
|
-
`.trim()}var
|
|
37
|
+
`.trim()}var a=class{constructor(e,t,n){this.overlay=null;this.modalContainer=null;this.container=null;this.previousOverflow="";this.isFullscreen=!1;this.previousIframeStyle=null;this.internalEventHandlers=new Map;this.config=e,this.logger=n,this.options=t,this.state={sessionId:this.options.sessionId,mode:this.options.mode||"modal",theme:this.options.theme||"light",isReady:!1,isClosed:!1,hasSucceeded:!1,hasDeclined:!1};let r=E(this.config.environment);this.allowedOrigin=u(this.config.environment);let s=f(r,this.options.sessionId,this.options.email,this.state.mode,this.state.theme,this.options.language,this.options.closeOnEscape);this.iframe=this.createIframe(s),this.messageListener=this.handleMessage.bind(this),window.addEventListener("message",this.messageListener),this.state.mode==="modal"?this.renderModal():this.renderInline(),this.logger.log("Instance created",{sessionId:this.state.sessionId,mode:this.state.mode})}createIframe(e){let t=document.createElement("iframe");return t.src=e,t.setAttribute("style",_(this.state.mode)),t.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"),t.setAttribute("allow","clipboard-write; camera; microphone; geolocation"),t}renderModal(){if(this.overlay=document.createElement("div"),this.overlay.setAttribute("style",b(this.options.zIndex??999999)),this.overlay.setAttribute("data-chaindoc-overlay","true"),this.modalContainer=document.createElement("div"),this.modalContainer.setAttribute("style",y(this.options.modalWidth,this.options.modalHeight)),this.modalContainer.appendChild(this.iframe),this.overlay.appendChild(this.modalContainer),this.options.closeOnClickOutside!==!1&&this.overlay.addEventListener("click",e=>{e.target===this.overlay&&(this.logger.log("Clicked outside modal - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())}),this.options.closeOnEscape!==!1){let e=t=>{t.key==="Escape"&&(this.logger.log("ESC key pressed - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())};document.addEventListener("keydown",e),this._internalOn("close",()=>{document.removeEventListener("keydown",e)})}this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",document.body.appendChild(this.overlay)}renderInline(){if(!this.options.container)throw new Error("Container is required for inline mode");this.container=S(this.options.container);let e=document.createElement("div");e.setAttribute("style",C()),e.setAttribute("data-chaindoc-inline","true"),e.appendChild(this.iframe),this.container.appendChild(e)}handleMessage(e){if(e.origin!==this.allowedOrigin||e.source!==this.iframe.contentWindow||!v(e.data))return;let t=e.data;switch(this.logger.log("Received message:",t.type,t),t.type){case"READY":this.state.isReady=!0,this.options.onReady?.();break;case"RESIZE":"data"in t&&!this.isFullscreen&&(this.iframe.style.height=`${t.data.height}px`);break;case"SUCCESS":this.state.hasSucceeded=!0,"data"in t&&this.options.onSuccess?.(t.data);break;case"ERROR":"data"in t&&this.options.onError?.(t.data);break;case"DECLINED":this.state.hasDeclined=!0,"data"in t&&this.options.onDecline?.(t.data);break;case"CANCEL":!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.();break;case"CLOSED":this.cleanup();break;case"RESEND_OTP":"data"in t&&this.options.onResendOtp?.(t.data);break;case"REQUEST_FULLSCREEN":this.enterFullscreen();break;case"EXIT_FULLSCREEN":this.exitFullscreen();break;default:this.logger.warn("Unknown message type:",t)}}enterFullscreen(){this.isFullscreen||this.state.isClosed||(this.logger.log("Entering fullscreen"),this.previousIframeStyle=this.iframe.getAttribute("style"),this.iframe.setAttribute("style",`
|
|
38
38
|
position: fixed;
|
|
39
39
|
top: 0;
|
|
40
40
|
left: 0;
|
|
@@ -48,5 +48,5 @@
|
|
|
48
48
|
padding: 0;
|
|
49
49
|
display: block;
|
|
50
50
|
z-index: 2147483647;
|
|
51
|
-
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var
|
|
51
|
+
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var c=class{constructor(e){this.instances=new Set;if(!e.publicKey)throw new Error("ChaindocEmbed: publicKey is required");if(!e.publicKey.startsWith("pk_"))throw new Error('ChaindocEmbed: publicKey must start with "pk_"');this.config={publicKey:e.publicKey,environment:e.environment||"production",debug:e.debug||!1},this.logger=new d(this.config.debug),this.logger.log("SDK initialized",this.config)}openSignatureFlow(e){if(!e.sessionId)throw new Error("openSignatureFlow: sessionId is required");if(!e.sessionId.startsWith("ses_"))throw new Error('openSignatureFlow: sessionId must start with "ses_"');if((e.mode||"modal")==="inline"&&!e.container)throw new Error("openSignatureFlow: container is required for inline mode");this.logger.log("Opening signature flow",e);let n=new a(this.config,e,this.logger);return this.instances.add(n),n._internalOn("close",()=>{this.instances.delete(n)}),n}destroy(){this.logger.log("Destroying SDK and all instances");for(let e of this.instances)e.close();this.instances.clear()}static get version(){return"2.4.0"}};var m=["SESSION_EXPIRED","SESSION_NOT_FOUND","INVALID_OTP","OTP_EXPIRED","DOCUMENT_NOT_FOUND","ALREADY_SIGNED","NETWORK_ERROR","UNAUTHORIZED","RATE_LIMITED","SIGNATURE_LIMIT_EXCEEDED","SUBSCRIPTION_NOT_FOUND","USER_NOT_FOUND","EMAIL_MISMATCH","SESSION_ALREADY_CONFIRMED","NO_FILES_PROVIDED","SERVER_ERROR","UNKNOWN_ERROR"],h=["NOT_YOUR_TURN","ACCOUNT_READ_ONLY","KYC_WAITS_FOR_A_UNIT","SIGNING_FIELDS_EMPTY","SIGNING_METHOD_BELOW_REQUIREMENT","INTEGRATIONS_NOT_IN_PLAN","PAYMENT_PROVIDER_ERROR","PAYMENT_PROVIDER_NOT_CONFIGURED","EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED","EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED","EMBEDDED_SIGNING_REQUEST_CLOSED","EMBEDDED_CONTRACT_NOT_SIGNABLE","EMBEDDED_DECLINE_REASON_REQUIRED","EMBEDDED_DECLINE_REASON_TOO_LONG","SESSION_REVOKED","EMBEDDED_SESSION_IDENTITY_STALE","KYC_REJECTED"],x=[...m,...h];function I(i){return typeof i=="string"&&x.includes(i)}function D(i){return typeof i=="string"&&h.includes(i)}function w(i){if(i.code!=="SIGNING_FIELDS_EMPTY")return null;let e=i.details?.fields;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let{key:r,name:s,problem:l}=n;typeof r!="string"||r===""||t.push({key:r,name:typeof s=="string"&&s!==""?s:r,problem:l==="invalid"?"invalid":"missing"})}return t}0&&(module.exports={ChaindocEmbed,EmbedInstance,LEGACY_EMBED_ERROR_CODES,TYPED_EMBED_ERROR_CODES,getSigningFieldProblems,isKnownEmbedErrorCode,isTypedEmbedErrorCode});
|
|
52
52
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts"],"sourcesContent":["/**\n * @chaindoc/embed-sdk\n *\n * JavaScript/TypeScript SDK for embedding Chaindoc document signing flow via iframe.\n *\n * @packageDocumentation\n */\n\nexport { ChaindocEmbed } from \"./ChaindocEmbed\";\nexport { EmbedInstance } from \"./EmbedInstance\";\nexport type {\n ChaindocEmbedConfig,\n SignatureFlowOptions,\n Environment,\n DisplayMode,\n Theme,\n Language,\n SignatureSuccessData,\n SignatureErrorData,\n ResendOtpData,\n IframeToSdkMessage,\n SdkToIframeMessage,\n} from \"./types\";\n","/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,kBAAAC,IAAA,eAAAC,EAAAJ,GCSO,SAASK,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,CACF,CAKO,SAASC,EACdD,EACAE,EACAC,EACAC,EACAC,EACAC,EACAC,EACQ,CAER,IAAMC,EAAM,IAAI,IAAI,eAAeN,CAAS,GAAIF,CAAO,EAEjDS,EAAkBN,GAAO,KAAK,EAAE,YAAY,EAClD,OAAIM,GACFD,EAAI,aAAa,IAAI,QAASC,CAAe,EAG3CL,GACFI,EAAI,aAAa,IAAI,OAAQJ,CAAI,EAG/BC,GACFG,EAAI,aAAa,IAAI,QAASH,CAAK,EAGjCC,GACFE,EAAI,aAAa,IAAI,OAAQF,CAAQ,EAGnCC,IAAkB,QACpBC,EAAI,aAAa,IAAI,gBAAiB,OA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KAAK,OAAO,IAAI,kCAAkC,EAElD,QAAWA,KAAY,KAAK,UAC1BA,EAAS,MAAM,EAGjB,KAAK,UAAU,MAAM,CACvB,CAKA,WAAW,SAAkB,CAC3B,MAAO,OACT,CACF","names":["index_exports","__export","ChaindocEmbed","EmbedInstance","__toCommonJS","getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts","../src/errors.ts"],"sourcesContent":["/**\n * @chaindoc/embed-sdk\n *\n * JavaScript/TypeScript SDK for embedding Chaindoc document signing flow via iframe.\n *\n * @packageDocumentation\n */\n\nexport { ChaindocEmbed } from \"./ChaindocEmbed\";\nexport { EmbedInstance } from \"./EmbedInstance\";\nexport type {\n ChaindocEmbedConfig,\n SignatureFlowOptions,\n Environment,\n DisplayMode,\n Theme,\n Language,\n SignatureSuccessData,\n SignatureErrorData,\n ResendOtpData,\n DeclinedData,\n SignatureResult,\n SignatureResultKind,\n SignatureKind,\n IframeToSdkMessage,\n SdkToIframeMessage,\n} from \"./types\";\nexport {\n LEGACY_EMBED_ERROR_CODES,\n TYPED_EMBED_ERROR_CODES,\n isKnownEmbedErrorCode,\n isTypedEmbedErrorCode,\n getSigningFieldProblems,\n} from \"./errors\";\nexport type {\n EmbedErrorCode,\n KnownEmbedErrorCode,\n LegacyEmbedErrorCode,\n TypedEmbedErrorCode,\n SigningFieldProblem,\n} from \"./errors\";\n","/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n hasDeclined: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'DECLINED':\n this.state.hasDeclined = true;\n if ('data' in message) {\n this.options.onDecline?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n","/**\n * Typed error codes of the embedded signing surface (added in 2.3.0).\n *\n * `SignatureErrorData.code` has always been a string. The codes below are the ones the embed reports for the\n * server's typed refusals (each is the backend's `errorKey`, verbatim). An unknown code still reaches `onError`\n * unchanged as a string: new server codes never break an integration.\n */\n\n/** Codes the embed reported before 2.3.0. */\nexport const LEGACY_EMBED_ERROR_CODES = [\n \"SESSION_EXPIRED\",\n \"SESSION_NOT_FOUND\",\n \"INVALID_OTP\",\n \"OTP_EXPIRED\",\n \"DOCUMENT_NOT_FOUND\",\n \"ALREADY_SIGNED\",\n \"NETWORK_ERROR\",\n \"UNAUTHORIZED\",\n \"RATE_LIMITED\",\n \"SIGNATURE_LIMIT_EXCEEDED\",\n \"SUBSCRIPTION_NOT_FOUND\",\n \"USER_NOT_FOUND\",\n \"EMAIL_MISMATCH\",\n \"SESSION_ALREADY_CONFIRMED\",\n \"NO_FILES_PROVIDED\",\n \"SERVER_ERROR\",\n \"UNKNOWN_ERROR\",\n] as const;\n\n/**\n * Typed refusals the embed names (new in 2.3.0). A refused signature reports the server's own `errorKey` verbatim, so a\n * code outside this list can still arrive (for example `KYC_NOT_VERIFIED`, `SIGNER_ALREADY_ACTED`, `SIGNING_REQUEST_EXPIRED`);\n * without a key it is `SERVER_ERROR`, `NETWORK_ERROR`, `RATE_LIMITED`, `UNAUTHORIZED` or `UNKNOWN_ERROR`. A session with\n * nothing to sign reports `EMBEDDED_SIGNING_REQUEST_CLOSED` (a contract's request ended) or `DOCUMENT_NOT_FOUND`.\n */\nexport const TYPED_EMBED_ERROR_CODES = [\n \"NOT_YOUR_TURN\",\n \"ACCOUNT_READ_ONLY\",\n \"KYC_WAITS_FOR_A_UNIT\",\n \"SIGNING_FIELDS_EMPTY\",\n \"SIGNING_METHOD_BELOW_REQUIREMENT\",\n \"INTEGRATIONS_NOT_IN_PLAN\",\n \"PAYMENT_PROVIDER_ERROR\",\n \"PAYMENT_PROVIDER_NOT_CONFIGURED\",\n \"EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED\",\n \"EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED\",\n \"EMBEDDED_SIGNING_REQUEST_CLOSED\",\n \"EMBEDDED_CONTRACT_NOT_SIGNABLE\",\n // A decline's own bounds, as the server says them: the window always asks a reason and checks its length first.\n \"EMBEDDED_DECLINE_REASON_REQUIRED\",\n \"EMBEDDED_DECLINE_REASON_TOO_LONG\",\n // The link no longer opens: the sender re-addressed the signer and this session was revoked; the session's address now\n // belongs to a different account than the one it was issued to. Issue a new session.\n \"SESSION_REVOKED\",\n \"EMBEDDED_SESSION_IDENTITY_STALE\",\n // The signer was refused identity verification for good (`details.rejectType: \"final\"`): they cannot sign this request.\n // Sent once per session, when the window first reads it; the window shows its own final screen and keeps Close.\n \"KYC_REJECTED\",\n] as const;\n\nexport type LegacyEmbedErrorCode = (typeof LEGACY_EMBED_ERROR_CODES)[number];\nexport type TypedEmbedErrorCode = (typeof TYPED_EMBED_ERROR_CODES)[number];\nexport type KnownEmbedErrorCode = LegacyEmbedErrorCode | TypedEmbedErrorCode;\n\n/**\n * Any error code. The known codes autocomplete; a code this SDK version does not know is still a `string`.\n */\nexport type EmbedErrorCode = KnownEmbedErrorCode | (string & Record<never, never>);\n\nconst KNOWN_CODES: readonly string[] = [\n ...LEGACY_EMBED_ERROR_CODES,\n ...TYPED_EMBED_ERROR_CODES,\n];\n\n/** True when `code` is one this SDK version knows by name. */\nexport function isKnownEmbedErrorCode(\n code: unknown,\n): code is KnownEmbedErrorCode {\n return typeof code === \"string\" && KNOWN_CODES.includes(code);\n}\n\n/** True when `code` is one of the typed refusals added in 2.3.0. */\nexport function isTypedEmbedErrorCode(\n code: unknown,\n): code is TypedEmbedErrorCode {\n return (\n typeof code === \"string\" &&\n (TYPED_EMBED_ERROR_CODES as readonly string[]).includes(code)\n );\n}\n\n/** One field a `SIGNING_FIELDS_EMPTY` refusal names. */\nexport interface SigningFieldProblem {\n /** Placement id of the field. */\n key: string;\n /** Field name for display (falls back to `key`). */\n name: string;\n /** `missing`: no value given; `invalid`: a value that does not fit the field. */\n problem: \"missing\" | \"invalid\";\n}\n\n/**\n * The fields a `SIGNING_FIELDS_EMPTY` error names, read from `error.details.fields`.\n * Returns `null` when the error is any other code. A malformed entry is dropped.\n */\nexport function getSigningFieldProblems(error: {\n code: string;\n details?: Record<string, unknown>;\n}): SigningFieldProblem[] | null {\n if (error.code !== \"SIGNING_FIELDS_EMPTY\") return null;\n const raw = error.details?.fields;\n if (!Array.isArray(raw)) return [];\n\n const problems: SigningFieldProblem[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const { key, name, problem } = entry as Record<string, unknown>;\n if (typeof key !== \"string\" || key === \"\") continue;\n problems.push({\n key,\n name: typeof name === \"string\" && name !== \"\" ? name : key,\n problem: problem === \"invalid\" ? \"invalid\" : \"missing\",\n });\n }\n return problems;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,kBAAAC,EAAA,6BAAAC,EAAA,4BAAAC,EAAA,4BAAAC,EAAA,0BAAAC,EAAA,0BAAAC,IAAA,eAAAC,EAAAT,GCSO,SAASU,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,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,EAGP,CAC/B,GAAIA,EAAM,OAAS,uBAAwB,OAAO,KAClD,IAAMC,EAAMD,EAAM,SAAS,OAC3B,GAAI,CAAC,MAAM,QAAQC,CAAG,EAAG,MAAO,CAAC,EAEjC,IAAMC,EAAkC,CAAC,EACzC,QAAWC,KAASF,EAAK,CACvB,GAAI,CAACE,GAAS,OAAOA,GAAU,SAAU,SACzC,GAAM,CAAE,IAAAC,EAAK,KAAAC,EAAM,QAAAC,CAAQ,EAAIH,EAC3B,OAAOC,GAAQ,UAAYA,IAAQ,IACvCF,EAAS,KAAK,CACZ,IAAAE,EACA,KAAM,OAAOC,GAAS,UAAYA,IAAS,GAAKA,EAAOD,EACvD,QAASE,IAAY,UAAY,UAAY,SAC/C,CAAC,CACH,CACA,OAAOJ,CACT","names":["index_exports","__export","ChaindocEmbed","EmbedInstance","LEGACY_EMBED_ERROR_CODES","TYPED_EMBED_ERROR_CODES","getSigningFieldProblems","isKnownEmbedErrorCode","isTypedEmbedErrorCode","__toCommonJS","getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance","LEGACY_EMBED_ERROR_CODES","TYPED_EMBED_ERROR_CODES","KNOWN_CODES","isKnownEmbedErrorCode","code","isTypedEmbedErrorCode","getSigningFieldProblems","error","raw","problems","entry","key","name","problem"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
declare const LEGACY_EMBED_ERROR_CODES: readonly ["SESSION_EXPIRED", "SESSION_NOT_FOUND", "INVALID_OTP", "OTP_EXPIRED", "DOCUMENT_NOT_FOUND", "ALREADY_SIGNED", "NETWORK_ERROR", "UNAUTHORIZED", "RATE_LIMITED", "SIGNATURE_LIMIT_EXCEEDED", "SUBSCRIPTION_NOT_FOUND", "USER_NOT_FOUND", "EMAIL_MISMATCH", "SESSION_ALREADY_CONFIRMED", "NO_FILES_PROVIDED", "SERVER_ERROR", "UNKNOWN_ERROR"];
|
|
2
|
+
declare const TYPED_EMBED_ERROR_CODES: readonly ["NOT_YOUR_TURN", "ACCOUNT_READ_ONLY", "KYC_WAITS_FOR_A_UNIT", "SIGNING_FIELDS_EMPTY", "SIGNING_METHOD_BELOW_REQUIREMENT", "INTEGRATIONS_NOT_IN_PLAN", "PAYMENT_PROVIDER_ERROR", "PAYMENT_PROVIDER_NOT_CONFIGURED", "EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED", "EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED", "EMBEDDED_SIGNING_REQUEST_CLOSED", "EMBEDDED_CONTRACT_NOT_SIGNABLE", "EMBEDDED_DECLINE_REASON_REQUIRED", "EMBEDDED_DECLINE_REASON_TOO_LONG", "SESSION_REVOKED", "EMBEDDED_SESSION_IDENTITY_STALE", "KYC_REJECTED"];
|
|
3
|
+
type LegacyEmbedErrorCode = (typeof LEGACY_EMBED_ERROR_CODES)[number];
|
|
4
|
+
type TypedEmbedErrorCode = (typeof TYPED_EMBED_ERROR_CODES)[number];
|
|
5
|
+
type KnownEmbedErrorCode = LegacyEmbedErrorCode | TypedEmbedErrorCode;
|
|
6
|
+
type EmbedErrorCode = KnownEmbedErrorCode | (string & Record<never, never>);
|
|
7
|
+
declare function isKnownEmbedErrorCode(code: unknown): code is KnownEmbedErrorCode;
|
|
8
|
+
declare function isTypedEmbedErrorCode(code: unknown): code is TypedEmbedErrorCode;
|
|
9
|
+
interface SigningFieldProblem {
|
|
10
|
+
key: string;
|
|
11
|
+
name: string;
|
|
12
|
+
problem: "missing" | "invalid";
|
|
13
|
+
}
|
|
14
|
+
declare function getSigningFieldProblems(error: {
|
|
15
|
+
code: string;
|
|
16
|
+
details?: Record<string, unknown>;
|
|
17
|
+
}): SigningFieldProblem[] | null;
|
|
18
|
+
|
|
1
19
|
type Environment = "production" | "staging" | "development";
|
|
2
20
|
type DisplayMode = "modal" | "inline";
|
|
3
21
|
type Theme = "light" | "dark";
|
|
@@ -23,6 +41,7 @@ interface SignatureFlowOptions {
|
|
|
23
41
|
onSuccess?: (data: SignatureSuccessData) => void;
|
|
24
42
|
onError?: (error: SignatureErrorData) => void;
|
|
25
43
|
onCancel?: () => void;
|
|
44
|
+
onDecline?: (data: DeclinedData) => void;
|
|
26
45
|
onClose?: () => void;
|
|
27
46
|
onResendOtp?: (data: ResendOtpData) => void;
|
|
28
47
|
}
|
|
@@ -31,9 +50,22 @@ interface SignatureSuccessData {
|
|
|
31
50
|
documentId: string;
|
|
32
51
|
signatureId: string;
|
|
33
52
|
signedAt: string;
|
|
53
|
+
result?: SignatureResult;
|
|
54
|
+
signatureKind?: SignatureKind;
|
|
55
|
+
}
|
|
56
|
+
type SignatureResultKind = "document_signature" | "contract_signature" | (string & Record<never, never>);
|
|
57
|
+
type SignatureKind = "simple" | "qualified" | (string & Record<never, never>);
|
|
58
|
+
interface SignatureResult {
|
|
59
|
+
kind: SignatureResultKind;
|
|
60
|
+
}
|
|
61
|
+
interface DeclinedData {
|
|
62
|
+
sessionId: string;
|
|
63
|
+
documentId?: string;
|
|
64
|
+
reason?: string;
|
|
65
|
+
declinedAt?: string;
|
|
34
66
|
}
|
|
35
67
|
interface SignatureErrorData {
|
|
36
|
-
code:
|
|
68
|
+
code: EmbedErrorCode;
|
|
37
69
|
message: string;
|
|
38
70
|
details?: Record<string, unknown>;
|
|
39
71
|
}
|
|
@@ -61,6 +93,10 @@ type IframeToSdkMessage = {
|
|
|
61
93
|
} | {
|
|
62
94
|
source: "chaindoc-embed";
|
|
63
95
|
type: "CANCEL";
|
|
96
|
+
} | {
|
|
97
|
+
source: "chaindoc-embed";
|
|
98
|
+
type: "DECLINED";
|
|
99
|
+
data: DeclinedData;
|
|
64
100
|
} | {
|
|
65
101
|
source: "chaindoc-embed";
|
|
66
102
|
type: "CLOSED";
|
|
@@ -142,4 +178,4 @@ declare class ChaindocEmbed {
|
|
|
142
178
|
static get version(): string;
|
|
143
179
|
}
|
|
144
180
|
|
|
145
|
-
export { ChaindocEmbed, type ChaindocEmbedConfig, type DisplayMode, EmbedInstance, type Environment, type IframeToSdkMessage, type Language, type ResendOtpData, type SdkToIframeMessage, type SignatureErrorData, type SignatureFlowOptions, type SignatureSuccessData, type Theme };
|
|
181
|
+
export { ChaindocEmbed, type ChaindocEmbedConfig, type DeclinedData, type DisplayMode, type EmbedErrorCode, EmbedInstance, type Environment, type IframeToSdkMessage, type KnownEmbedErrorCode, LEGACY_EMBED_ERROR_CODES, type Language, type LegacyEmbedErrorCode, type ResendOtpData, type SdkToIframeMessage, type SignatureErrorData, type SignatureFlowOptions, type SignatureKind, type SignatureResult, type SignatureResultKind, type SignatureSuccessData, type SigningFieldProblem, TYPED_EMBED_ERROR_CODES, type Theme, type TypedEmbedErrorCode, getSigningFieldProblems, isKnownEmbedErrorCode, isTypedEmbedErrorCode };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
declare const LEGACY_EMBED_ERROR_CODES: readonly ["SESSION_EXPIRED", "SESSION_NOT_FOUND", "INVALID_OTP", "OTP_EXPIRED", "DOCUMENT_NOT_FOUND", "ALREADY_SIGNED", "NETWORK_ERROR", "UNAUTHORIZED", "RATE_LIMITED", "SIGNATURE_LIMIT_EXCEEDED", "SUBSCRIPTION_NOT_FOUND", "USER_NOT_FOUND", "EMAIL_MISMATCH", "SESSION_ALREADY_CONFIRMED", "NO_FILES_PROVIDED", "SERVER_ERROR", "UNKNOWN_ERROR"];
|
|
2
|
+
declare const TYPED_EMBED_ERROR_CODES: readonly ["NOT_YOUR_TURN", "ACCOUNT_READ_ONLY", "KYC_WAITS_FOR_A_UNIT", "SIGNING_FIELDS_EMPTY", "SIGNING_METHOD_BELOW_REQUIREMENT", "INTEGRATIONS_NOT_IN_PLAN", "PAYMENT_PROVIDER_ERROR", "PAYMENT_PROVIDER_NOT_CONFIGURED", "EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED", "EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED", "EMBEDDED_SIGNING_REQUEST_CLOSED", "EMBEDDED_CONTRACT_NOT_SIGNABLE", "EMBEDDED_DECLINE_REASON_REQUIRED", "EMBEDDED_DECLINE_REASON_TOO_LONG", "SESSION_REVOKED", "EMBEDDED_SESSION_IDENTITY_STALE", "KYC_REJECTED"];
|
|
3
|
+
type LegacyEmbedErrorCode = (typeof LEGACY_EMBED_ERROR_CODES)[number];
|
|
4
|
+
type TypedEmbedErrorCode = (typeof TYPED_EMBED_ERROR_CODES)[number];
|
|
5
|
+
type KnownEmbedErrorCode = LegacyEmbedErrorCode | TypedEmbedErrorCode;
|
|
6
|
+
type EmbedErrorCode = KnownEmbedErrorCode | (string & Record<never, never>);
|
|
7
|
+
declare function isKnownEmbedErrorCode(code: unknown): code is KnownEmbedErrorCode;
|
|
8
|
+
declare function isTypedEmbedErrorCode(code: unknown): code is TypedEmbedErrorCode;
|
|
9
|
+
interface SigningFieldProblem {
|
|
10
|
+
key: string;
|
|
11
|
+
name: string;
|
|
12
|
+
problem: "missing" | "invalid";
|
|
13
|
+
}
|
|
14
|
+
declare function getSigningFieldProblems(error: {
|
|
15
|
+
code: string;
|
|
16
|
+
details?: Record<string, unknown>;
|
|
17
|
+
}): SigningFieldProblem[] | null;
|
|
18
|
+
|
|
1
19
|
type Environment = "production" | "staging" | "development";
|
|
2
20
|
type DisplayMode = "modal" | "inline";
|
|
3
21
|
type Theme = "light" | "dark";
|
|
@@ -23,6 +41,7 @@ interface SignatureFlowOptions {
|
|
|
23
41
|
onSuccess?: (data: SignatureSuccessData) => void;
|
|
24
42
|
onError?: (error: SignatureErrorData) => void;
|
|
25
43
|
onCancel?: () => void;
|
|
44
|
+
onDecline?: (data: DeclinedData) => void;
|
|
26
45
|
onClose?: () => void;
|
|
27
46
|
onResendOtp?: (data: ResendOtpData) => void;
|
|
28
47
|
}
|
|
@@ -31,9 +50,22 @@ interface SignatureSuccessData {
|
|
|
31
50
|
documentId: string;
|
|
32
51
|
signatureId: string;
|
|
33
52
|
signedAt: string;
|
|
53
|
+
result?: SignatureResult;
|
|
54
|
+
signatureKind?: SignatureKind;
|
|
55
|
+
}
|
|
56
|
+
type SignatureResultKind = "document_signature" | "contract_signature" | (string & Record<never, never>);
|
|
57
|
+
type SignatureKind = "simple" | "qualified" | (string & Record<never, never>);
|
|
58
|
+
interface SignatureResult {
|
|
59
|
+
kind: SignatureResultKind;
|
|
60
|
+
}
|
|
61
|
+
interface DeclinedData {
|
|
62
|
+
sessionId: string;
|
|
63
|
+
documentId?: string;
|
|
64
|
+
reason?: string;
|
|
65
|
+
declinedAt?: string;
|
|
34
66
|
}
|
|
35
67
|
interface SignatureErrorData {
|
|
36
|
-
code:
|
|
68
|
+
code: EmbedErrorCode;
|
|
37
69
|
message: string;
|
|
38
70
|
details?: Record<string, unknown>;
|
|
39
71
|
}
|
|
@@ -61,6 +93,10 @@ type IframeToSdkMessage = {
|
|
|
61
93
|
} | {
|
|
62
94
|
source: "chaindoc-embed";
|
|
63
95
|
type: "CANCEL";
|
|
96
|
+
} | {
|
|
97
|
+
source: "chaindoc-embed";
|
|
98
|
+
type: "DECLINED";
|
|
99
|
+
data: DeclinedData;
|
|
64
100
|
} | {
|
|
65
101
|
source: "chaindoc-embed";
|
|
66
102
|
type: "CLOSED";
|
|
@@ -142,4 +178,4 @@ declare class ChaindocEmbed {
|
|
|
142
178
|
static get version(): string;
|
|
143
179
|
}
|
|
144
180
|
|
|
145
|
-
export { ChaindocEmbed, type ChaindocEmbedConfig, type DisplayMode, EmbedInstance, type Environment, type IframeToSdkMessage, type Language, type ResendOtpData, type SdkToIframeMessage, type SignatureErrorData, type SignatureFlowOptions, type SignatureSuccessData, type Theme };
|
|
181
|
+
export { ChaindocEmbed, type ChaindocEmbedConfig, type DeclinedData, type DisplayMode, type EmbedErrorCode, EmbedInstance, type Environment, type IframeToSdkMessage, type KnownEmbedErrorCode, LEGACY_EMBED_ERROR_CODES, type Language, type LegacyEmbedErrorCode, type ResendOtpData, type SdkToIframeMessage, type SignatureErrorData, type SignatureFlowOptions, type SignatureKind, type SignatureResult, type SignatureResultKind, type SignatureSuccessData, type SigningFieldProblem, TYPED_EMBED_ERROR_CODES, type Theme, type TypedEmbedErrorCode, getSigningFieldProblems, isKnownEmbedErrorCode, isTypedEmbedErrorCode };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function
|
|
1
|
+
function c(i){switch(i){case"production":return"https://embed.chaindoc.io";case"staging":return"https://embed-demo.chaindoc.io";case"development":return"https://embed-demo.chaindoc.io";default:return"https://embed.chaindoc.io"}}function m(i){let e=c(i);try{return new URL(e).origin}catch{return e}}function p(i,e,t,n,r,s,l){let o=new URL(`/embed/sign/${e}`,i),E=t?.trim().toLowerCase();return E&&o.searchParams.set("email",E),n&&o.searchParams.set("mode",n),r&&o.searchParams.set("theme",r),s&&o.searchParams.set("lang",s),l!==void 0&&o.searchParams.set("closeOnEscape",String(l)),o.toString()}function u(i){if(typeof i=="string"){let e=document.querySelector(i);if(!e)throw new Error(`Container element not found: ${i}`);return e}return i}var d=class{constructor(e){this.debug=e}log(...e){this.debug&&console.log("[Chaindoc SDK]",...e)}warn(...e){this.debug&&console.warn("[Chaindoc SDK]",...e)}error(...e){this.debug&&console.error("[Chaindoc SDK]",...e)}};function f(i){return typeof i=="object"&&i!==null&&"source"in i&&i.source==="chaindoc-embed"}function S(i){return`
|
|
2
2
|
position: fixed;
|
|
3
3
|
top: 0;
|
|
4
4
|
left: 0;
|
|
@@ -10,7 +10,7 @@ function d(i){switch(i){case"production":return"https://embed.chaindoc.io";case"
|
|
|
10
10
|
justify-content: center;
|
|
11
11
|
z-index: ${i};
|
|
12
12
|
padding: 20px;
|
|
13
|
-
`.trim()}function
|
|
13
|
+
`.trim()}function v(i,e){return`
|
|
14
14
|
position: relative;
|
|
15
15
|
width: 100%;
|
|
16
16
|
max-width: ${i??450}px;
|
|
@@ -20,7 +20,7 @@ function d(i){switch(i){case"production":return"https://embed.chaindoc.io";case"
|
|
|
20
20
|
border-radius: 12px;
|
|
21
21
|
overflow: hidden;
|
|
22
22
|
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
|
23
|
-
`.trim()}function
|
|
23
|
+
`.trim()}function b(i){let e=`
|
|
24
24
|
width: 100%;
|
|
25
25
|
border: none;
|
|
26
26
|
display: block;
|
|
@@ -31,10 +31,10 @@ function d(i){switch(i){case"production":return"https://embed.chaindoc.io";case"
|
|
|
31
31
|
`.trim():`
|
|
32
32
|
${e}
|
|
33
33
|
height: 0;
|
|
34
|
-
`.trim()}function
|
|
34
|
+
`.trim()}function y(){return`
|
|
35
35
|
position: relative;
|
|
36
36
|
width: 100%;
|
|
37
|
-
`.trim()}var
|
|
37
|
+
`.trim()}var a=class{constructor(e,t,n){this.overlay=null;this.modalContainer=null;this.container=null;this.previousOverflow="";this.isFullscreen=!1;this.previousIframeStyle=null;this.internalEventHandlers=new Map;this.config=e,this.logger=n,this.options=t,this.state={sessionId:this.options.sessionId,mode:this.options.mode||"modal",theme:this.options.theme||"light",isReady:!1,isClosed:!1,hasSucceeded:!1,hasDeclined:!1};let r=c(this.config.environment);this.allowedOrigin=m(this.config.environment);let s=p(r,this.options.sessionId,this.options.email,this.state.mode,this.state.theme,this.options.language,this.options.closeOnEscape);this.iframe=this.createIframe(s),this.messageListener=this.handleMessage.bind(this),window.addEventListener("message",this.messageListener),this.state.mode==="modal"?this.renderModal():this.renderInline(),this.logger.log("Instance created",{sessionId:this.state.sessionId,mode:this.state.mode})}createIframe(e){let t=document.createElement("iframe");return t.src=e,t.setAttribute("style",b(this.state.mode)),t.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-downloads"),t.setAttribute("allow","clipboard-write; camera; microphone; geolocation"),t}renderModal(){if(this.overlay=document.createElement("div"),this.overlay.setAttribute("style",S(this.options.zIndex??999999)),this.overlay.setAttribute("data-chaindoc-overlay","true"),this.modalContainer=document.createElement("div"),this.modalContainer.setAttribute("style",v(this.options.modalWidth,this.options.modalHeight)),this.modalContainer.appendChild(this.iframe),this.overlay.appendChild(this.modalContainer),this.options.closeOnClickOutside!==!1&&this.overlay.addEventListener("click",e=>{e.target===this.overlay&&(this.logger.log("Clicked outside modal - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())}),this.options.closeOnEscape!==!1){let e=t=>{t.key==="Escape"&&(this.logger.log("ESC key pressed - closing"),!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.(),this.close())};document.addEventListener("keydown",e),this._internalOn("close",()=>{document.removeEventListener("keydown",e)})}this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",document.body.appendChild(this.overlay)}renderInline(){if(!this.options.container)throw new Error("Container is required for inline mode");this.container=u(this.options.container);let e=document.createElement("div");e.setAttribute("style",y()),e.setAttribute("data-chaindoc-inline","true"),e.appendChild(this.iframe),this.container.appendChild(e)}handleMessage(e){if(e.origin!==this.allowedOrigin||e.source!==this.iframe.contentWindow||!f(e.data))return;let t=e.data;switch(this.logger.log("Received message:",t.type,t),t.type){case"READY":this.state.isReady=!0,this.options.onReady?.();break;case"RESIZE":"data"in t&&!this.isFullscreen&&(this.iframe.style.height=`${t.data.height}px`);break;case"SUCCESS":this.state.hasSucceeded=!0,"data"in t&&this.options.onSuccess?.(t.data);break;case"ERROR":"data"in t&&this.options.onError?.(t.data);break;case"DECLINED":this.state.hasDeclined=!0,"data"in t&&this.options.onDecline?.(t.data);break;case"CANCEL":!this.state.hasSucceeded&&!this.state.hasDeclined&&this.options.onCancel?.();break;case"CLOSED":this.cleanup();break;case"RESEND_OTP":"data"in t&&this.options.onResendOtp?.(t.data);break;case"REQUEST_FULLSCREEN":this.enterFullscreen();break;case"EXIT_FULLSCREEN":this.exitFullscreen();break;default:this.logger.warn("Unknown message type:",t)}}enterFullscreen(){this.isFullscreen||this.state.isClosed||(this.logger.log("Entering fullscreen"),this.previousIframeStyle=this.iframe.getAttribute("style"),this.iframe.setAttribute("style",`
|
|
38
38
|
position: fixed;
|
|
39
39
|
top: 0;
|
|
40
40
|
left: 0;
|
|
@@ -48,5 +48,5 @@ function d(i){switch(i){case"production":return"https://embed.chaindoc.io";case"
|
|
|
48
48
|
padding: 0;
|
|
49
49
|
display: block;
|
|
50
50
|
z-index: 2147483647;
|
|
51
|
-
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var h=class{constructor(e){this.instances=new Set;if(!e.publicKey)throw new Error("ChaindocEmbed: publicKey is required");if(!e.publicKey.startsWith("pk_"))throw new Error('ChaindocEmbed: publicKey must start with "pk_"');this.config={publicKey:e.publicKey,environment:e.environment||"production",debug:e.debug||!1},this.logger=new
|
|
51
|
+
`.trim()),this.isFullscreen=!0)}exitFullscreen(){this.isFullscreen&&(this.logger.log("Exiting fullscreen"),this.previousIframeStyle!==null?this.iframe.setAttribute("style",this.previousIframeStyle):this.iframe.removeAttribute("style"),this.previousIframeStyle=null,this.isFullscreen=!1)}sendMessage(e){if(!this.iframe.contentWindow){this.logger.error("Cannot send message: iframe contentWindow not available");return}this.iframe.contentWindow.postMessage(e,this.allowedOrigin),this.logger.log("Sent message to iframe:",e.type)}close(){if(this.state.isClosed){this.logger.warn("Instance already closed");return}this.logger.log("Closing instance"),this.sendMessage({source:"chaindoc-embed",type:"CLOSE"}),setTimeout(()=>{this.state.isClosed||(this.logger.warn("Iframe did not respond to CLOSE, forcing cleanup"),this.cleanup())},3e3)}changeTheme(e){this.logger.log("Changing theme to:",e),this.state.theme=e,this.sendMessage({source:"chaindoc-embed",type:"THEME_CHANGE",data:{theme:e}})}isReady(){return this.state.isReady}getSessionId(){return this.state.sessionId}_internalOn(e,t){let n=this.internalEventHandlers.get(e);if(n){n.add(t);return}this.internalEventHandlers.set(e,new Set([t]))}emit(e){let t=this.internalEventHandlers.get(e);t&&t.forEach(n=>n())}cleanup(){this.state.isClosed||(this.logger.log("Cleaning up instance"),this.isFullscreen&&this.exitFullscreen(),this.state.isClosed=!0,window.removeEventListener("message",this.messageListener),this.overlay&&(this.overlay.remove(),document.body.style.overflow=this.previousOverflow),this.container&&this.container.querySelector("[data-chaindoc-inline]")?.remove(),this.options.onClose?.(),this.emit("close"),this.internalEventHandlers.clear())}};var h=class{constructor(e){this.instances=new Set;if(!e.publicKey)throw new Error("ChaindocEmbed: publicKey is required");if(!e.publicKey.startsWith("pk_"))throw new Error('ChaindocEmbed: publicKey must start with "pk_"');this.config={publicKey:e.publicKey,environment:e.environment||"production",debug:e.debug||!1},this.logger=new d(this.config.debug),this.logger.log("SDK initialized",this.config)}openSignatureFlow(e){if(!e.sessionId)throw new Error("openSignatureFlow: sessionId is required");if(!e.sessionId.startsWith("ses_"))throw new Error('openSignatureFlow: sessionId must start with "ses_"');if((e.mode||"modal")==="inline"&&!e.container)throw new Error("openSignatureFlow: container is required for inline mode");this.logger.log("Opening signature flow",e);let n=new a(this.config,e,this.logger);return this.instances.add(n),n._internalOn("close",()=>{this.instances.delete(n)}),n}destroy(){this.logger.log("Destroying SDK and all instances");for(let e of this.instances)e.close();this.instances.clear()}static get version(){return"2.4.0"}};var _=["SESSION_EXPIRED","SESSION_NOT_FOUND","INVALID_OTP","OTP_EXPIRED","DOCUMENT_NOT_FOUND","ALREADY_SIGNED","NETWORK_ERROR","UNAUTHORIZED","RATE_LIMITED","SIGNATURE_LIMIT_EXCEEDED","SUBSCRIPTION_NOT_FOUND","USER_NOT_FOUND","EMAIL_MISMATCH","SESSION_ALREADY_CONFIRMED","NO_FILES_PROVIDED","SERVER_ERROR","UNKNOWN_ERROR"],g=["NOT_YOUR_TURN","ACCOUNT_READ_ONLY","KYC_WAITS_FOR_A_UNIT","SIGNING_FIELDS_EMPTY","SIGNING_METHOD_BELOW_REQUIREMENT","INTEGRATIONS_NOT_IN_PLAN","PAYMENT_PROVIDER_ERROR","PAYMENT_PROVIDER_NOT_CONFIGURED","EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED","EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED","EMBEDDED_SIGNING_REQUEST_CLOSED","EMBEDDED_CONTRACT_NOT_SIGNABLE","EMBEDDED_DECLINE_REASON_REQUIRED","EMBEDDED_DECLINE_REASON_TOO_LONG","SESSION_REVOKED","EMBEDDED_SESSION_IDENTITY_STALE","KYC_REJECTED"],C=[..._,...g];function I(i){return typeof i=="string"&&C.includes(i)}function D(i){return typeof i=="string"&&g.includes(i)}function w(i){if(i.code!=="SIGNING_FIELDS_EMPTY")return null;let e=i.details?.fields;if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!="object")continue;let{key:r,name:s,problem:l}=n;typeof r!="string"||r===""||t.push({key:r,name:typeof s=="string"&&s!==""?s:r,problem:l==="invalid"?"invalid":"missing"})}return t}export{h as ChaindocEmbed,a as EmbedInstance,_ as LEGACY_EMBED_ERROR_CODES,g as TYPED_EMBED_ERROR_CODES,w as getSigningFieldProblems,I as isKnownEmbedErrorCode,D as isTypedEmbedErrorCode};
|
|
52
52
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts"],"sourcesContent":["/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n"],"mappings":"AASO,SAASA,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,CACF,CAKO,SAASC,EACdD,EACAE,EACAC,EACAC,EACAC,EACAC,EACAC,EACQ,CAER,IAAMC,EAAM,IAAI,IAAI,eAAeN,CAAS,GAAIF,CAAO,EAEjDS,EAAkBN,GAAO,KAAK,EA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ACF,EAGF,KAAK,OAAO,IAAI,yBAA0BA,CAAO,EAGjD,IAAMC,EAAW,IAAIC,EAAc,KAAK,OAAQF,EAAS,KAAK,MAAM,EAGpE,YAAK,UAAU,IAAIC,CAAQ,EAG3BA,EAAS,YAAY,QAAS,IAAM,CAClC,KAAK,UAAU,OAAOA,CAAQ,CAChC,CAAC,EAEMA,CACT,CAKA,SAAgB,CACd,KAAK,OAAO,IAAI,kCAAkC,EAElD,QAAWA,KAAY,KAAK,UAC1BA,EAAS,MAAM,EAGjB,KAAK,UAAU,MAAM,CACvB,CAKA,WAAW,SAAkB,CAC3B,MAAO,OACT,CACF","names":["getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/styles.ts","../src/EmbedInstance.ts","../src/ChaindocEmbed.ts","../src/errors.ts"],"sourcesContent":["/**\n * Utility functions for Chaindoc Embed SDK\n */\n\nimport type { DisplayMode, Environment } from \"./types\";\n\n/**\n * Get the iframe base URL based on environment\n */\nexport function getIframeBaseUrl(environment: Environment): string {\n switch (environment) {\n case \"production\":\n return \"https://embed.chaindoc.io\";\n case \"staging\":\n return \"https://embed-demo.chaindoc.io\";\n case \"development\":\n return \"https://embed-demo.chaindoc.io\";\n default:\n return \"https://embed.chaindoc.io\";\n }\n}\n\n/**\n * Get allowed origin for postMessage validation\n */\nexport function getAllowedOrigin(environment: Environment): string {\n const baseUrl = getIframeBaseUrl(environment);\n try {\n const url = new URL(baseUrl);\n return url.origin;\n } catch {\n return baseUrl;\n }\n}\n\n/**\n * Build iframe URL with query parameters\n */\nexport function buildIframeUrl(\n baseUrl: string,\n sessionId: string,\n email?: string,\n mode?: DisplayMode,\n theme?: string,\n language?: string,\n closeOnEscape?: boolean\n): string {\n // Session ID goes into the path, not as a query parameter\n const url = new URL(`/embed/sign/${sessionId}`, baseUrl);\n\n const normalizedEmail = email?.trim().toLowerCase();\n if (normalizedEmail) {\n url.searchParams.set(\"email\", normalizedEmail);\n }\n\n if (mode) {\n url.searchParams.set(\"mode\", mode);\n }\n\n if (theme) {\n url.searchParams.set(\"theme\", theme);\n }\n\n if (language) {\n url.searchParams.set(\"lang\", language);\n }\n\n if (closeOnEscape !== undefined) {\n url.searchParams.set(\"closeOnEscape\", String(closeOnEscape));\n }\n\n return url.toString();\n}\n\n/**\n * Resolve container element from HTMLElement or selector string\n */\nexport function resolveContainer(container: HTMLElement | string): HTMLElement {\n if (typeof container === \"string\") {\n const element = document.querySelector<HTMLElement>(container);\n if (!element) {\n throw new Error(`Container element not found: ${container}`);\n }\n return element;\n }\n return container;\n}\n\n/**\n * Debug logger (only logs when debug mode is enabled)\n */\nexport class Logger {\n constructor(private debug: boolean) {}\n\n log(...args: unknown[]): void {\n if (this.debug) {\n console.log(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n warn(...args: unknown[]): void {\n if (this.debug) {\n console.warn(\"[Chaindoc SDK]\", ...args);\n }\n }\n\n error(...args: unknown[]): void {\n if (this.debug) {\n console.error(\"[Chaindoc SDK]\", ...args);\n }\n }\n}\n\n/**\n * Type guard to check if a message is from Chaindoc iframe\n */\nexport function isChaindocMessage(\n message: unknown\n): message is { source: \"chaindoc-embed\" } {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"source\" in message &&\n message.source === \"chaindoc-embed\"\n );\n}\n","/**\n * CSS-in-JS styles for modal and inline modes\n */\n\n/**\n * Get styles for modal overlay\n */\nexport function getOverlayStyles(zIndex: number): string {\n return `\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: ${zIndex};\n padding: 20px;\n `.trim();\n}\n\n/**\n * Get styles for modal container\n */\nexport function getModalContainerStyles(\n width?: number,\n height?: number\n): string {\n const modalWidth = width ?? 450;\n const modalHeight = height ?? 850;\n\n return `\n position: relative;\n width: 100%;\n max-width: ${modalWidth}px;\n height: ${modalHeight}px;\n max-height: 90vh;\n background: white;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n `.trim();\n}\n\n/**\n * Get styles for iframe (common for both modal and inline)\n */\nexport function getIframeStyles(mode: \"modal\" | \"inline\"): string {\n const baseStyles = `\n width: 100%;\n border: none;\n display: block;\n `.trim();\n\n if (mode === \"modal\") {\n return `\n ${baseStyles}\n height: 100%;\n min-height: 400px;\n `.trim();\n }\n\n // Inline mode\n return `\n ${baseStyles}\n height: 0;\n `.trim();\n}\n\n/**\n * Get styles for inline container wrapper\n */\nexport function getInlineContainerStyles(): string {\n return `\n position: relative;\n width: 100%;\n `.trim();\n}\n","/**\n * Instance class for managing individual signature flows\n */\n\nimport type {\n SignatureFlowOptions,\n Theme,\n IframeToSdkMessage,\n SdkToIframeMessage,\n InstanceState,\n Environment,\n} from './types';\nimport {\n getIframeBaseUrl,\n getAllowedOrigin,\n buildIframeUrl,\n resolveContainer,\n isChaindocMessage,\n Logger,\n} from './utils';\nimport {\n getOverlayStyles,\n getModalContainerStyles,\n getIframeStyles,\n getInlineContainerStyles,\n} from './styles';\n\n/**\n * Internal config interface for EmbedInstance\n */\ninterface InternalConfig {\n publicKey: string;\n environment: Environment;\n debug: boolean;\n}\n\ntype InternalEventHandler = () => void;\n\n/**\n * Represents a single signature flow instance\n *\n * @example\n * ```typescript\n * const instance = sdk.openSignatureFlow({ sessionId: 'ses_xxx' });\n * instance.changeTheme('dark');\n * instance.close();\n * ```\n */\nexport class EmbedInstance {\n private config: InternalConfig;\n private options: SignatureFlowOptions;\n private logger: Logger;\n\n private state: InstanceState;\n private iframe: HTMLIFrameElement;\n private overlay: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private container: HTMLElement | null = null;\n\n private allowedOrigin: string;\n private messageListener: (event: MessageEvent) => void;\n private previousOverflow: string = '';\n\n private isFullscreen: boolean = false;\n private previousIframeStyle: string | null = null;\n\n private internalEventHandlers: Map<string, Set<InternalEventHandler>> = new Map();\n\n constructor(\n config: InternalConfig,\n options: SignatureFlowOptions,\n logger: Logger\n ) {\n this.config = config;\n this.logger = logger;\n\n // Store options\n this.options = options;\n\n // Initialize state\n this.state = {\n sessionId: this.options.sessionId,\n mode: this.options.mode || 'modal',\n theme: this.options.theme || 'light',\n isReady: false,\n isClosed: false,\n hasSucceeded: false,\n hasDeclined: false,\n };\n\n // Calculate allowed origin\n const baseUrl = getIframeBaseUrl(this.config.environment);\n this.allowedOrigin = getAllowedOrigin(this.config.environment);\n\n // Build iframe URL\n const iframeUrl = buildIframeUrl(\n baseUrl,\n this.options.sessionId,\n this.options.email,\n this.state.mode,\n this.state.theme,\n this.options.language,\n this.options.closeOnEscape\n );\n\n // Create iframe\n this.iframe = this.createIframe(iframeUrl);\n\n // Setup message listener\n this.messageListener = this.handleMessage.bind(this);\n window.addEventListener('message', this.messageListener);\n\n // Render based on mode\n if (this.state.mode === 'modal') {\n this.renderModal();\n } else {\n this.renderInline();\n }\n\n this.logger.log('Instance created', { sessionId: this.state.sessionId, mode: this.state.mode });\n }\n\n /**\n * Create iframe element\n */\n private createIframe(url: string): HTMLIFrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n iframe.setAttribute('style', getIframeStyles(this.state.mode));\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-downloads'\n );\n // Permissions for KYC verification (camera/microphone for liveness check, geolocation optional)\n iframe.setAttribute('allow', 'clipboard-write; camera; microphone; geolocation');\n return iframe;\n }\n\n /**\n * Render modal mode\n */\n private renderModal(): void {\n // Create overlay\n this.overlay = document.createElement('div');\n this.overlay.setAttribute('style', getOverlayStyles(this.options.zIndex ?? 999999));\n this.overlay.setAttribute('data-chaindoc-overlay', 'true');\n\n // Create modal container\n this.modalContainer = document.createElement('div');\n this.modalContainer.setAttribute(\n 'style',\n getModalContainerStyles(this.options.modalWidth, this.options.modalHeight)\n );\n this.modalContainer.appendChild(this.iframe);\n\n // Add container to overlay\n this.overlay.appendChild(this.modalContainer);\n\n // Click outside to cancel and close (configurable, default: true)\n if (this.options.closeOnClickOutside !== false) {\n this.overlay.addEventListener('click', (e) => {\n if (e.target === this.overlay) {\n this.logger.log('Clicked outside modal - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n });\n }\n\n // ESC key to cancel and close (configurable, default: true)\n if (this.options.closeOnEscape !== false) {\n const handleEscape = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n this.logger.log('ESC key pressed - closing');\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n this.close();\n }\n };\n document.addEventListener('keydown', handleEscape);\n\n // Store cleanup\n this._internalOn('close', () => {\n document.removeEventListener('keydown', handleEscape);\n });\n }\n\n // Lock body scroll (preserve previous value for restoration)\n this.previousOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n\n // Append to body\n document.body.appendChild(this.overlay);\n }\n\n /**\n * Render inline mode\n */\n private renderInline(): void {\n if (!this.options.container) {\n throw new Error('Container is required for inline mode');\n }\n\n // Resolve container\n this.container = resolveContainer(this.options.container);\n\n // Create wrapper\n const wrapper = document.createElement('div');\n wrapper.setAttribute('style', getInlineContainerStyles());\n wrapper.setAttribute('data-chaindoc-inline', 'true');\n wrapper.appendChild(this.iframe);\n\n // Inject into container\n this.container.appendChild(wrapper);\n }\n\n /**\n * Handle incoming postMessage events\n */\n private handleMessage(event: MessageEvent): void {\n // Validate origin and source (ensure message comes from our iframe, not another iframe with same origin)\n if (event.origin !== this.allowedOrigin || event.source !== this.iframe.contentWindow) {\n return;\n }\n\n // Validate message structure\n if (!isChaindocMessage(event.data)) {\n return;\n }\n\n const message = event.data as IframeToSdkMessage;\n this.logger.log('Received message:', message.type, message);\n\n // Handle message by type\n switch (message.type) {\n case 'READY':\n this.state.isReady = true;\n this.options.onReady?.();\n break;\n\n case 'RESIZE':\n if ('data' in message && !this.isFullscreen) {\n this.iframe.style.height = `${message.data.height}px`;\n }\n break;\n\n case 'SUCCESS':\n this.state.hasSucceeded = true;\n if ('data' in message) {\n this.options.onSuccess?.(message.data);\n }\n break;\n\n case 'ERROR':\n if ('data' in message) {\n this.options.onError?.(message.data);\n }\n break;\n\n case 'DECLINED':\n this.state.hasDeclined = true;\n if ('data' in message) {\n this.options.onDecline?.(message.data);\n }\n break;\n\n case 'CANCEL':\n if (!this.state.hasSucceeded && !this.state.hasDeclined) {\n this.options.onCancel?.();\n }\n break;\n\n case 'CLOSED':\n this.cleanup();\n break;\n\n case 'RESEND_OTP':\n if ('data' in message) {\n this.options.onResendOtp?.(message.data);\n }\n break;\n\n case 'REQUEST_FULLSCREEN':\n this.enterFullscreen();\n break;\n\n case 'EXIT_FULLSCREEN':\n this.exitFullscreen();\n break;\n\n default:\n this.logger.warn('Unknown message type:', message);\n }\n }\n\n /**\n * Expand iframe to cover the entire parent viewport.\n * Works uniformly in modal and inline modes, including iOS Safari\n * (does not rely on the native Fullscreen API).\n *\n * Parent body.overflow is intentionally NOT modified here: it is brittle\n * (easy to leak a `hidden` lock back to the host page if the restore path\n * is missed). Scroll-chaining from the fullscreen iframe is handled inside\n * the iframe itself via `overscroll-behavior: contain` on the scroll area.\n */\n private enterFullscreen(): void {\n if (this.isFullscreen || this.state.isClosed) {\n return;\n }\n\n this.logger.log('Entering fullscreen');\n\n this.previousIframeStyle = this.iframe.getAttribute('style');\n\n this.iframe.setAttribute(\n 'style',\n `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n border: 0;\n border-radius: 0;\n margin: 0;\n padding: 0;\n display: block;\n z-index: 2147483647;\n `.trim()\n );\n\n this.isFullscreen = true;\n }\n\n /**\n * Restore iframe to its previous size and position.\n */\n private exitFullscreen(): void {\n if (!this.isFullscreen) {\n return;\n }\n\n this.logger.log('Exiting fullscreen');\n\n if (this.previousIframeStyle !== null) {\n this.iframe.setAttribute('style', this.previousIframeStyle);\n } else {\n this.iframe.removeAttribute('style');\n }\n this.previousIframeStyle = null;\n\n this.isFullscreen = false;\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: SdkToIframeMessage): void {\n if (!this.iframe.contentWindow) {\n this.logger.error('Cannot send message: iframe contentWindow not available');\n return;\n }\n\n this.iframe.contentWindow.postMessage(message, this.allowedOrigin);\n this.logger.log('Sent message to iframe:', message.type);\n }\n\n /**\n * Close the signature flow\n */\n close(): void {\n if (this.state.isClosed) {\n this.logger.warn('Instance already closed');\n return;\n }\n\n this.logger.log('Closing instance');\n\n // Send CLOSE message to iframe\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'CLOSE',\n });\n\n // Force cleanup after timeout if iframe doesn't respond\n setTimeout(() => {\n if (!this.state.isClosed) {\n this.logger.warn('Iframe did not respond to CLOSE, forcing cleanup');\n this.cleanup();\n }\n }, 3000);\n }\n\n /**\n * Change theme\n */\n changeTheme(theme: Theme): void {\n this.logger.log('Changing theme to:', theme);\n\n this.state.theme = theme;\n\n this.sendMessage({\n source: 'chaindoc-embed',\n type: 'THEME_CHANGE',\n data: { theme },\n });\n }\n\n /**\n * Check if iframe is ready\n */\n isReady(): boolean {\n return this.state.isReady;\n }\n\n /**\n * Get session ID\n */\n getSessionId(): string {\n return this.state.sessionId;\n }\n\n /**\n * Internal event system (for cleanup tracking)\n * @internal\n */\n _internalOn(event: string, handler: InternalEventHandler): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.add(handler);\n return;\n }\n\n this.internalEventHandlers.set(event, new Set([handler]));\n }\n\n private emit(event: string): void {\n const handlers = this.internalEventHandlers.get(event);\n if (handlers) {\n handlers.forEach((handler) => handler());\n }\n }\n\n /**\n * Cleanup all resources\n */\n private cleanup(): void {\n if (this.state.isClosed) {\n return;\n }\n\n this.logger.log('Cleaning up instance');\n\n // Restore body overflow if we are destroyed while fullscreen is active\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n\n this.state.isClosed = true;\n\n // Remove message listener\n window.removeEventListener('message', this.messageListener);\n\n // Remove DOM elements\n if (this.overlay) {\n this.overlay.remove();\n document.body.style.overflow = this.previousOverflow;\n }\n\n if (this.container) {\n const wrapper = this.container.querySelector('[data-chaindoc-inline]');\n wrapper?.remove();\n }\n\n // Call onClose callback\n this.options.onClose?.();\n\n // Emit internal close event\n this.emit('close');\n\n // Clear internal handlers\n this.internalEventHandlers.clear();\n }\n}\n","/**\n * Main SDK class for Chaindoc Embed\n */\n\nimport { EmbedInstance } from \"./EmbedInstance\";\nimport type { ChaindocEmbedConfig, SignatureFlowOptions } from \"./types\";\nimport { Logger } from \"./utils\";\n\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Main entry point for Chaindoc Embed SDK\n *\n * @example\n * ```typescript\n * const sdk = new ChaindocEmbed({\n * publicKey: 'pk_test_xxx',\n * environment: 'development',\n * debug: true\n * });\n *\n * const instance = sdk.openSignatureFlow({\n * sessionId: 'ses_xxx',\n * onSuccess: (data) => console.log('Signed!', data)\n * });\n * ```\n */\n/**\n * Internal config type with defaults applied\n */\ninterface InternalConfig {\n publicKey: string;\n environment: \"production\" | \"staging\" | \"development\";\n debug: boolean;\n}\n\nexport class ChaindocEmbed {\n private config: InternalConfig;\n private logger: Logger;\n private instances: Set<EmbedInstance> = new Set();\n\n /**\n * Create a new ChaindocEmbed instance\n *\n * @param config - SDK configuration\n * @throws {Error} If publicKey is missing or invalid\n */\n constructor(config: ChaindocEmbedConfig) {\n // Validate required config\n if (!config.publicKey) {\n throw new Error(\"ChaindocEmbed: publicKey is required\");\n }\n\n if (!config.publicKey.startsWith(\"pk_\")) {\n throw new Error('ChaindocEmbed: publicKey must start with \"pk_\"');\n }\n\n // Set defaults\n this.config = {\n publicKey: config.publicKey,\n environment: config.environment || \"production\",\n debug: config.debug || false,\n };\n\n this.logger = new Logger(this.config.debug);\n this.logger.log(\"SDK initialized\", this.config);\n }\n\n /**\n * Open a signature flow\n *\n * @param options - Signature flow options\n * @returns EmbedInstance for controlling the flow\n * @throws {Error} If sessionId is missing or invalid\n * @throws {Error} If inline mode is used without container\n */\n openSignatureFlow(options: SignatureFlowOptions): EmbedInstance {\n // Validate required options\n if (!options.sessionId) {\n throw new Error(\"openSignatureFlow: sessionId is required\");\n }\n\n if (!options.sessionId.startsWith(\"ses_\")) {\n throw new Error('openSignatureFlow: sessionId must start with \"ses_\"');\n }\n\n const mode = options.mode || \"modal\";\n\n if (mode === \"inline\" && !options.container) {\n throw new Error(\n \"openSignatureFlow: container is required for inline mode\"\n );\n }\n\n this.logger.log(\"Opening signature flow\", options);\n\n // Create instance\n const instance = new EmbedInstance(this.config, options, this.logger);\n\n // Track instance\n this.instances.add(instance);\n\n // Remove from tracking when closed\n instance._internalOn(\"close\", () => {\n this.instances.delete(instance);\n });\n\n return instance;\n }\n\n /**\n * Destroy all instances and cleanup\n */\n destroy(): void {\n this.logger.log(\"Destroying SDK and all instances\");\n\n for (const instance of this.instances) {\n instance.close();\n }\n\n this.instances.clear();\n }\n\n /**\n * Get SDK version\n */\n static get version(): string {\n return __SDK_VERSION__;\n }\n}\n","/**\n * Typed error codes of the embedded signing surface (added in 2.3.0).\n *\n * `SignatureErrorData.code` has always been a string. The codes below are the ones the embed reports for the\n * server's typed refusals (each is the backend's `errorKey`, verbatim). An unknown code still reaches `onError`\n * unchanged as a string: new server codes never break an integration.\n */\n\n/** Codes the embed reported before 2.3.0. */\nexport const LEGACY_EMBED_ERROR_CODES = [\n \"SESSION_EXPIRED\",\n \"SESSION_NOT_FOUND\",\n \"INVALID_OTP\",\n \"OTP_EXPIRED\",\n \"DOCUMENT_NOT_FOUND\",\n \"ALREADY_SIGNED\",\n \"NETWORK_ERROR\",\n \"UNAUTHORIZED\",\n \"RATE_LIMITED\",\n \"SIGNATURE_LIMIT_EXCEEDED\",\n \"SUBSCRIPTION_NOT_FOUND\",\n \"USER_NOT_FOUND\",\n \"EMAIL_MISMATCH\",\n \"SESSION_ALREADY_CONFIRMED\",\n \"NO_FILES_PROVIDED\",\n \"SERVER_ERROR\",\n \"UNKNOWN_ERROR\",\n] as const;\n\n/**\n * Typed refusals the embed names (new in 2.3.0). A refused signature reports the server's own `errorKey` verbatim, so a\n * code outside this list can still arrive (for example `KYC_NOT_VERIFIED`, `SIGNER_ALREADY_ACTED`, `SIGNING_REQUEST_EXPIRED`);\n * without a key it is `SERVER_ERROR`, `NETWORK_ERROR`, `RATE_LIMITED`, `UNAUTHORIZED` or `UNKNOWN_ERROR`. A session with\n * nothing to sign reports `EMBEDDED_SIGNING_REQUEST_CLOSED` (a contract's request ended) or `DOCUMENT_NOT_FOUND`.\n */\nexport const TYPED_EMBED_ERROR_CODES = [\n \"NOT_YOUR_TURN\",\n \"ACCOUNT_READ_ONLY\",\n \"KYC_WAITS_FOR_A_UNIT\",\n \"SIGNING_FIELDS_EMPTY\",\n \"SIGNING_METHOD_BELOW_REQUIREMENT\",\n \"INTEGRATIONS_NOT_IN_PLAN\",\n \"PAYMENT_PROVIDER_ERROR\",\n \"PAYMENT_PROVIDER_NOT_CONFIGURED\",\n \"EMBEDDED_PAYMENT_METHOD_NOT_REQUIRED\",\n \"EMBEDDED_PAYMENT_METHOD_ALREADY_LINKED\",\n \"EMBEDDED_SIGNING_REQUEST_CLOSED\",\n \"EMBEDDED_CONTRACT_NOT_SIGNABLE\",\n // A decline's own bounds, as the server says them: the window always asks a reason and checks its length first.\n \"EMBEDDED_DECLINE_REASON_REQUIRED\",\n \"EMBEDDED_DECLINE_REASON_TOO_LONG\",\n // The link no longer opens: the sender re-addressed the signer and this session was revoked; the session's address now\n // belongs to a different account than the one it was issued to. Issue a new session.\n \"SESSION_REVOKED\",\n \"EMBEDDED_SESSION_IDENTITY_STALE\",\n // The signer was refused identity verification for good (`details.rejectType: \"final\"`): they cannot sign this request.\n // Sent once per session, when the window first reads it; the window shows its own final screen and keeps Close.\n \"KYC_REJECTED\",\n] as const;\n\nexport type LegacyEmbedErrorCode = (typeof LEGACY_EMBED_ERROR_CODES)[number];\nexport type TypedEmbedErrorCode = (typeof TYPED_EMBED_ERROR_CODES)[number];\nexport type KnownEmbedErrorCode = LegacyEmbedErrorCode | TypedEmbedErrorCode;\n\n/**\n * Any error code. The known codes autocomplete; a code this SDK version does not know is still a `string`.\n */\nexport type EmbedErrorCode = KnownEmbedErrorCode | (string & Record<never, never>);\n\nconst KNOWN_CODES: readonly string[] = [\n ...LEGACY_EMBED_ERROR_CODES,\n ...TYPED_EMBED_ERROR_CODES,\n];\n\n/** True when `code` is one this SDK version knows by name. */\nexport function isKnownEmbedErrorCode(\n code: unknown,\n): code is KnownEmbedErrorCode {\n return typeof code === \"string\" && KNOWN_CODES.includes(code);\n}\n\n/** True when `code` is one of the typed refusals added in 2.3.0. */\nexport function isTypedEmbedErrorCode(\n code: unknown,\n): code is TypedEmbedErrorCode {\n return (\n typeof code === \"string\" &&\n (TYPED_EMBED_ERROR_CODES as readonly string[]).includes(code)\n );\n}\n\n/** One field a `SIGNING_FIELDS_EMPTY` refusal names. */\nexport interface SigningFieldProblem {\n /** Placement id of the field. */\n key: string;\n /** Field name for display (falls back to `key`). */\n name: string;\n /** `missing`: no value given; `invalid`: a value that does not fit the field. */\n problem: \"missing\" | \"invalid\";\n}\n\n/**\n * The fields a `SIGNING_FIELDS_EMPTY` error names, read from `error.details.fields`.\n * Returns `null` when the error is any other code. A malformed entry is dropped.\n */\nexport function getSigningFieldProblems(error: {\n code: string;\n details?: Record<string, unknown>;\n}): SigningFieldProblem[] | null {\n if (error.code !== \"SIGNING_FIELDS_EMPTY\") return null;\n const raw = error.details?.fields;\n if (!Array.isArray(raw)) return [];\n\n const problems: SigningFieldProblem[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const { key, name, problem } = entry as Record<string, unknown>;\n if (typeof key !== \"string\" || key === \"\") continue;\n problems.push({\n key,\n name: typeof name === \"string\" && name !== \"\" ? name : key,\n problem: problem === \"invalid\" ? \"invalid\" : \"missing\",\n });\n }\n return problems;\n}\n"],"mappings":"AASO,SAASA,EAAiBC,EAAkC,CACjE,OAAQA,EAAa,CACnB,IAAK,aACH,MAAO,4BACT,IAAK,UACH,MAAO,iCACT,IAAK,cACH,MAAO,iCACT,QACE,MAAO,2BACX,CACF,CAKO,SAASC,EAAiBD,EAAkC,CACjE,IAAME,EAAUH,EAAiBC,CAAW,EAC5C,GAAI,CAEF,OADY,IAAI,IAAIE,CAAO,EAChB,MACb,MAAQ,CACN,OAAOA,CACT,CACF,CAKO,SAASC,EACdD,EACAE,EACAC,EACAC,EACAC,EACAC,EACAC,EACQ,CAER,IAAMC,EAAM,IAAI,IAAI,eAAeN,CAAS,GAAIF,CAAO,EAEjDS,EAAkBN,GAAO,KAAK,EAAE,YAAY,EAClD,OAAIM,GACFD,EAAI,aAAa,IAAI,QAASC,CAAe,EAG3CL,GACFI,EAAI,aAAa,IAAI,OAAQJ,CAAI,EAG/BC,GACFG,EAAI,aAAa,IAAI,QAASH,CAAK,EAGjCC,GACFE,EAAI,aAAa,IAAI,OAAQF,CAAQ,EAGnCC,IAAkB,QACpBC,EAAI,aAAa,IAAI,gBAAiB,OAAOD,CAAa,CAAC,EAGtDC,EAAI,SAAS,CACtB,CAKO,SAASE,EAAiBC,EAA8C,CAC7E,GAAI,OAAOA,GAAc,SAAU,CACjC,IAAMC,EAAU,SAAS,cAA2BD,CAAS,EAC7D,G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AOA,CAAQ,CAChC,CAAC,EAEMA,CACT,CAKA,SAAgB,CACd,KAAK,OAAO,IAAI,kCAAkC,EAElD,QAAWA,KAAY,KAAK,UAC1BA,EAAS,MAAM,EAGjB,KAAK,UAAU,MAAM,CACvB,CAKA,WAAW,SAAkB,CAC3B,MAAO,OACT,CACF,ECxHO,IAAME,EAA2B,CACtC,kBACA,oBACA,cACA,cACA,qBACA,iBACA,gBACA,eACA,eACA,2BACA,yBACA,iBACA,iBACA,4BACA,oBACA,eACA,eACF,EAQaC,EAA0B,CACrC,gBACA,oBACA,uBACA,uBACA,mCACA,2BACA,yBACA,kCACA,uCACA,yCACA,kCACA,iCAEA,mCACA,mCAGA,kBACA,kCAGA,cACF,EAWMC,EAAiC,CACrC,GAAGF,EACH,GAAGC,CACL,EAGO,SAASE,EACdC,EAC6B,CAC7B,OAAO,OAAOA,GAAS,UAAYF,EAAY,SAASE,CAAI,CAC9D,CAGO,SAASC,EACdD,EAC6B,CAC7B,OACE,OAAOA,GAAS,UACfH,EAA8C,SAASG,CAAI,CAEhE,CAgBO,SAASE,EAAwBC,EAGP,CAC/B,GAAIA,EAAM,OAAS,uBAAwB,OAAO,KAClD,IAAMC,EAAMD,EAAM,SAAS,OAC3B,GAAI,CAAC,MAAM,QAAQC,CAAG,EAAG,MAAO,CAAC,EAEjC,IAAMC,EAAkC,CAAC,EACzC,QAAWC,KAASF,EAAK,CACvB,GAAI,CAACE,GAAS,OAAOA,GAAU,SAAU,SACzC,GAAM,CAAE,IAAAC,EAAK,KAAAC,EAAM,QAAAC,CAAQ,EAAIH,EAC3B,OAAOC,GAAQ,UAAYA,IAAQ,IACvCF,EAAS,KAAK,CACZ,IAAAE,EACA,KAAM,OAAOC,GAAS,UAAYA,IAAS,GAAKA,EAAOD,EACvD,QAASE,IAAY,UAAY,UAAY,SAC/C,CAAC,CACH,CACA,OAAOJ,CACT","names":["getIframeBaseUrl","environment","getAllowedOrigin","baseUrl","buildIframeUrl","sessionId","email","mode","theme","language","closeOnEscape","url","normalizedEmail","resolveContainer","container","element","Logger","debug","args","isChaindocMessage","message","getOverlayStyles","zIndex","getModalContainerStyles","width","height","getIframeStyles","mode","baseStyles","getInlineContainerStyles","EmbedInstance","config","options","logger","baseUrl","getIframeBaseUrl","getAllowedOrigin","iframeUrl","buildIframeUrl","url","iframe","getIframeStyles","getOverlayStyles","getModalContainerStyles","handleEscape","e","resolveContainer","wrapper","getInlineContainerStyles","event","isChaindocMessage","message","theme","handler","handlers","ChaindocEmbed","config","Logger","options","instance","EmbedInstance","LEGACY_EMBED_ERROR_CODES","TYPED_EMBED_ERROR_CODES","KNOWN_CODES","isKnownEmbedErrorCode","code","isTypedEmbedErrorCode","getSigningFieldProblems","error","raw","problems","entry","key","name","problem"]}
|
package/package.json
CHANGED