react-native-docusign 1.0.3

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/LICENSE +21 -0
  3. package/README.md +867 -0
  4. package/android/build.gradle +81 -0
  5. package/android/src/main/AndroidManifest.xml +7 -0
  6. package/android/src/main/java/expo/modules/docusign/DocuSignError.kt +18 -0
  7. package/android/src/main/java/expo/modules/docusign/DocuSignManager.kt +321 -0
  8. package/android/src/main/java/expo/modules/docusign/DocuSignModule.kt +190 -0
  9. package/app.plugin.js +1 -0
  10. package/build/DocuSign.types.d.ts +77 -0
  11. package/build/DocuSign.types.d.ts.map +1 -0
  12. package/build/DocuSign.types.js +2 -0
  13. package/build/DocuSign.types.js.map +1 -0
  14. package/build/DocuSignModule.d.ts +14 -0
  15. package/build/DocuSignModule.d.ts.map +1 -0
  16. package/build/DocuSignModule.js +3 -0
  17. package/build/DocuSignModule.js.map +1 -0
  18. package/build/api.d.ts +39 -0
  19. package/build/api.d.ts.map +1 -0
  20. package/build/api.js +62 -0
  21. package/build/api.js.map +1 -0
  22. package/build/index.d.ts +6 -0
  23. package/build/index.d.ts.map +1 -0
  24. package/build/index.js +5 -0
  25. package/build/index.js.map +1 -0
  26. package/build/useDocuSignSigning.d.ts +38 -0
  27. package/build/useDocuSignSigning.d.ts.map +1 -0
  28. package/build/useDocuSignSigning.js +126 -0
  29. package/build/useDocuSignSigning.js.map +1 -0
  30. package/expo-module.config.json +9 -0
  31. package/ios/DocuSignError.swift +31 -0
  32. package/ios/DocuSignManager.swift +776 -0
  33. package/ios/DocuSignModule.swift +169 -0
  34. package/ios/ReactNativeDocuSign.podspec +29 -0
  35. package/package.json +60 -0
  36. package/plugin/build/index.d.ts +8 -0
  37. package/plugin/build/index.js +235 -0
  38. package/plugin/build/index.js.map +1 -0
