@signature-kit/documenso 0.2.0 → 0.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 CHANGED
@@ -1,5 +1,44 @@
1
+ ## @signature-kit/documenso@0.4.0
2
+
3
+ ### Runtime updates and signature inspection
4
+
5
+ Update to stable Effect 4 and current compatible dependencies. Error classes use the native branded Schema.TaggedError constructor. Use TypeScript 7 for builds and checks with the official TypeScript 6 API compatibility alias. Upgrade direct ASN.1 dependencies to v4, interchange SDK values through DER, and encode timestamp requests with the native RFC 3161 schema. Packages do not require a consumer ASN.1 override.
6
+
7
+ Add per-signature PDF verification, certificate-validity inspection through the Effect clock, and cancellable polling for final request states in all five remote signers. Applications control polling deadlines and retry policy; a terminal request is not necessarily completed.
8
+
9
+ Update the documentation runtime, use the loading task for PDF.js cleanup, and fix dynamic Node routes by forwarding Request.duplex in the Hono adapter. Keep the app and Fumapress on a single Waku runtime.
10
+
11
+ Reject non-finite domain numbers, validate XML signature methods before WebCrypto verification, and preserve unexpected SDK failures as defects. Strengthen native Effect and accessibility lint checks.
12
+
13
+ Add branded PDF stamps with proportional PNG logos and handwriting, theme/title controls, and a PDF-rendered preview. Run browser PDF preparation and preview rendering through native Effect worker RPC with scoped termination and typed validation failures. Preserve caller buffers and signing dates across the worker boundary.
14
+
15
+ Fix structured batch stamp option conflicts, reject badges without usable drawing space, and prevent premeasured text from wrapping into adjacent rows. Restore signer interaction after React StrictMode mount replay and register localized Fumapress demo routes through the framework's native locale option. Add real worker, StrictMode, PDF text-stream, cropped/rotated page, cancellation, and invalid-image regressions.
16
+
1
17
  # Changelog
2
18
 
19
+ ## Unreleased
20
+
21
+ - Keep concrete credentials, provider, and provider-collection wiring private; consumers compose `DocumensoSignatureRequest` through `providers(options)`.
22
+
23
+ ## 0.3.0
24
+
25
+ - Documenso now owns its envelope props, attributes, state schema, schema names,
26
+ and retained no-op diff instead of using core remote-signature contracts.
27
+ - Decode provider options through a cached credential Effect, so retained-resource
28
+ `list` hooks and `read` calls without cached output do not touch credentials.
29
+ - Treat failed envelope distribution as still `draft` with `not_distributed`
30
+ provider status instead of reporting it as sent.
31
+ - Limit distribute rollback deletion to unambiguous pre-effect 4xx failures
32
+ (except 408, 409, and 429); response-shape errors, 5xxs, and timeouts no
33
+ longer delete possibly live envelopes.
34
+ - Accept missing recipient `signingUrl` values in create, get, and list responses.
35
+ - Add offline local-HTTP-server coverage for Documenso provider behavior in the
36
+ default test suite.
37
+
38
+ Breaking: request props now use `DocumensoEnvelopeProps` with `contentBase64`
39
+ documents, and `getDocumensoSignatureRequest` / `listDocumensoSignatureRequests`
40
+ return `DocumensoEnvelope` instead of core `RemoteSignature*` types.
41
+
3
42
  ## 0.2.0
4
43
 