package/README.md ADDED
@@ -0,0 +1,867 @@
1
+ # react-native-docusign
2
+
3
+ [![npm version](https://img.shields.io/npm/v/react-native-docusign.svg?style=flat-square)](https://www.npmjs.com/package/react-native-docusign)
4
+ [![npm downloads](https://img.shields.io/npm/dm/react-native-docusign.svg?style=flat-square)](https://www.npmjs.com/package/react-native-docusign)
5
+ [![license](https://img.shields.io/npm/l/react-native-docusign.svg?style=flat-square)](LICENSE)
6
+ [![platforms](https://img.shields.io/badge/platform-ios%20%7C%20android-blue?style=flat-square)](#)
7
+ [![types](https://img.shields.io/badge/types-TypeScript-blue?style=flat-square)](#)
8
+ [![Expo SDK](https://img.shields.io/badge/Expo%20SDK-55%2B-000020?style=flat-square&logo=expo)](https://docs.expo.dev/)
9
+
10
+ React Native / Expo native module that wraps the official DocuSign iOS and Android SDKs, allowing apps to present the native DocuSign signing UI directly in-app (captive signing).
11
+
12
+ Built on the Expo Modules API. Works with Expo SDK 55+, bare React Native, and Expo Dev Client.
13
+
14
+ > **Unofficial package.** This is a community wrapper. It is not affiliated with or endorsed by DocuSign, Inc. "DocuSign" is a trademark of DocuSign, Inc.
15
+
16
+ ## iOS ↔ Android parity
17
+
18
+ | Flow | iOS | Android |
19
+ |-------------------------------------------------------------------------|:---:|:-------:|
20
+ | Session flow: `initialize` → `loginWithAccessToken` → `presentCaptiveSigning` | ✅ | ✅ |
21
+ | URL flow: `presentCaptiveSigningWithUrl` | ✅ | ❌ |
22
+
23
+ The DocuSign Android SDK (2.1.4) does not expose a public URL-based signing entry point; calling `presentCaptiveSigningWithUrl` on Android rejects with `not_implemented`. **Default to the session flow for cross-platform apps.**
24
+
25
+ ## One backend response, both platforms
26
+
27
+ Both iOS and Android consume the **same 13-field session payload** from your backend. There is no platform-specific branching on the client. Mint it once on your BFF, hand it to the module, and the same code path runs on both OSes.
28
+
29
+ The mobile module expects exactly these fields:
30
+
31
+ `integratorKey`, `environment`, `accessToken`, `expiresIn`, `host`, `accountId`, `userId`, `userName`, `email`, `envelopeId`, `clientUserId`, `recipientName`, `recipientEmail`.
32
+
33
+ Full schema and BFF reference implementation: [`docs/BACKEND_GUIDE.md` → Session Payload Contract](docs/BACKEND_GUIDE.md#session-payload-contract).
34
+
35
+ ## Table of contents
36
+
37
+ - [Features](#features)
38
+ - [How it works](#how-it-works)
39
+ - [Platform requirements](#platform-requirements)
40
+ - [SDK bundling policy](#sdk-bundling-policy)
41
+ - [Installation](#installation)
42
+ - [Config plugin](#config-plugin)
43
+ - [Quick start](#quick-start)
44
+ - [API reference](#api-reference)
45
+ - [initialize](#initializeconfig-docusignconfig-promisevoid)
46
+ - [loginWithAccessToken](#loginwithaccesstokenparams-docusignauthparams-promisevoid)
47
+ - [presentCaptiveSigning](#presentcaptivesigningparams-captivesigningparams-promisesigningresult)
48
+ - [presentCaptiveSigningWithUrl](#presentcaptivesigningwithurlparams-captivesigningurlparams-promisesigningresult)
49
+ - [logout](#logout-promisevoid)
50
+ - [isLoggedIn](#isloggedin-promiseboolean)
51
+ - [endSigningSession](#endsigningsession-promisevoid)
52
+ - [Event listeners](#event-listeners)
53
+ - [Types](#types)
54
+ - [Authentication flow](#authentication-flow)
55
+ - [Prefilling document fields](#prefilling-document-fields)
56
+ - [Multi-document / multi-envelope chaining](#multi-document--multi-envelope-chaining)
57
+ - [Error handling](#error-handling)
58
+ - [Security considerations](#security-considerations)
59
+ - [Permissions](#permissions)
60
+ - [Troubleshooting](#troubleshooting)
61
+ - [Compatibility matrix](#compatibility-matrix)
62
+ - [Limitations](#limitations)
63
+ - [FAQ](#faq)
64
+ - [License](#license)
65
+
66
+ ## Features
67
+
68
+ - Native in-app captive (embedded) signing on iOS and Android
69
+ - Full native DocuSign signing UI, including document viewer, form fields, signature pad, initials, date picker, attachments, and dropdowns
70
+ - OAuth access token authentication (JWT Grant handled on your backend)
71
+ - Promise-based API plus event listeners for completion, cancellation, and errors
72
+ - Config plugin that automatically configures iOS Info.plist, Android permissions, and Android Maven repo
73
+ - TypeScript-first public API with strict types
74
+ - No WebView dependency, no HTML bridges, no hybrid UI
75
+
76
+ ## How it works
77
+
78
+ At a high level, a signing flow looks like this:
79
+
80
+ 1. Your backend creates a DocuSign envelope from a template (prefilling any known fields) and returns a short-lived access token plus envelope metadata to the mobile app.
81
+ 2. The mobile app calls `initialize()` once (on app start or on-demand) to configure the DocuSign SDK.
82
+ 3. The app calls `loginWithAccessToken()` with the session data from your backend.
83
+ 4. The app calls `presentCaptiveSigning()`. The DocuSign SDK takes over the screen and presents its own native signing UI.
84
+ 5. The user reviews the document, fills any remaining fields, and signs.
85
+ 6. The SDK dismisses itself. The promise resolves (or an event fires) with the final signing status.
86
+ 7. Your backend confirms the signing status via a DocuSign Connect webhook (server-side source of truth).
87
+
88
+ The React Native layer never renders any of the signing UI. It only triggers the flow, passes credentials to the SDK, and listens for completion events.
89
+
90
+ ## Platform requirements
91
+
92
+ | Platform | Minimum OS | SDK version | Language |
93
+ | -------- | -------------------- | -------------------------- | ----------- |
94
+ | iOS | 15.1 | DocuSign iOS SDK 4.1.1 | Swift 5.9 |
95
+ | Android | API 24 (Android 7.0) | DocuSign Android SDK 2.1.4 | Kotlin 1.8+ |
96
+
97
+ **Runtime requirements:**
98
+
99
+ - Expo SDK 55 or newer, OR bare React Native 0.74+
100
+ - React Native New Architecture (Fabric + Hermes): supported, no additional configuration
101
+ - Expo Go: NOT supported (custom native modules require a development build)
102
+
103
+ ## SDK bundling policy
104
+
105
+ The DocuSign native SDKs are **NOT bundled** inside this npm package. They are declared as external dependencies and resolved at consumer build time:
106
+
107
+ - **iOS**: `pod 'DocuSign-iOS-SDK', '~> 4.1.1'` from the public CocoaPods trunk
108
+ - **Android**: `com.docusign:androidsdk:2.1.4` from DocuSign's Maven repository (the config plugin adds the repo automatically)
109
+
110
+ ### Android Glide collision workaround
111
+
112
+ DocuSign's `com.docusign:sdk-pdf:2.1.4` AAR ships a pre-generated `com.bumptech.glide.GeneratedAppGlideModuleImpl.class` that collides at dex time with any other Glide-based library in the host app (notably `expo-image`, `react-native-fast-image`, and similar). To avoid this without redistributing DocuSign's binary, the Expo Config Plugin downloads `sdk-pdf-2.1.4.aar` directly from DocuSign's public Maven during `expo prebuild`, removes the offending class in-memory, and writes the stripped artifact to `node_modules/react-native-docusign/android/libs/`. The existing flatDir injection picks it up at consumer build time. The download is cached after the first run.
113
+
114
+ ### What ships inside this package
115
+
116
+ - TypeScript source + type definitions
117
+ - Swift + Kotlin bridge source files
118
+ - Podspec and gradle config
119
+ - Config plugin compiled output
120
+ - README, CHANGELOG, LICENSE
121
+
122
+ Estimated package size: under 1 MB.
123
+
124
+ ### What does NOT ship inside this package
125
+
126
+ - DocuSign iOS xcframework binaries
127
+ - DocuSign Android AAR binaries
128
+ - Any DocuSign proprietary code
129
+
130
+ ### Why not bundle the SDKs
131
+
132
+ 1. **Distribution model**: DocuSign publishes the SDKs via CocoaPods and their own Maven repository. Consumers' builds resolve them directly and accept DocuSign's terms at install time, the standard native dependency pattern.
133
+ 2. **Size**: Keeps this npm package tiny.
134
+ 3. **Updates**: Consumers can bump DocuSign SDK versions via CocoaPods / Gradle independently of this wrapper.
135
+ 4. **Legal clarity**: Referencing SDK coordinates rather than shipping binaries keeps this wrapper cleanly MIT and avoids ambiguity about DocuSign's proprietary artifacts.
136
+
137
+ ## Installation
138
+
139
+ ### 1. Install the package
140
+
141
+ ```bash
142
+ npm install react-native-docusign
143
+ # or
144
+ yarn add react-native-docusign
145
+ # or
146
+ pnpm add react-native-docusign
147
+ ```
148
+
149
+ ### 2. Add the config plugin
150
+
151
+ In `app.config.ts` (or `app.json`):
152
+
153
+ ```ts
154
+ export default {
155
+ expo: {
156
+ // ...
157
+ plugins: [
158
+ [
159
+ 'react-native-docusign',
160
+ {
161
+ cameraPermission: 'Allows you to sign DocuSign documents using your camera.',
162
+ photoPermission: 'Allows you to attach photos to DocuSign documents.',
163
+ },
164
+ ],
165
+ ],
166
+ },
167
+ };
168
+ ```
169
+
170
+ ### 3. Rebuild the development client
171
+
172
+ ```bash
173
+ npx expo prebuild --clean
174
+ npx expo run:ios
175
+ npx expo run:android
176
+ ```
177
+
178
+ ### Bare React Native (without Expo prebuild)
179
+
180
+ If you are not using Expo prebuild, you must manually:
181
+
182
+ - **iOS**: add `pod 'DocuSign-iOS-SDK', '~> 4.1.1'` to your Podfile and run `pod install`
183
+ - **Android**: add the Maven repo and the DocuSign dependency to your `android/build.gradle` + `android/app/build.gradle`
184
+ - **iOS**: add the `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` keys to your `Info.plist`
185
+ - **Android**: add the required permissions to your `AndroidManifest.xml`
186
+
187
+ See the [Permissions](#permissions) section for exact values.
188
+
189
+ ## Config plugin
190
+
191
+ The config plugin accepts the following props:
192
+
193
+ ```ts
194
+ type DocuSignPluginProps = {
195
+ /**
196
+ * Value written to NSCameraUsageDescription in Info.plist.
197
+ * Defaults to a generic DocuSign-appropriate message.
198
+ */
199
+ cameraPermission?: string;
200
+
201
+ /**
202
+ * Value written to NSPhotoLibraryUsageDescription in Info.plist.
203
+ * Defaults to a generic DocuSign-appropriate message.
204
+ */
205
+ photoPermission?: string;
206
+
207
+ /**
208
+ * URL of the Android Maven repository that serves the DocuSign Android SDK.
209
+ * Defaults to 'https://maven.docusign.com/'.
210
+ * Override only if DocuSign moves their repo.
211
+ */
212
+ androidMavenRepo?: string;
213
+ };
214
+ ```
215
+
216
+ What the plugin does during `expo prebuild`:
217
+
218
+ - **iOS**: writes `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` to `Info.plist`
219
+ - **Android**: adds `INTERNET`, `ACCESS_NETWORK_STATE`, and `CAMERA` permissions to `AndroidManifest.xml`
220
+ - **Android**: injects the DocuSign Maven repository into the project-level `build.gradle` under `allprojects { repositories { ... } }`
221
+
222
+ ## Quick start
223
+
224
+ ```ts
225
+ import * as DocuSign from 'react-native-docusign';
226
+
227
+ async function signAgreement() {
228
+ // Step 1: configure the SDK (call once per app lifetime)
229
+ await DocuSign.initialize({
230
+ integratorKey: 'YOUR_INTEGRATOR_KEY',
231
+ environment: 'demo', // or 'production'
232
+ });
233
+
234
+ // Step 2: fetch a signing session from your backend
235
+ const session = await fetch('/api/envelopes/signing-session', {
236
+ method: 'POST',
237
+ headers: { 'Content-Type': 'application/json' },
238
+ body: JSON.stringify({ documentId: 'doc_123', requestType: 'standard' }),
239
+ }).then((r) => r.json());
240
+
241
+ // Step 3: authenticate the SDK
242
+ await DocuSign.loginWithAccessToken({
243
+ accessToken: session.accessToken,
244
+ accountId: session.accountId,
245
+ userId: session.userId,
246
+ userName: session.userName,
247
+ email: session.email,
248
+ host: session.host, // 'https://demo.docusign.net/restapi'
249
+ });
250
+
251
+ // Step 4: present the native signing UI
252
+ const result = await DocuSign.presentCaptiveSigning({
253
+ envelopeId: session.envelopeId,
254
+ recipientUserName: session.userName,
255
+ recipientEmail: session.email,
256
+ recipientClientUserId: session.recipientClientUserId,
257
+ });
258
+
259
+ switch (result.status) {
260
+ case 'completed':
261
+ console.log('Signed:', result.envelopeId);
262
+ break;
263
+ case 'cancelled':
264
+ console.log('User cancelled signing');
265
+ break;
266
+ case 'error':
267
+ console.error('Signing error:', result.errorMessage);
268
+ break;
269
+ }
270
+ }
271
+ ```
272
+
273
+ ## API reference
274
+
275
+ ### `initialize(config: DocuSignConfig): Promise<void>`
276
+
277
+ Configures the underlying DocuSign SDK. Must be called once before any other function. Safe to call multiple times (subsequent calls are no-ops).
278
+
279
+ ```ts
280
+ type DocuSignConfig = {
281
+ integratorKey: string;
282
+ environment: 'demo' | 'production';
283
+ };
284
+ ```
285
+
286
+ **Parameters:**
287
+
288
+ - `integratorKey`: your DocuSign Integrator Key (Client ID). Can be fetched from your backend at runtime to avoid shipping it in the app bundle.
289
+ - `environment`: `'demo'` targets `demo.docusign.net` (DocuSign developer sandbox). `'production'` targets `docusign.net`.
290
+
291
+ **Throws:** rejects if the SDK cannot be initialized.
292
+
293
+ ### `loginWithAccessToken(params: DocuSignAuthParams): Promise<void>`
294
+
295
+ Authenticates the SDK with a short-lived access token obtained from your backend (via DocuSign JWT Grant).
296
+
297
+ ```ts
298
+ type DocuSignAuthParams = {
299
+ accessToken: string;
300
+ accountId: string;
301
+ userId: string;
302
+ userName: string;
303
+ email: string;
304
+ host: string;
305
+ };
306
+ ```
307
+
308
+ **Parameters:**
309
+
310
+ - `accessToken`: OAuth 2.0 access token from DocuSign
311
+ - `accountId`: DocuSign account ID (GUID)
312
+ - `userId`: DocuSign user ID (GUID)
313
+ - `userName`: display name for the signer
314
+ - `email`: email address for the signer
315
+ - `host`: DocuSign API host URL (e.g. `'https://demo.docusign.net/restapi'`)
316
+
317
+ **Throws:** rejects with `login_failed` if the token is invalid, expired, or rejected by DocuSign.
318
+
319
+ **Notes:** access tokens from DocuSign are typically valid for 1 hour. Do not cache them client-side. Fetch a fresh token for each signing session.
320
+
321
+ ### `presentCaptiveSigning(params: CaptiveSigningParams): Promise<SigningResult>`
322
+
323
+ Presents the native DocuSign signing UI on top of your React Native app. The returned promise resolves when the user completes or cancels signing.
324
+
325
+ ```ts
326
+ type CaptiveSigningParams = {
327
+ envelopeId: string;
328
+ recipientUserName: string;
329
+ recipientEmail: string;
330
+ recipientClientUserId: string;
331
+ };
332
+
333
+ type SigningResult = {
334
+ status: 'completed' | 'cancelled' | 'error';
335
+ envelopeId: string;
336
+ errorCode?: string;
337
+ errorMessage?: string;
338
+ };
339
+ ```
340
+
341
+ **Parameters:**
342
+
343
+ - `envelopeId`: the DocuSign envelope ID created by your backend
344
+ - `recipientUserName`, `recipientEmail`: must match the recipient registered on the envelope
345
+ - `recipientClientUserId`: the `clientUserId` of the embedded recipient, used by DocuSign to identify captive signers
346
+
347
+ **Throws:** rejects with `signing_failed` if the SDK fails to present the signing UI (e.g. not initialized, not logged in, invalid envelope).
348
+
349
+ **Returns:** resolves with a `SigningResult` once the user completes or cancels. `status === 'completed'` means the user finished the signing ceremony. `status === 'cancelled'` means the user explicitly cancelled or closed the signing UI.
350
+
351
+ ### `presentCaptiveSigningWithUrl(params: CaptiveSigningUrlParams): Promise<SigningResult>`
352
+
353
+ **iOS only.** Presents the DocuSign signing UI using a pre-minted recipient view URL (obtained server-side from `POST /envelopes/{id}/views/recipient`). Bypasses SDK authentication; no `initialize` / `loginWithAccessToken` required first.
354
+
355
+ ```ts
356
+ type CaptiveSigningUrlParams = {
357
+ signingUrl: string;
358
+ envelopeId: string;
359
+ recipientId?: string;
360
+ };
361
+ ```
362
+
363
+ **Parameters:**
364
+
365
+ - `signingUrl`: short-lived recipient view URL from your backend (~5 min TTL, single use)
366
+ - `envelopeId`: the DocuSign envelope ID
367
+ - `recipientId` (optional): identifier used for event correlation
368
+
369
+ **Throws:**
370
+
371
+ - `not_implemented` on Android (see [Limitations](#limitations))
372
+ - `signing_failed` if the URL is expired, malformed, or rejected by DocuSign
373
+
374
+ **Returns:** same `SigningResult` shape as `presentCaptiveSigning`.
375
+
376
+ **Why this flow:** keeps the DocuSign access token out of the mobile app entirely; your backend mints the signing URL and hands that single-use credential to the client. Recommended for production iOS flows.
377
+
378
+ ### `logout(): Promise<void>`
379
+
380
+ Logs out of the DocuSign SDK and clears any cached credentials. Call this when the user signs out of your app.
381
+
382
+ ### `isLoggedIn(): Promise<boolean>`
383
+
384
+ Returns the current login state. Useful for deciding whether to skip the login step on a subsequent signing attempt.
385
+
386
+ ### `endSigningSession(): Promise<void>`
387
+
388
+ Tears down any in-flight signing session and the underlying SDK auth state so the next `loginWithAccessToken` + `presentCaptiveSigning` pair starts from a clean slate. Safe to call when no session is active.
389
+
390
+ Call this between captive signing flows (e.g. inside the `finally` block of your orchestrator) when running multiple envelopes in the same app session. Without it, the package falls back to an implicit teardown inside `performLogin` which has historically (≤ 1.0.1) raced on iOS and caused the captive signing UI to hang on a spinner on the second consecutive open. The 1.0.2 fix sequences that teardown correctly, but calling `endSigningSession` explicitly remains the cleanest pattern.
391
+
392
+ The `useDocuSignSigning` hook's `reset()` calls this automatically when the SDK has been initialized.
393
+
394
+ ### Event listeners
395
+
396
+ In addition to the promise-based API, you can subscribe to events. Events fire for every signing result, including those triggered from other parts of your app.
397
+
398
+ ```ts
399
+ const completeSub = DocuSign.addSigningCompleteListener((event) => {
400
+ console.log('Signed envelope:', event.envelopeId);
401
+ });
402
+
403
+ const cancelSub = DocuSign.addSigningCancelledListener((event) => {
404
+ console.log('Cancelled:', event.envelopeId, event.reason);
405
+ });
406
+
407
+ const errorSub = DocuSign.addSigningErrorListener((event) => {
408
+ console.error('Error:', event.errorCode, event.errorMessage);
409
+ });
410
+
411
+ // Later, clean up:
412
+ completeSub.remove();
413
+ cancelSub.remove();
414
+ errorSub.remove();
415
+ ```
416
+
417
+ In React hooks:
418
+
419
+ ```ts
420
+ import { useEffect } from 'react';
421
+
422
+ import * as DocuSign from 'react-native-docusign';
423
+
424
+ useEffect(() => {
425
+ const sub = DocuSign.addSigningCompleteListener((event) => {
426
+ refetchEnvelopeStatus(event.envelopeId);
427
+ });
428
+ return () => sub.remove();
429
+ }, []);
430
+ ```
431
+
432
+ ## Hook API
433
+
434
+ For React consumers, the package exports a `useDocuSignSigning` hook that wraps the SDK lifecycle, the state machine, and event subscription so you do not have to implement them yourself.
435
+
436
+ ### Usage
437
+
438
+ ```tsx
439
+ import { useDocuSignSigning } from 'react-native-docusign';
440
+
441
+ function SigningScreen() {
442
+ const { state, error, result, startSigning } = useDocuSignSigning({
443
+ config: {
444
+ integratorKey: 'YOUR_INTEGRATOR_KEY',
445
+ environment: 'demo',
446
+ },
447
+ });
448
+
449
+ async function handleSign() {
450
+ // Fetch the signing session from your backend
451
+ const session = await fetchSigningSessionFromYourBackend();
452
+
453
+ // Hook handles loginWithAccessToken + presentCaptiveSigning + state transitions
454
+ const result = await startSigning(session);
455
+
456
+ if (result.status === 'completed') {
457
+ // Navigate to confirmation
458
+ }
459
+ }
460
+
461
+ return (
462
+ <View>
463
+ {state === 'initializing' && <Text>Setting up DocuSign...</Text>}
464
+ {state === 'ready' && <Button title="Sign document" onPress={handleSign} />}
465
+ {state === 'preparing' && <ActivityIndicator />}
466
+ {state === 'signing' && <Text>Opening signing UI...</Text>}
467
+ {state === 'completed' && <Text>Signed envelope {result?.envelopeId}</Text>}
468
+ {state === 'cancelled' && <Text>Signing cancelled</Text>}
469
+ {state === 'error' && <Text>Error: {error?.message}</Text>}
470
+ </View>
471
+ );
472
+ }
473
+ ```
474
+
475
+ ### What the hook does for you
476
+
477
+ - Calls `initialize()` automatically on mount (toggle with `autoInitialize: false` if you want to defer)
478
+ - Accepts both signing flows via a discriminated union on `startSigning(session)`:
479
+ - `{ type: 'session', ... }`: runs `loginWithAccessToken` + `presentCaptiveSigning` (iOS + Android)
480
+ - `{ type: 'url', ... }`: runs `presentCaptiveSigningWithUrl` (iOS only; throws on Android)
481
+ - Tracks SDK state in a finite state machine
482
+ - Subscribes to error events and surfaces them in the `error` field
483
+ - Cleans up event listeners on unmount
484
+
485
+ ### URL-flow example (iOS)
486
+
487
+ ```tsx
488
+ const result = await startSigning({
489
+ type: 'url',
490
+ signingUrl: sessionFromBackend.signingUrl,
491
+ envelopeId: sessionFromBackend.envelopeId,
492
+ });
493
+ ```
494
+
495
+ ### Session-flow example (iOS + Android)
496
+
497
+ ```tsx
498
+ const result = await startSigning({
499
+ type: 'session',
500
+ accessToken: sessionFromBackend.accessToken,
501
+ accountId: sessionFromBackend.accountId,
502
+ userId: sessionFromBackend.userId,
503
+ userName: sessionFromBackend.userName,
504
+ email: sessionFromBackend.email,
505
+ host: sessionFromBackend.host,
506
+ envelopeId: sessionFromBackend.envelopeId,
507
+ recipientUserName: sessionFromBackend.userName,
508
+ recipientEmail: sessionFromBackend.email,
509
+ recipientClientUserId: sessionFromBackend.recipientClientUserId,
510
+ });
511
+ ```
512
+
513
+ ### What stays YOUR responsibility
514
+
515
+ - Fetching the signing session from your backend (every consumer has a different backend)
516
+ - Form state collection (request details, addresses, dates) BEFORE calling `startSigning`
517
+ - Multi-envelope chaining UX (call `startSigning` again with a fresh session)
518
+ - Navigation between screens
519
+
520
+ ### State machine
521
+
522
+ ```
523
+ idle ──auto-init──> initializing ──> ready ──startSigning──> preparing ──> signing ──> completed
524
+ │ │
525
+ │ └─> cancelled
526
+ │ │
527
+ └────────────── error <───── any failure ──────── └─> error
528
+ ```
529
+
530
+ ### Reference
531
+
532
+ ```ts
533
+ type DocuSignSigningState =
534
+ | 'idle' // hook just mounted, initialization not started
535
+ | 'initializing' // initialize() in progress
536
+ | 'ready' // SDK ready, can call startSigning
537
+ | 'preparing' // loginWithAccessToken in progress
538
+ | 'signing' // native signing UI is presented
539
+ | 'completed' // user finished signing successfully
540
+ | 'cancelled' // user cancelled signing
541
+ | 'error'; // any failure
542
+
543
+ type SigningSessionWithAuth = DocuSignAuthParams & CaptiveSigningParams & { type: 'session' };
544
+ type SigningSessionWithUrl = CaptiveSigningUrlParams & { type: 'url' };
545
+ type SigningSession = SigningSessionWithAuth | SigningSessionWithUrl;
546
+
547
+ type UseDocuSignSigningOptions = {
548
+ config: DocuSignConfig;
549
+ autoInitialize?: boolean; // default true
550
+ };
551
+
552
+ type UseDocuSignSigningReturn = {
553
+ state: DocuSignSigningState;
554
+ error: Error | null;
555
+ result: SigningResult | null;
556
+ initialize: () => Promise<void>; // manual init if autoInitialize=false
557
+ startSigning: (session: SigningSession) => Promise<SigningResult>;
558
+ reset: () => void; // back to idle/ready, clears error and result
559
+ };
560
+ ```
561
+
562
+ ### When NOT to use the hook
563
+
564
+ If you need fine-grained control over the SDK lifecycle (e.g., re-using login across multiple screens, or custom error recovery flows), use the lower-level functions directly: `initialize`, `loginWithAccessToken`, `presentCaptiveSigning`. The hook is opinionated and may not fit every flow.
565
+
566
+ ## Types
567
+
568
+ ```ts
569
+ export type DocuSignEnvironment = 'demo' | 'production';
570
+
571
+ export type DocuSignConfig = {
572
+ integratorKey: string;
573
+ environment: DocuSignEnvironment;
574
+ };
575
+
576
+ export type DocuSignAuthParams = {
577
+ accessToken: string;
578
+ accountId: string;
579
+ userId: string;
580
+ userName: string;
581
+ email: string;
582
+ host: string;
583
+ };
584
+
585
+ export type CaptiveSigningParams = {
586
+ envelopeId: string;
587
+ recipientUserName: string;
588
+ recipientEmail: string;
589
+ recipientClientUserId: string;
590
+ };
591
+
592
+ export type SigningStatus = 'completed' | 'cancelled' | 'error';
593
+
594
+ export type SigningResult = {
595
+ status: SigningStatus;
596
+ envelopeId: string;
597
+ errorCode?: string;
598
+ errorMessage?: string;
599
+ };
600
+
601
+ export type SigningCompleteEvent = {
602
+ envelopeId: string;
603
+ };
604
+
605
+ export type SigningCancelledEvent = {
606
+ envelopeId: string;
607
+ reason?: string;
608
+ };
609
+
610
+ export type SigningErrorEvent = {
611
+ envelopeId?: string;
612
+ errorCode: string;
613
+ errorMessage: string;
614
+ };
615
+ ```
616
+
617
+ ## Authentication flow
618
+
619
+ This package does NOT implement DocuSign JWT Grant authentication. JWT Grant must happen on your backend because it requires access to an RSA private key that should never ship on mobile devices.
620
+
621
+ Recommended flow:
622
+
623
+ ```
624
+ Mobile app Your backend DocuSign
625
+ ---------- ------------ --------
626
+ 1. Request signing --->
627
+ 2. JWT Grant ------------->
628
+ 3. Access token <----------
629
+ 4. Create envelope -------->
630
+ 5. Envelope ID <----------
631
+ <-- Signing session data
632
+
633
+ 6. initialize()
634
+ 7. loginWithAccessToken()
635
+ 8. presentCaptiveSigning()
636
+ [Native SDK UI]
637
+ 9. Complete/cancel event
638
+
639
+ 10. Confirm status --->
640
+ 11. Verify via webhook ---->
641
+ 12. Confirmed <---------
642
+ ```
643
+
644
+ The mobile app **never stores DocuSign tokens**. Access tokens are fetched per signing session, used immediately, and discarded. Your backend must perform authorization checks before issuing a signing session for a given envelope.
645
+
646
+ For information on DocuSign JWT Grant auth on the backend, see https://developers.docusign.com/platform/auth/jwt/.
647
+
648
+ ## Prefilling document fields
649
+
650
+ The SDK itself does not provide an API to prefill document fields. Prefilling happens **server-side** when the envelope is created.
651
+
652
+ When your backend calls DocuSign's REST API `POST /accounts/{accountId}/envelopes`, it should set tab values on the envelope:
653
+
654
+ - `textTabs`: text fields
655
+ - `checkboxTabs`: checkboxes
656
+ - `dateTabs`: date pickers
657
+ - `dropdownTabs` (alias `listTabs`): dropdown selections
658
+ - `signHereTabs`: signature placement (leave empty for user to sign)
659
+ - `initialHereTabs`: initial placement
660
+
661
+ When the mobile app then calls `presentCaptiveSigning()`, the user will see the document with all server-prefilled fields already populated. They only need to fill remaining fields and sign.
662
+
663
+ Example (backend, pseudo-code):
664
+
665
+ ```ts
666
+ const envelope = await docusign.envelopes.create({
667
+ templateId: 'template_agreement_v1',
668
+ templateRoles: [
669
+ {
670
+ email: 'user@example.com',
671
+ name: 'Jane Doe',
672
+ roleName: 'signer',
673
+ clientUserId: 'user_123',
674
+ tabs: {
675
+ textTabs: [
676
+ { tabLabel: 'request_type', value: 'standard' },
677
+ { tabLabel: 'counterparty', value: 'Acme Corp.' },
678
+ { tabLabel: 'mailing_address', value: '123 Main St, Anytown, USA' },
679
+ ],
680
+ dateTabs: [{ tabLabel: 'effective_date', value: '2026-05-01' }],
681
+ },
682
+ },
683
+ ],
684
+ status: 'sent',
685
+ });
686
+ ```
687
+
688
+ ## Multi-document / multi-envelope chaining
689
+
690
+ Because the DocuSign SDK returns control to your app after each signing ceremony, you can easily chain multiple signings in sequence:
691
+
692
+ ```ts
693
+ async function signMultipleDocuments(documents: Document[]) {
694
+ const results: SigningResult[] = [];
695
+
696
+ for (const document of documents) {
697
+ const session = await fetchSigningSession(document.id);
698
+ await DocuSign.loginWithAccessToken(session);
699
+ const result = await DocuSign.presentCaptiveSigning({
700
+ envelopeId: session.envelopeId,
701
+ recipientUserName: session.userName,
702
+ recipientEmail: session.email,
703
+ recipientClientUserId: session.recipientClientUserId,
704
+ });
705
+ results.push(result);
706
+
707
+ if (result.status !== 'completed') break;
708
+ }
709
+
710
+ return results;
711
+ }
712
+ ```
713
+
714
+ Between signings, you can also show a confirmation prompt ("sign another document?") and only continue if the user agrees.
715
+
716
+ ## Error handling
717
+
718
+ The module rejects promises with coded exceptions you can inspect at the call site:
719
+
720
+ | Error code | When | Mitigation |
721
+ | ------------------- | --------------------------------------------- | -------------------------------------------------------------- |
722
+ | `initialize_failed` | SDK failed to configure | Check integrator key and network connectivity |
723
+ | `login_failed` | Access token was rejected | Fetch a fresh token from your backend |
724
+ | `signing_failed` | SDK failed to present or complete signing | Check envelope ID, recipient info, SDK login state |
725
+ | `not_initialized` | `initialize()` was not called first | Call `initialize()` before any other method |
726
+ | `not_logged_in` | `loginWithAccessToken()` was not called first | Call `loginWithAccessToken()` before `presentCaptiveSigning()` |
727
+
728
+ Example:
729
+
730
+ ```ts
731
+ try {
732
+ await DocuSign.presentCaptiveSigning(params);
733
+ } catch (error) {
734
+ if (error.code === 'not_logged_in') {
735
+ const session = await refreshSession();
736
+ await DocuSign.loginWithAccessToken(session);
737
+ // retry
738
+ } else {
739
+ reportError(error);
740
+ }
741
+ }
742
+ ```
743
+
744
+ ## Security considerations
745
+
746
+ 1. **Never log access tokens.** If you use LogRocket, Sentry, Datadog, or any other session recording tool, add the signing session endpoint and any DocuSign token fields to your network scrub list.
747
+ 2. **Never store DocuSign tokens on the device.** Fetch per session, use immediately, discard.
748
+ 3. **Backend authorization.** Your backend MUST verify that the requesting user has permission to sign the envelope before returning a signing session.
749
+ 4. **Integrator key exposure.** The integrator key is technically a public client ID (not a secret), but you may prefer to fetch it from your backend at runtime instead of hardcoding it in the app bundle, to make revocation easier.
750
+ 5. **Token scope.** When minting access tokens via JWT Grant, request only the `signature` scope. Do not request broader scopes (`impersonation`, etc.) unless strictly necessary.
751
+ 6. **HTTPS only.** The DocuSign SDK uses HTTPS with SSL pinning. Do not disable SSL pinning in production.
752
+
753
+ ## Permissions
754
+
755
+ ### iOS `Info.plist`
756
+
757
+ The config plugin writes these keys automatically, or you can configure them manually:
758
+
759
+ | Key | Purpose |
760
+ | -------------------------------- | ------------------------------------------------------------------ |
761
+ | `NSCameraUsageDescription` | Required when users capture signatures or attach photos via camera |
762
+ | `NSPhotoLibraryUsageDescription` | Required when users attach photos from the photo library |
763
+
764
+ ### Android `AndroidManifest.xml`
765
+
766
+ | Permission | Purpose |
767
+ | ----------------------------------------- | ------------------------------- |
768
+ | `android.permission.INTERNET` | DocuSign API calls |
769
+ | `android.permission.ACCESS_NETWORK_STATE` | DocuSign SDK network monitoring |
770
+ | `android.permission.CAMERA` | Signature and photo capture |
771
+
772
+ ## Troubleshooting
773
+
774
+ ### iOS build fails with "No such module 'DocuSignSDK'"
775
+
776
+ Ensure `pod install` completed successfully inside `ios/`. The podspec declares a dependency on `DocuSign-iOS-SDK`; if CocoaPods trunk is unreachable, the pod cannot be installed. Check your network, proxy, and CocoaPods version (`pod --version` should be 1.14+).
777
+
778
+ ### iOS build fails with "Undefined symbols" for DSMManager
779
+
780
+ The DocuSign SDK must be set to `use_frameworks!` mode. Most Expo projects use frameworks by default. If you recently switched to static libraries, add `use_frameworks! :linkage => :static` to your Podfile and rebuild.
781
+
782
+ ### Android build fails with "Could not find com.docusign:androidsdk:2.1.4"
783
+
784
+ The DocuSign Android SDK is not on Maven Central; it is hosted on DocuSign's own Maven repository. Ensure the config plugin has added the repo to your project-level `build.gradle`. If running a bare project, manually add:
785
+
786
+ ```groovy
787
+ allprojects {
788
+ repositories {
789
+ maven { url "https://maven.docusign.com/" }
790
+ }
791
+ }
792
+ ```
793
+
794
+ ### "not_logged_in" error when calling `presentCaptiveSigning`
795
+
796
+ The SDK login state is in-memory and does not survive app restarts. Always call `loginWithAccessToken()` before `presentCaptiveSigning()` within the same app session.
797
+
798
+ ### Access token expired mid-signing
799
+
800
+ DocuSign access tokens are valid for about 1 hour. If a token expires while the signing UI is open, the SDK emits an error event and the promise rejects. Catch the error, fetch a fresh session from your backend, and retry.
801
+
802
+ ### Signing UI does not appear on iOS
803
+
804
+ The SDK presents its UI on the topmost view controller. If you are presenting from within a modal, the module walks the presented view controller chain. If signing still does not appear, call `presentCaptiveSigning()` after any existing modals have been dismissed.
805
+
806
+ ### Signing UI does not appear on Android
807
+
808
+ The module uses `appContext.activityProvider.currentActivity` to get the current activity. Ensure `presentCaptiveSigning()` is called while the app is in the foreground.
809
+
810
+ ## Compatibility matrix
811
+
812
+ | This package version | Expo SDK | React Native | iOS SDK | Android SDK |
813
+ | -------------------- | -------- | ------------ | ------------------ | ---------------------- |
814
+ | 1.0.x | 55.x | 0.82.x | DocuSign iOS 4.1.1 | DocuSign Android 2.1.4 |
815
+
816
+ ## Limitations
817
+
818
+ - **URL-based captive signing is iOS-only.** `presentCaptiveSigningWithUrl` is supported on iOS via DocuSign's iOS SDK 4.1.1. The DocuSign Android SDK 2.1.4 does not expose a public API that accepts a pre-minted recipient view URL, so the method throws `not_implemented` on Android. On Android, use `loginWithAccessToken` + `presentCaptiveSigning` (the session path). Your backend can branch response shape per platform.
819
+ - **Offline signing not exposed.** DocuSign's Android SDK supports offline signing via `com.docusign:sdk-offline-signing`. This package does not currently expose offline APIs. If you need offline signing, open an issue or send a pull request.
820
+ - **Template management not exposed.** The SDK's template caching and download APIs are not wrapped. Template creation should happen server-side via the DocuSign REST API.
821
+ - **Custom UI not supported.** The signing UI is provided by the DocuSign SDK and cannot be customized from this package. DocuSign owns the look and feel of the signing ceremony (this is intentional for legal compliance consistency).
822
+ - **No partial save.** If the user fills some fields and then cancels, those values are NOT persisted. DocuSign signing is all-or-nothing: the document is either signed completely or not at all.
823
+ - **No web support.** This package is iOS and Android only. For web, use DocuSign's JavaScript SDK directly.
824
+
825
+ ## FAQ
826
+
827
+ ### Can I use this with Expo Go?
828
+
829
+ No. Expo Go does not support custom native modules. You must use a development build (`expo-dev-client`) or bare React Native.
830
+
831
+ ### Does this support SSO / SAML authentication?
832
+
833
+ Not directly. SSO should be handled on your backend. Exchange the SSO session for a DocuSign access token via JWT Grant, then pass the access token to `loginWithAccessToken()`.
834
+
835
+ ### Can I call `presentCaptiveSigning()` without logging in first?
836
+
837
+ No. You must call `initialize()` then `loginWithAccessToken()` before `presentCaptiveSigning()`. This is a DocuSign SDK constraint, not a limitation of this wrapper.
838
+
839
+ ### Can I retrieve the signed PDF from the SDK?
840
+
841
+ Not directly. After signing completes, use the DocuSign REST API from your backend to download the completed envelope PDF (`GET /accounts/{accountId}/envelopes/{envelopeId}/documents/combined`).
842
+
843
+ ### How do I test signing without a real DocuSign account?
844
+
845
+ Create a free DocuSign developer account at https://developers.docusign.com. It gives you access to the `demo.docusign.net` sandbox, which you can target by setting `environment: 'demo'` in `initialize()`.
846
+
847
+ ### How do I handle signing completion server-side?
848
+
849
+ Configure a DocuSign Connect webhook that points to your backend. DocuSign will push envelope status updates (sent, delivered, completed, declined, voided) as they happen. Use the webhook as your source of truth and treat the mobile-side `SigningResult` as a UX signal only.
850
+
851
+ ### Why is the DocuSign SDK so large?
852
+
853
+ The DocuSign native SDKs include a full PDF viewer, signature pad, form renderer, and offline sync engine. Combined, they add roughly 30 to 50 MB per platform to your app bundle. DocuSign reduced the iOS SDK size by about 75% in v4.0.0; the current size is considered the minimum viable footprint.
854
+
855
+ ### Can I ship this alongside `react-native-pdf` or another PDF viewer?
856
+
857
+ Yes. The DocuSign SDK's internal PDF viewer only renders inside the signing ceremony. It does not conflict with other PDF viewers.
858
+
859
+ ### Is this package maintained?
860
+
861
+ Yes, actively. See [CHANGELOG.md](./CHANGELOG.md) for release history.
862
+
863
+ ## License
864
+
865
+ MIT. See [LICENSE](./LICENSE).
866
+
867
+ This package is not affiliated with or endorsed by DocuSign, Inc. "DocuSign" is a trademark of DocuSign, Inc. The DocuSign native SDKs are distributed separately under their own license terms.