5
44
  - Download signed documents via the envelope item id (previously passed the envelope id and
@@ -11,4 +50,4 @@
11
50
 
12
51
  - Initial npm-ready release for `@signature-kit/documenso`.
13
52
  - Published package metadata, MIT license, README, and package-local changelog.
14
- - Ships alchemy v2 remote-signature provider for Documenso envelope creation, lookup, deletion, and signed-document download.
53
+ - Ships an Alchemy v2 remote-signature provider for Documenso envelope creation, lookup, deletion, and signed-document download.
package/README.md CHANGED
@@ -1,24 +1,104 @@
1
1
  # @signature-kit/documenso
2
2
 
3
- Alchemy v2 remote-signature provider for Documenso envelope creation, lookup, deletion, and signed-document download.
3
+ Alchemy v2 remote-signature provider for Documenso envelope creation, lookup, listing, cancellation, deletion, and completed-document download.
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```sh
8
- bun add @signature-kit/documenso effect alchemy
8
+ bun add @signature-kit/documenso @signature-kit/http effect alchemy
9
9
  ```
10
10
 
11
- ## Exports
11
+ `effect` and `alchemy` are direct runtime dependencies. Provide
12
+ `signatureHttpClientLive` at the stack boundary; `providers(options)` supplies
13
+ only Documenso credentials and resource providers. Provider options are stored as
14
+ a cached credential Effect, so retained `list` hooks and `read` calls without
15
+ cached output do not decode credentials.
12
16
 
13
- - `@signature-kit/documenso`
17
+ ## Public surface
14
18
 
15
- ## Runtime model
19
+ - `@signature-kit/documenso` — Documenso envelope/document/recipient schemas, `DocumensoSignatureRequest`, `providers`, `getDocumensoSignatureRequest`, `listDocumensoSignatureRequests`, `cancelDocumensoSignatureRequest`, `deleteDocumensoSignatureRequest`, and `downloadDocumensoSignedDocument`.
16
20
 
17
- SignatureKit packages are Effect-native. Public APIs return typed `Effect.Effect` values; recoverable faults stay in the typed error channel; callers provide required services and layers explicitly at the application boundary.
21
+ Capability matrix:
18
22
 
19
- ## Version
23
+ | Capability | Supported |
24
+ | -------------------------------- | ------------------------------------------------------------------------- |
25
+ | Create retained Alchemy envelope | Yes |
26
+ | Get envelope | Yes |
27
+ | List envelopes | Yes |
28
+ | Cancel envelope | Yes |
29
+ | Delete envelope | Yes |
30
+ | Download signed document | Yes, after the envelope is completed and an envelope item id is available |
20
31
 
21
- Current npm release line: `0.1.0`.
32
+ Retained-resource semantics: Alchemy `reconcile` creates once and returns cached output on subsequent plans; provider `list` returns `[]`; `nuke` is skipped. Multi-step create rollback deletes remote state only after unambiguous pre-effect 4xx failures, excluding 408, 409, 429, 5xx, timeouts, and response-shape failures.
33
+
34
+ ## Example
35
+
36
+ ```ts
37
+ import * as Alchemy from "alchemy";
38
+ import {
39
+ DocumensoSignatureRequest,
40
+ downloadDocumensoSignedDocument,
41
+ providers as documensoProviders,
42
+ type DocumensoProviderOptions,
43
+ } from "@signature-kit/documenso";
44
+ import { signatureHttpClientLive } from "@signature-kit/http";
45
+ import { Effect, Layer, Redacted } from "effect";
46
+
47
+ declare const pdfBase64: string;
48
+ declare const apiKey: string;
49
+
50
+ const options: DocumensoProviderOptions = {
51
+ apiKey: Redacted.make(apiKey),
52
+ };
53
+
54
+ export default class Contracts extends Alchemy.Stack<Contracts>()(
55
+ "Contracts",
56
+ {
57
+ providers: Layer.merge(documensoProviders(options), signatureHttpClientLive),
58
+ state: Alchemy.inMemoryState(),
59
+ },
60
+ Effect.gen(function* () {
61
+ return yield* DocumensoSignatureRequest("service-agreement", {
62
+ title: "Service agreement",
63
+ documents: [
64
+ { fileName: "contract.pdf", mimeType: "application/pdf", contentBase64: pdfBase64 },
65
+ ],
66
+ recipients: [{ name: "Ada Lovelace", email: "ada@example.com", role: "signer" }],
67
+ send: true,
68
+ });
69
+ }),
70
+ ) {}
71
+
72
+ export const downloadSigned = (envelopeId: string) =>
73
+ downloadDocumensoSignedDocument(options, envelopeId).pipe(
74
+ Effect.provide(signatureHttpClientLive),
75
+ );
76
+ ```
77
+
78
+ ## Wait for a final state
79
+
80
+ `waitForDocumensoSignatureRequest(options, id, pollInterval)` reads immediately and polls while the request is `draft` or `sent`. It returns the provider's final state, including cancellation, rejection, deletion, or expiry; inspect `state` before downloading. The interval must be positive and finite. Read failures propagate immediately without automatic retry. Interruption cancels the active read and stops future polls. The caller owns the deadline:
81
+
82
+ ```ts
83
+ import { waitForDocumensoSignatureRequest } from "@signature-kit/documenso";
84
+ import { signatureHttpClientLive } from "@signature-kit/http";
85
+ import { Duration, Effect } from "effect";
86
+ import type { DocumensoProviderOptions } from "@signature-kit/documenso";
87
+
88
+ declare const options: DocumensoProviderOptions;
89
+ declare const requestId: string;
90
+
91
+ const program = waitForDocumensoSignatureRequest(options, requestId, Duration.seconds(2)).pipe(
92
+ Effect.timeout(Duration.minutes(5)),
93
+ Effect.provide(signatureHttpClientLive),
94
+ );
95
+ ```
96
+
97
+ ## Errors and i18n
98
+
99
+ Invalid inputs, remote HTTP failures, unsupported operations, and invalid response shapes fail as `SignatureKitError` from `@signature-kit/signatures`. Applications can render localized copy through `errorMessage` from `@signature-kit/i18n` with the `signatureKitErrorMessages` catalog from `@signature-kit/signatures`.
100
+
101
+ Docs: <https://signaturekit.dev/en-US/docs/providers/documenso>.
22
102
 
23
103
  ## License
24
104
 
package/dist/index.d.ts CHANGED
@@ -1,9 +1,82 @@
1
- import { SignatureKitError } from "@signature-kit/core/config";
2
- import type { RemoteSignatureRequest, RemoteSignatureRequestProps } from "@signature-kit/core/config";
3
- import { SignatureHttpClient } from "@signature-kit/core/http";
1
+ import { SignatureKitError } from "@signature-kit/signatures";
2
+ import { SignatureHttpClient } from "@signature-kit/http";
4
3
  import { Resource } from "alchemy";
5
4
  import * as Provider from "alchemy/Provider";
6
- import { Context, Effect, Layer, Redacted, Schema } from "effect";
5
+ import { Duration, Effect, Layer, Redacted, Schema } from "effect";
6
+ export declare const DocumensoProviderId = "documenso";
7
+ export declare const DocumensoEnvelopeStateSchema: Schema.Literals<readonly ["draft", "sent", "completed", "cancelled", "deleted", "declined", "expired"]>;
8
+ export type DocumensoEnvelopeState = (typeof DocumensoEnvelopeStateSchema)["Type"];
9
+ export declare const DocumensoEnvelopeDocumentSchema: Schema.Struct<{
10
+ readonly fileName: Schema.NonEmptyString;
11
+ readonly mimeType: Schema.Literal<"application/pdf">;
12
+ readonly content: Schema.Uint8Array;
13
+ }>;
14
+ export type DocumensoEnvelopeDocument = (typeof DocumensoEnvelopeDocumentSchema)["Type"];
15
+ export declare const DocumensoEnvelopeDocumentPropsSchema: Schema.Struct<{
16
+ readonly fileName: Schema.NonEmptyString;
17
+ readonly mimeType: Schema.Literal<"application/pdf">;
18
+ readonly contentBase64: Schema.ConstraintDecoder<string, never>;
19
+ }>;
20
+ export type DocumensoEnvelopeDocumentProps = (typeof DocumensoEnvelopeDocumentPropsSchema)["Type"];
21
+ export declare const DocumensoRecipientRoleSchema: Schema.Literals<readonly ["approver", "signer"]>;
22
+ export type DocumensoRecipientRole = (typeof DocumensoRecipientRoleSchema)["Type"];
23
+ export declare const DocumensoEnvelopeRecipientSchema: Schema.Struct<{
24
+ readonly name: Schema.NonEmptyString;
25
+ readonly email: Schema.NonEmptyString;
26
+ readonly role: Schema.optional<Schema.Literals<readonly ["approver", "signer"]>>;
27
+ readonly routingOrder: Schema.optional<Schema.Finite>;
28
+ }>;
29
+ export type DocumensoEnvelopeRecipient = (typeof DocumensoEnvelopeRecipientSchema)["Type"];
30
+ export declare const DocumensoEnvelopeInputSchema: Schema.Struct<{
31
+ readonly title: Schema.NonEmptyString;
32
+ readonly subject: Schema.optional<Schema.NonEmptyString>;
33
+ readonly message: Schema.optional<Schema.NonEmptyString>;
34
+ readonly documents: Schema.NonEmptyArray<Schema.Struct<{
35
+ readonly fileName: Schema.NonEmptyString;
36
+ readonly mimeType: Schema.Literal<"application/pdf">;
37
+ readonly content: Schema.Uint8Array;
38
+ }>>;
39
+ readonly recipients: Schema.NonEmptyArray<Schema.Struct<{
40
+ readonly name: Schema.NonEmptyString;
41
+ readonly email: Schema.NonEmptyString;
42
+ readonly role: Schema.optional<Schema.Literals<readonly ["approver", "signer"]>>;
43
+ readonly routingOrder: Schema.optional<Schema.Finite>;
44
+ }>>;
45
+ readonly send: Schema.optional<Schema.Boolean>;
46
+ readonly expiresAt: Schema.optional<Schema.Date>;
47
+ readonly redirectUrl: Schema.optional<Schema.NonEmptyString>;
48
+ }>;
49
+ export type DocumensoEnvelopeInput = (typeof DocumensoEnvelopeInputSchema)["Type"];
50
+ export declare const DocumensoEnvelopePropsSchema: Schema.Struct<{
51
+ readonly title: Schema.NonEmptyString;
52
+ readonly subject: Schema.optional<Schema.NonEmptyString>;
53
+ readonly message: Schema.optional<Schema.NonEmptyString>;
54
+ readonly documents: Schema.NonEmptyArray<Schema.Struct<{
55
+ readonly fileName: Schema.NonEmptyString;
56
+ readonly mimeType: Schema.Literal<"application/pdf">;
57
+ readonly contentBase64: Schema.ConstraintDecoder<string, never>;
58
+ }>>;
59
+ readonly recipients: Schema.NonEmptyArray<Schema.Struct<{
60
+ readonly name: Schema.NonEmptyString;
61
+ readonly email: Schema.NonEmptyString;
62
+ readonly role: Schema.optional<Schema.Literals<readonly ["approver", "signer"]>>;
63
+ readonly routingOrder: Schema.optional<Schema.Finite>;
64
+ }>>;
65
+ readonly send: Schema.optional<Schema.Boolean>;
66
+ readonly expiresAt: Schema.optional<Schema.Date>;
67
+ readonly redirectUrl: Schema.optional<Schema.NonEmptyString>;
68
+ }>;
69
+ export type DocumensoEnvelopeProps = (typeof DocumensoEnvelopePropsSchema)["Type"];
70
+ export declare const DocumensoEnvelopeSchema: Schema.Struct<{
71
+ readonly provider: Schema.Literal<"documenso">;
72
+ readonly id: Schema.NonEmptyString;
73
+ readonly state: Schema.Literals<readonly ["draft", "sent", "completed", "cancelled", "deleted", "declined", "expired"]>;
74
+ readonly providerStatus: Schema.optional<Schema.String>;
75
+ readonly signingUrl: Schema.optional<Schema.String>;
76
+ readonly detailsUrl: Schema.optional<Schema.String>;
77
+ readonly downloadUrl: Schema.optional<Schema.String>;
78
+ }>;
79
+ export type DocumensoEnvelope = (typeof DocumensoEnvelopeSchema)["Type"];
7
80
  declare const DocumensoAuthorizationSchemeSchema: Schema.Literals<readonly ["raw", "bearer"]>;
8
81
  export type DocumensoAuthorizationScheme = (typeof DocumensoAuthorizationSchemeSchema)["Type"];
9
82
  export declare const DocumensoProviderOptionsSchema: Schema.Struct<{
@@ -12,25 +85,29 @@ export declare const DocumensoProviderOptionsSchema: Schema.Struct<{
12
85
  readonly authorizationScheme: Schema.optional<Schema.Literals<readonly ["raw", "bearer"]>>;
13
86
  }>;
14
87
  export type DocumensoProviderOptions = (typeof DocumensoProviderOptionsSchema)["Type"];
15
- export type DocumensoSignatureRequest = Resource<"SignatureKit.DocumensoSignatureRequest", RemoteSignatureRequestProps, RemoteSignatureRequest>;
88
+ export type DocumensoSignatureRequest = Resource<"SignatureKit.DocumensoSignatureRequest", DocumensoEnvelopeProps, DocumensoEnvelope>;
16
89
  export declare const DocumensoSignatureRequest: import("alchemy").ResourceClass<DocumensoSignatureRequest>;
17
- declare const DocumensoCredentials_base: Context.ServiceClass<DocumensoCredentials, "@signature-kit/documenso/Credentials", {
18
- readonly apiKey: Redacted.Redacted<string>;
19
- readonly baseUrl?: string | undefined;
20
- readonly authorizationScheme?: "raw" | "bearer" | undefined;
21
- }>;
22
- export declare class DocumensoCredentials extends DocumensoCredentials_base {
23
- }
24
- export declare const documensoCredentialsLayer: (options: DocumensoProviderOptions) => Layer.Layer<DocumensoCredentials, SignatureKitError>;
25
- export declare const DocumensoSignatureRequestProvider: () => Layer.Layer<Provider.Provider<DocumensoSignatureRequest>, never, DocumensoCredentials | SignatureHttpClient>;
26
90
  declare const DocumensoProviders_base: Provider.ProviderCollection<DocumensoProviders, "@signature-kit/documenso/Providers">;
27
- export declare class DocumensoProviders extends DocumensoProviders_base {
91
+ declare class DocumensoProviders extends DocumensoProviders_base {
28
92
  }
29
- export declare const providers: (options: DocumensoProviderOptions) => Layer.Layer<DocumensoProviders, SignatureKitError, SignatureHttpClient>;
30
- export declare const getDocumensoSignatureRequest: (options: DocumensoProviderOptions, id: string) => Effect.Effect<RemoteSignatureRequest, SignatureKitError, SignatureHttpClient>;
31
- export declare const listDocumensoSignatureRequests: (options: DocumensoProviderOptions) => Effect.Effect<ReadonlyArray<RemoteSignatureRequest>, SignatureKitError, SignatureHttpClient>;
93
+ export declare const providers: (options: DocumensoProviderOptions) => Layer.Layer<DocumensoProviders, never, SignatureHttpClient>;
94
+ export declare const getDocumensoSignatureRequest: (options: DocumensoProviderOptions, id: string) => Effect.Effect<DocumensoEnvelope, SignatureKitError, SignatureHttpClient>;
95
+ export declare const listDocumensoSignatureRequests: (options: DocumensoProviderOptions) => Effect.Effect<ReadonlyArray<DocumensoEnvelope>, SignatureKitError, SignatureHttpClient>;
32
96
  export declare const cancelDocumensoSignatureRequest: (options: DocumensoProviderOptions, id: string) => Effect.Effect<void, SignatureKitError, SignatureHttpClient>;
33
97
  export declare const deleteDocumensoSignatureRequest: (options: DocumensoProviderOptions, id: string) => Effect.Effect<void, SignatureKitError, SignatureHttpClient>;
34
98
  export declare const downloadDocumensoSignedDocument: (options: DocumensoProviderOptions, envelopeId: string) => Effect.Effect<Uint8Array, SignatureKitError, SignatureHttpClient>;
99
+ export declare const waitForDocumensoSignatureRequest: (options: {
100
+ readonly apiKey: Redacted.Redacted<string>;
101
+ readonly baseUrl?: string | undefined;
102
+ readonly authorizationScheme?: "bearer" | "raw" | undefined;
103
+ }, id: string, pollInterval: Duration.Duration) => Effect.Effect<{
104
+ readonly provider: "documenso";
105
+ readonly id: string;
106
+ readonly state: "cancelled" | "completed" | "declined" | "deleted" | "draft" | "expired" | "sent";
107
+ readonly providerStatus?: string | undefined;
108
+ readonly signingUrl?: string | undefined;
109
+ readonly detailsUrl?: string | undefined;
110
+ readonly downloadUrl?: string | undefined;
111
+ }, SignatureKitError, SignatureHttpClient>;
35
112
  export {};
36
113
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EAMlB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAEV,sBAAsB,EAEtB,2BAA2B,EAC5B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAqB,MAAM,0BAA0B,CAAC;AAElF,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAU,QAAQ,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AASlF,QAAA,MAAM,kCAAkC,6CAAqC,CAAC;AAC9E,MAAM,MAAM,4BAA4B,GAAG,CAAC,OAAO,kCAAkC,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/F,eAAO,MAAM,8BAA8B;;;;EAIzC,CAAC;AACH,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,8BAA8B,CAAC,CAAC,MAAM,CAAC,CAAC;AAqDvF,MAAM,MAAM,yBAAyB,GAAG,QAAQ,CAC9C,wCAAwC,EACxC,2BAA2B,EAC3B,sBAAsB,CACvB,CAAC;AAEF,eAAO,MAAM,yBAAyB,4DAGrC,CAAC;;;;;;AACF,qBAAa,oBAAqB,SAAQ,yBAGC;CAAG;AAE9C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 @@
1
- import { SignatureKitError, SignatureKitErrorCodeValue, SignatureKitOperationValue, SignatureKitSchemaNameValue, redactedStringSchema, remoteSignatureInputFromResourceProps, } from "@signature-kit/core/config";
2
- import { SignatureHttpClient, normalizedBaseUrl } from "@signature-kit/core/http";
1
+ import { base64ToBytes } from "@signature-kit/crypto/base64";
2
+ import { SignatureKitError, SignatureKitErrorCodeValue, SignatureKitOperationValue, redactedStringSchema, } from "@signature-kit/signatures";
3
+ import { SignatureHttpClient, normalizedBaseUrl } from "@signature-kit/http";
3
4
  import { Resource } from "alchemy";
4
5
  import * as Provider from "alchemy/Provider";
5
- import { Context, Effect, Layer, Option, Redacted, Schema, Stream } from "effect";
6
- const PROVIDER = "documenso";
6
+ import { Context, Duration, Effect, Layer, Match, Option, Redacted, Schedule, Schema, Stream, } from "effect";
7
+ const DocumensoSchemaName = {
8
+ providerOptions: "DocumensoProviderOptions",
9
+ signatureRequestProps: "DocumensoEnvelopeProps",
10
+ createEnvelopeResult: "DocumensoCreateEnvelopeResult",
11
+ distributeEnvelopeResult: "DocumensoDistributeEnvelopeResult",
12
+ envelopeResult: "DocumensoEnvelopeResult",
13
+ envelopeListResult: "DocumensoEnvelopeListResult",
14
+ };
15
+ const DocumensoOperation = {
16
+ create: "documenso.create",
17
+ download: "documenso.download",
18
+ };
19
+ const base64String = Schema.String.check(Schema.isBase64());
20
+ export const DocumensoProviderId = "documenso";
21
+ const PROVIDER = DocumensoProviderId;
22
+ export const DocumensoEnvelopeStateSchema = Schema.Literals([
23
+ "draft",
24
+ "sent",
25
+ "completed",
26
+ "cancelled",
27
+ "deleted",
28
+ "declined",
29
+ "expired",
30
+ ]);
31
+ export const DocumensoEnvelopeDocumentSchema = Schema.Struct({
32
+ fileName: Schema.NonEmptyString,
33
+ mimeType: Schema.Literal("application/pdf"),
34
+ content: Schema.Uint8Array,
35
+ });
36
+ export const DocumensoEnvelopeDocumentPropsSchema = Schema.Struct({
37
+ fileName: Schema.NonEmptyString,
38
+ mimeType: Schema.Literal("application/pdf"),
39
+ contentBase64: base64String,
40
+ });
41
+ export const DocumensoRecipientRoleSchema = Schema.Literals(["approver", "signer"]);
42
+ export const DocumensoEnvelopeRecipientSchema = Schema.Struct({
43
+ name: Schema.NonEmptyString,
44
+ email: Schema.NonEmptyString,
45
+ role: Schema.optional(DocumensoRecipientRoleSchema),
46
+ routingOrder: Schema.optional(Schema.Finite),
47
+ });
48
+ export const DocumensoEnvelopeInputSchema = Schema.Struct({
49
+ title: Schema.NonEmptyString,
50
+ subject: Schema.optional(Schema.NonEmptyString),
51
+ message: Schema.optional(Schema.NonEmptyString),
52
+ documents: Schema.NonEmptyArray(DocumensoEnvelopeDocumentSchema),
53
+ recipients: Schema.NonEmptyArray(DocumensoEnvelopeRecipientSchema),
54
+ send: Schema.optional(Schema.Boolean),
55
+ expiresAt: Schema.optional(Schema.Date),
56
+ redirectUrl: Schema.optional(Schema.NonEmptyString),
57
+ });
58
+ export const DocumensoEnvelopePropsSchema = Schema.Struct({
59
+ title: Schema.NonEmptyString,
60
+ subject: Schema.optional(Schema.NonEmptyString),
61
+ message: Schema.optional(Schema.NonEmptyString),
62
+ documents: Schema.NonEmptyArray(DocumensoEnvelopeDocumentPropsSchema),
63
+ recipients: Schema.NonEmptyArray(DocumensoEnvelopeRecipientSchema),
64
+ send: Schema.optional(Schema.Boolean),
65
+ expiresAt: Schema.optional(Schema.Date),
66
+ redirectUrl: Schema.optional(Schema.NonEmptyString),
67
+ });
68
+ export const DocumensoEnvelopeSchema = Schema.Struct({
69
+ provider: Schema.Literal(PROVIDER),
70
+ id: Schema.NonEmptyString,
71
+ state: DocumensoEnvelopeStateSchema,
72
+ providerStatus: Schema.optional(Schema.String),
73
+ signingUrl: Schema.optional(Schema.String),
74
+ detailsUrl: Schema.optional(Schema.String),
75
+ downloadUrl: Schema.optional(Schema.String),
76
+ });
77
+ const documensoSignatureRequestNoopDiff = { action: "noop" };
78
+ const documensoSignatureRequestDiff = ({ olds, }) => Effect.succeed(olds === undefined ? undefined : documensoSignatureRequestNoopDiff);
79
+ const documensoSignatureRequestInputFromProps = Effect.fn(function* (props) {
80
+ const [firstDocument, ...restDocuments] = props.documents;
81
+ const firstContent = yield* base64ToBytes(firstDocument.contentBase64).pipe(Effect.orDie);
82
+ const decodedRestDocuments = yield* Effect.forEach(restDocuments, (document) => base64ToBytes(document.contentBase64).pipe(Effect.orDie, Effect.map((content) => ({
83
+ fileName: document.fileName,
84
+ mimeType: document.mimeType,
85
+ content,
86
+ }))));
87
+ const documents = [
88
+ {
89
+ fileName: firstDocument.fileName,
90
+ mimeType: firstDocument.mimeType,
91
+ content: firstContent,
92
+ },
93
+ ...decodedRestDocuments,
94
+ ];
95
+ return {
96
+ title: props.title,
97
+ documents,
98
+ recipients: props.recipients,
99
+ ...(props.subject === undefined ? {} : { subject: props.subject }),
100
+ ...(props.message === undefined ? {} : { message: props.message }),
101
+ ...(props.send === undefined ? {} : { send: props.send }),
102
+ ...(props.expiresAt === undefined ? {} : { expiresAt: props.expiresAt }),
103
+ ...(props.redirectUrl === undefined ? {} : { redirectUrl: props.redirectUrl }),
104
+ };
105
+ });
106
+ const documensoSignatureRequestInputFromResourceProps = (props) => Schema.decodeUnknownEffect(DocumensoEnvelopePropsSchema)(props).pipe(Effect.mapError((issue) => new SignatureKitError({
107
+ code: SignatureKitErrorCodeValue.invalidInput,
108
+ retryable: false,
109
+ provider: PROVIDER,
110
+ operation: SignatureKitOperationValue.schemaDecode,
111
+ schemaName: DocumensoSchemaName.signatureRequestProps,
112
+ issueMessage: String(issue),
113
+ })), Effect.flatMap(documensoSignatureRequestInputFromProps));
7
114
  const DOCUMENSO_PROVIDER_COLLECTION_ID = "@signature-kit/documenso/Providers";
8
115
  const DEFAULT_BASE_URL = "https://app.documenso.com/api/v2";
9
116
  const DOCUMENSO_LIST_FIRST_PAGE = 1;
@@ -19,12 +126,12 @@ const DocumensoCreateEnvelopeResultSchema = Schema.Struct({
19
126
  id: Schema.NonEmptyString,
20
127
  });
21
128
  const DocumensoRecipientResultSchema = Schema.Struct({
22
- id: Schema.Number,
129
+ id: Schema.Finite,
23
130
  name: Schema.String,
24
131
  email: Schema.String,
25
132
  role: Schema.String,
26
- signingOrder: Schema.optional(Schema.NullOr(Schema.Number)),
27
- signingUrl: Schema.String,
133
+ signingOrder: Schema.optional(Schema.NullOr(Schema.Finite)),
134
+ signingUrl: Schema.optional(Schema.String),
28
135
  });
29
136
  const DocumensoDistributeEnvelopeResultSchema = Schema.Struct({
30
137
  success: Schema.Boolean,
@@ -32,7 +139,7 @@ const DocumensoDistributeEnvelopeResultSchema = Schema.Struct({
32
139
  recipients: Schema.Array(DocumensoRecipientResultSchema),
33
140
  });
34
141
  const DocumensoEnvelopeRecipientResultSchema = Schema.Struct({
35
- id: Schema.Union([Schema.NonEmptyString, Schema.Number]),
142
+ id: Schema.Union([Schema.NonEmptyString, Schema.Finite]),
36
143
  name: Schema.String,
37
144
  email: Schema.String,
38
145
  role: Schema.String,
@@ -48,26 +155,26 @@ const DocumensoEnvelopeResultSchema = Schema.Struct({
48
155
  envelopeItems: Schema.optional(Schema.Array(DocumensoEnvelopeItemResultSchema)),
49
156
  });
50
157
  const DocumensoEnvelopeListPaginationSchema = Schema.Struct({
51
- page: Schema.Number,
52
- perPage: Schema.Number,
53
- totalPages: Schema.Number,
54
- totalItems: Schema.Number,
158
+ page: Schema.Finite,
159
+ perPage: Schema.Finite,
160
+ totalPages: Schema.Finite,
161
+ totalItems: Schema.Finite,
55
162
  });
56
163
  const DocumensoEnvelopeListResultSchema = Schema.Struct({
57
164
  data: Schema.Array(DocumensoEnvelopeResultSchema),
58
165
  pagination: DocumensoEnvelopeListPaginationSchema,
59
166
  });
60
167
  export const DocumensoSignatureRequest = Resource("SignatureKit.DocumensoSignatureRequest", { defaultRemovalPolicy: "retain" });
61
- export class DocumensoCredentials extends Context.Service()("@signature-kit/documenso/Credentials") {
168
+ class DocumensoCredentials extends Context.Service()("@signature-kit/documenso/Credentials") {
62
169
  }
63
- export const documensoCredentialsLayer = (options) => Layer.effect(DocumensoCredentials, Schema.decodeUnknownEffect(DocumensoProviderOptionsSchema)(options).pipe(Effect.mapError((issue) => new SignatureKitError({
170
+ const documensoCredentialsLayer = (options) => Layer.effect(DocumensoCredentials, Effect.cached(Schema.decodeUnknownEffect(DocumensoProviderOptionsSchema)(options).pipe(Effect.mapError((issue) => new SignatureKitError({
64
171
  code: SignatureKitErrorCodeValue.invalidInput,
65
172
  retryable: false,
66
173
  provider: PROVIDER,
67
174
  operation: SignatureKitOperationValue.schemaDecode,
68
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
175
+ schemaName: DocumensoSchemaName.providerOptions,
69
176
  issueMessage: String(issue),
70
- }))));
177
+ })))));
71
178
  const documensoBaseUrl = (options) => options.baseUrl === undefined ? DEFAULT_BASE_URL : normalizedBaseUrl(options.baseUrl);
72
179
  const documensoAuthorization = (options) => {
73
180
  const token = Redacted.value(options.apiKey);
@@ -123,7 +230,7 @@ const createEnvelope = (http, options, baseUrl, input) => http.requestJson({
123
230
  url: `${baseUrl}/envelope/create`,
124
231
  headers: { Authorization: documensoAuthorization(options) },
125
232
  body: createEnvelopeBody(input),
126
- }, DocumensoCreateEnvelopeResultSchema, SignatureKitSchemaNameValue.documensoCreateEnvelopeResult);
233
+ }, DocumensoCreateEnvelopeResultSchema, DocumensoSchemaName.createEnvelopeResult);
127
234
  const distributeEnvelope = (http, options, baseUrl, input, envelope) => http
128
235
  .requestJson({
129
236
  provider: PROVIDER,
@@ -134,42 +241,38 @@ const distributeEnvelope = (http, options, baseUrl, input, envelope) => http
134
241
  Authorization: documensoAuthorization(options),
135
242
  },
136
243
  body: JSON.stringify({ envelopeId: envelope.id, meta: requestMeta(input) }),
137
- }, DocumensoDistributeEnvelopeResultSchema, SignatureKitSchemaNameValue.documensoDistributeEnvelopeResult)
244
+ }, DocumensoDistributeEnvelopeResultSchema, DocumensoSchemaName.distributeEnvelopeResult)
138
245
  .pipe(Effect.map((result) => ({
139
246
  provider: PROVIDER,
140
247
  id: result.id,
141
- state: "sent",
248
+ state: result.success ? "sent" : "draft",
142
249
  providerStatus: result.success ? "distributed" : "not_distributed",
143
250
  detailsUrl: `${baseUrl}/envelope/${documensoPathId(result.id)}`,
144
251
  ...(result.recipients[0]?.signingUrl === undefined
145
252
  ? {}
146
253
  : { signingUrl: result.recipients[0].signingUrl }),
147
254
  })));
255
+ const DocumensoEnvelopeStatusSchema = Schema.Literals([
256
+ "DRAFT",
257
+ "PENDING",
258
+ "PROCESSING",
259
+ "SENT",
260
+ "SIGNED",
261
+ "COMPLETED",
262
+ "CLOSED",
263
+ "REJECTED",
264
+ "DECLINED",
265
+ "CANCELED",
266
+ "CANCELLED",
267
+ "DELETED",
268
+ "EXPIRED",
269
+ ]);
270
+ const isDocumensoEnvelopeStatus = Schema.is(DocumensoEnvelopeStatusSchema);
148
271
  const mapEnvelopeStatus = (status) => {
149
- switch (status.toUpperCase()) {
150
- case "DRAFT":
151
- return "draft";
152
- case "PENDING":
153
- case "PROCESSING":
154
- case "SENT":
155
- return "sent";
156
- case "SIGNED":
157
- case "COMPLETED":
158
- case "CLOSED":
159
- return "completed";
160
- case "REJECTED":
161
- case "DECLINED":
162
- return "declined";
163
- case "CANCELED":
164
- case "CANCELLED":
165
- return "cancelled";
166
- case "DELETED":
167
- return "deleted";
168
- case "EXPIRED":
169
- return "expired";
170
- default:
171
- return "sent";
172
- }
272
+ const normalized = status.toUpperCase();
273
+ if (!isDocumensoEnvelopeStatus(normalized))
274
+ return "sent";
275
+ return Match.value(normalized).pipe(Match.when("DRAFT", () => "draft"), Match.whenOr("PENDING", "PROCESSING", "SENT", () => "sent"), Match.whenOr("SIGNED", "COMPLETED", "CLOSED", () => "completed"), Match.whenOr("REJECTED", "DECLINED", () => "declined"), Match.whenOr("CANCELED", "CANCELLED", () => "cancelled"), Match.when("DELETED", () => "deleted"), Match.when("EXPIRED", () => "expired"), Match.orElse(() => "sent"));
173
276
  };
174
277
  const envelopeSignedDownloadUrl = (baseUrl, envelopeItemId) => {
175
278
  const encodedItemId = documensoPathId(envelopeItemId);
@@ -183,7 +286,7 @@ const envelopeSignedDownloadUrlFromEnvelope = (baseUrl, envelope) => {
183
286
  ? undefined
184
287
  : envelopeSignedDownloadUrl(baseUrl, envelopeItemId);
185
288
  };
186
- const mapEnvelopeToRemoteRequest = (baseUrl, envelope) => {
289
+ const mapEnvelopeToDocumensoEnvelope = (baseUrl, envelope) => {
187
290
  const signingUrl = envelope.recipients?.[0]?.signingUrl;
188
291
  const downloadUrl = envelopeSignedDownloadUrlFromEnvelope(baseUrl, envelope);
189
292
  return {
@@ -201,26 +304,24 @@ const fetchEnvelopeResult = (http, options, baseUrl, id) => http.requestJson({
201
304
  method: "GET",
202
305
  url: `${baseUrl}/envelope/${documensoPathId(id)}`,
203
306
  headers: { Authorization: documensoAuthorization(options) },
204
- }, DocumensoEnvelopeResultSchema, SignatureKitSchemaNameValue.documensoEnvelopeResult);
205
- const getEnvelope = (http, options, baseUrl, id) => fetchEnvelopeResult(http, options, baseUrl, id).pipe(Effect.map((result) => mapEnvelopeToRemoteRequest(baseUrl, result)));
206
- const listEnvelopes = (http, options, baseUrl) => {
207
- return Stream.paginate(DOCUMENSO_LIST_FIRST_PAGE, (page) => {
208
- const url = new URL(`${baseUrl}/envelope`);
209
- url.searchParams.set("page", String(page));
210
- url.searchParams.set("perPage", String(DOCUMENSO_LIST_PER_PAGE));
211
- return http
212
- .requestJson({
213
- provider: PROVIDER,
214
- method: "GET",
215
- url: url.toString(),
216
- headers: { Authorization: documensoAuthorization(options) },
217
- }, DocumensoEnvelopeListResultSchema, SignatureKitSchemaNameValue.documensoEnvelopeListResult)
218
- .pipe(Effect.map((result) => [
219
- result.data.map((envelope) => mapEnvelopeToRemoteRequest(baseUrl, envelope)),
220
- documensoNextPage(result.pagination, page),
221
- ]));
222
- }).pipe(Stream.runCollect, Effect.map((requests) => requests.flat()));
223
- };
307
+ }, DocumensoEnvelopeResultSchema, DocumensoSchemaName.envelopeResult);
308
+ const getEnvelope = (http, options, baseUrl, id) => fetchEnvelopeResult(http, options, baseUrl, id).pipe(Effect.map((result) => mapEnvelopeToDocumensoEnvelope(baseUrl, result)));
309
+ const listEnvelopes = (http, options, baseUrl) => Stream.paginate(DOCUMENSO_LIST_FIRST_PAGE, (page) => {
310
+ const url = new URL(`${baseUrl}/envelope`);
311
+ url.searchParams.set("page", String(page));
312
+ url.searchParams.set("perPage", String(DOCUMENSO_LIST_PER_PAGE));
313
+ return http
314
+ .requestJson({
315
+ provider: PROVIDER,
316
+ method: "GET",
317
+ url: url.toString(),
318
+ headers: { Authorization: documensoAuthorization(options) },
319
+ }, DocumensoEnvelopeListResultSchema, DocumensoSchemaName.envelopeListResult)
320
+ .pipe(Effect.map((result) => [
321
+ result.data.map((envelope) => mapEnvelopeToDocumensoEnvelope(baseUrl, envelope)),
322
+ documensoNextPage(result.pagination, page),
323
+ ]));
324
+ }).pipe(Stream.runCollect);
224
325
  const cancelEnvelope = (http, options, baseUrl, envelopeId) => http.requestVoid({
225
326
  provider: PROVIDER,
226
327
  method: "POST",
@@ -243,29 +344,36 @@ const deleteEnvelope = (http, options, baseUrl, envelopeId) => http
243
344
  body: JSON.stringify({ envelopeId }),
244
345
  })
245
346
  .pipe(Effect.catchIf((error) => error.code === SignatureKitErrorCodeValue.http && error.status === 404, () => Effect.void));
246
- const downloadSignedEnvelopeItem = (http, options, baseUrl, envelopeItemId) => {
247
- const encodedItemId = documensoPathId(envelopeItemId);
248
- const url = new URL(`${baseUrl}/envelope/item/${encodedItemId}/download`);
249
- url.searchParams.set("version", "signed");
250
- return requestEnvelopeSignedBytes(http, options, baseUrl, url.toString());
251
- };
252
347
  const downloadSignedEnvelopeDocument = (http, options, baseUrl, envelopeId) => fetchEnvelopeResult(http, options, baseUrl, envelopeId).pipe(Effect.flatMap((envelope) => {
253
- const downloadUrl = envelopeSignedDownloadUrlFromEnvelope(baseUrl, envelope);
254
- if (downloadUrl !== undefined) {
255
- return requestEnvelopeSignedBytes(http, options, baseUrl, downloadUrl);
348
+ if (mapEnvelopeStatus(envelope.status) !== "completed") {
349
+ return Effect.fail(new SignatureKitError({
350
+ code: SignatureKitErrorCodeValue.unsupportedOperation,
351
+ retryable: false,
352
+ provider: PROVIDER,
353
+ operation: DocumensoOperation.download,
354
+ reason: `Documenso envelope ${envelopeId} is not completed yet (status: ${envelope.status ?? "unknown"}); the signed document does not exist.`,
355
+ }));
256
356
  }
257
- if (envelope.envelopeItems?.[0]?.id === undefined) {
357
+ const envelopeItemId = envelope.envelopeItems?.[0]?.id;
358
+ if (envelopeItemId === undefined) {
258
359
  return Effect.fail(new SignatureKitError({
259
- code: SignatureKitErrorCodeValue.responseShape,
360
+ code: SignatureKitErrorCodeValue.unsupportedOperation,
260
361
  retryable: false,
261
362
  provider: PROVIDER,
262
- operation: SignatureKitOperationValue.remoteDownload,
363
+ operation: DocumensoOperation.download,
263
364
  reason: `Documenso envelope ${envelopeId} has no downloadable item ID.`,
264
365
  }));
265
366
  }
266
- return downloadSignedEnvelopeItem(http, options, baseUrl, envelope.envelopeItems[0].id);
367
+ return requestEnvelopeSignedBytes(http, options, baseUrl, envelopeSignedDownloadUrl(baseUrl, envelopeItemId));
267
368
  }));
268
- const createRemoteRequest = (http, options, baseUrl, input) => createEnvelope(http, options, baseUrl, input).pipe(Effect.flatMap((envelope) => {
369
+ const shouldRollbackDocumensoCreate = (error) => error.code === SignatureKitErrorCodeValue.http &&
370
+ error.status !== undefined &&
371
+ error.status >= 400 &&
372
+ error.status < 500 &&
373
+ error.status !== 408 &&
374
+ error.status !== 409 &&
375
+ error.status !== 429;
376
+ const createDocumensoEnvelopeRequest = (http, options, baseUrl, input) => createEnvelope(http, options, baseUrl, input).pipe(Effect.flatMap((envelope) => {
269
377
  if (input.send === false) {
270
378
  return Effect.succeed({
271
379
  provider: PROVIDER,
@@ -275,37 +383,47 @@ const createRemoteRequest = (http, options, baseUrl, input) => createEnvelope(ht
275
383
  detailsUrl: `${baseUrl}/envelope/${documensoPathId(envelope.id)}`,
276
384
  });
277
385
  }
278
- return distributeEnvelope(http, options, baseUrl, input, envelope).pipe(Effect.catch((error) => deleteEnvelope(http, options, baseUrl, envelope.id).pipe(Effect.catch(() => Effect.void), Effect.flatMap(() => Effect.fail(error)))));
386
+ return distributeEnvelope(http, options, baseUrl, input, envelope).pipe(Effect.catchIf(shouldRollbackDocumensoCreate, (error) => deleteEnvelope(http, options, baseUrl, envelope.id).pipe(Effect.ignore, Effect.flatMap(() => Effect.fail(error)))));
279
387
  }));
280
- export const DocumensoSignatureRequestProvider = () => Provider.effect(DocumensoSignatureRequest, Effect.gen(function* () {
281
- const options = yield* DocumensoCredentials;
388
+ const documensoSignatureRequestProvider = Provider.effect(DocumensoSignatureRequest, Effect.gen(function* () {
389
+ const credentials = yield* DocumensoCredentials;
282
390
  const http = yield* SignatureHttpClient;
283
- const baseUrl = documensoBaseUrl(options);
284
391
  return DocumensoSignatureRequest.Provider.of({
285
- diff: ({ olds }) => Effect.succeed(olds === undefined ? undefined : { action: "noop" }),
286
- list: () => listEnvelopes(http, options, baseUrl),
287
- read: ({ output }) => output === undefined
288
- ? Effect.succeed(undefined)
289
- : getEnvelope(http, options, baseUrl, output.id).pipe(Effect.catchIf((error) => error.code === SignatureKitErrorCodeValue.http && error.status === 404, () => Effect.succeed(undefined))),
392
+ nuke: { skip: true },
393
+ diff: documensoSignatureRequestDiff,
394
+ list: () => Effect.succeed([]),
395
+ read: Effect.fn(function* ({ output }) {
396
+ if (output === undefined)
397
+ return undefined;
398
+ const options = yield* credentials;
399
+ const baseUrl = documensoBaseUrl(options);
400
+ return yield* getEnvelope(http, options, baseUrl, output.id).pipe(Effect.catchIf((error) => error.code === SignatureKitErrorCodeValue.http && error.status === 404, () => Effect.succeed(undefined)));
401
+ }),
290
402
  reconcile: Effect.fn(function* ({ news, output }) {
291
403
  if (output !== undefined)
292
404
  return output;
293
- const input = yield* remoteSignatureInputFromResourceProps(PROVIDER, news);
294
- return yield* createRemoteRequest(http, options, baseUrl, input);
405
+ const options = yield* credentials;
406
+ const baseUrl = documensoBaseUrl(options);
407
+ const input = yield* documensoSignatureRequestInputFromResourceProps(news);
408
+ return yield* createDocumensoEnvelopeRequest(http, options, baseUrl, input);
409
+ }),
410
+ delete: Effect.fn(function* ({ output }) {
411
+ const options = yield* credentials;
412
+ const baseUrl = documensoBaseUrl(options);
413
+ return yield* deleteEnvelope(http, options, baseUrl, output.id);
295
414
  }),
296
- delete: ({ output }) => deleteEnvelope(http, options, baseUrl, output.id),
297
415
  });
298
416
  }));
299
- export class DocumensoProviders extends Provider.ProviderCollection()(DOCUMENSO_PROVIDER_COLLECTION_ID) {
417
+ class DocumensoProviders extends Provider.ProviderCollection()(DOCUMENSO_PROVIDER_COLLECTION_ID) {
300
418
  }
301
- export const providers = (options) => Layer.effect(DocumensoProviders, Provider.collection([DocumensoSignatureRequest])).pipe(Layer.provide(DocumensoSignatureRequestProvider()), Layer.provide(documensoCredentialsLayer(options)));
419
+ export const providers = (options) => Layer.effect(DocumensoProviders, Provider.collection([DocumensoSignatureRequest])).pipe(Layer.provide(Layer.fresh(documensoSignatureRequestProvider)), Layer.provide(documensoCredentialsLayer(options)));
302
420
  export const getDocumensoSignatureRequest = (options, id) => Effect.gen(function* () {
303
421
  const valid = yield* Schema.decodeUnknownEffect(DocumensoProviderOptionsSchema)(options).pipe(Effect.mapError((issue) => new SignatureKitError({
304
422
  code: SignatureKitErrorCodeValue.invalidInput,
305
423
  retryable: false,
306
424
  provider: PROVIDER,
307
425
  operation: SignatureKitOperationValue.schemaDecode,
308
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
426
+ schemaName: DocumensoSchemaName.providerOptions,
309
427
  issueMessage: String(issue),
310
428
  })));
311
429
  const http = yield* SignatureHttpClient;
@@ -317,7 +435,7 @@ export const listDocumensoSignatureRequests = (options) => Effect.gen(function*
317
435
  retryable: false,
318
436
  provider: PROVIDER,
319
437
  operation: SignatureKitOperationValue.schemaDecode,
320
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
438
+ schemaName: DocumensoSchemaName.providerOptions,
321
439
  issueMessage: String(issue),
322
440
  })));
323
441
  const http = yield* SignatureHttpClient;
@@ -329,7 +447,7 @@ export const cancelDocumensoSignatureRequest = (options, id) => Effect.gen(funct
329
447
  retryable: false,
330
448
  provider: PROVIDER,
331
449
  operation: SignatureKitOperationValue.schemaDecode,
332
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
450
+ schemaName: DocumensoSchemaName.providerOptions,
333
451
  issueMessage: String(issue),
334
452
  })));
335
453
  const http = yield* SignatureHttpClient;
@@ -341,7 +459,7 @@ export const deleteDocumensoSignatureRequest = (options, id) => Effect.gen(funct
341
459
  retryable: false,
342
460
  provider: PROVIDER,
343
461
  operation: SignatureKitOperationValue.schemaDecode,
344
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
462
+ schemaName: DocumensoSchemaName.providerOptions,
345
463
  issueMessage: String(issue),
346
464
  })));
347
465
  const http = yield* SignatureHttpClient;
@@ -353,9 +471,24 @@ export const downloadDocumensoSignedDocument = (options, envelopeId) => Effect.g
353
471
  retryable: false,
354
472
  provider: PROVIDER,
355
473
  operation: SignatureKitOperationValue.schemaDecode,
356
- schemaName: SignatureKitSchemaNameValue.documensoProviderOptions,
474
+ schemaName: DocumensoSchemaName.providerOptions,
357
475
  issueMessage: String(issue),
358
476
  })));
359
477
  const http = yield* SignatureHttpClient;
360
478
  return yield* downloadSignedEnvelopeDocument(http, valid, documensoBaseUrl(valid), envelopeId);
361
479
  });
480
+ export const waitForDocumensoSignatureRequest = Effect.fn(function* (options, id, pollInterval) {
481
+ const interval = yield* Schema.decodeUnknownEffect(Schema.Duration.check(Schema.makeFilter((value) => Duration.isFinite(value) && Duration.isPositive(value))))(pollInterval).pipe(Effect.mapError((issue) => new SignatureKitError({
482
+ code: SignatureKitErrorCodeValue.invalidInput,
483
+ retryable: false,
484
+ provider: PROVIDER,
485
+ operation: SignatureKitOperationValue.schemaDecode,
486
+ schemaName: "DocumensoPollInterval",
487
+ issueMessage: String(issue),
488
+ reason: "Polling requires a positive, finite interval.",
489
+ })));
490
+ return yield* getDocumensoSignatureRequest(options, id).pipe(Effect.repeat({
491
+ while: (request) => Match.value(request.state).pipe(Match.whenOr("draft", "sent", () => true), Match.whenOr("completed", "cancelled", "deleted", "declined", "expired", () => false), Match.exhaustive),
492
+ schedule: Schedule.spaced(interval),
493
+ }));
494
+ });
package/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@signature-kit/documenso",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/Licitei/signature-kit.git"
8
+ },
5
9
  "files": [
6
10
  "dist",
7
11
  "README.md",
@@ -22,21 +26,21 @@
22
26
  "access": "public"
23
27
  },
24
28
  "scripts": {
25
- "build": "tsc -b tsconfig.json",
26
- "typecheck": "tsc -p tsconfig.json --noEmit",
27
29
  "test": "vitest run"
28
30
  },
29
31
  "dependencies": {
30
- "@signature-kit/core": "^0.2.0",
31
- "alchemy": "2.0.0-beta.57",
32
- "effect": "4.0.0-beta.86"
32
+ "@signature-kit/crypto": "^0.2.1",
33
+ "@signature-kit/http": "^0.1.0",
34
+ "@signature-kit/signatures": "^0.2.0",
35
+ "alchemy": "2.0.0-beta.83",
36
+ "effect": "4.0.5"
33
37
  },
34
38
  "nx": {
35
39
  "targets": {
36
40
  "npm-pack": {
37
41
  "executor": "nx:run-commands",
38
42
  "options": {
39
- "command": "npm pack --dry-run --json",
43
+ "command": "bun pm pack --dry-run",
40
44
  "cwd": "{projectRoot}"
41
45
  }
42
46
  },