@quantidia/sdk 1.0.4
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 +43 -0
- package/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/client/apis/DefaultApi.d.ts +27 -0
- package/dist/client/apis/index.d.ts +1 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/models/ApiRestCoreAuthLoginPostRequest.d.ts +38 -0
- package/dist/client/models/index.d.ts +1 -0
- package/dist/client/runtime.d.ts +184 -0
- package/dist/quantidia-sdk.cjs +1 -0
- package/dist/quantidia-sdk.es.js +1 -0
- package/dist/quantidia-sdk.umd.js +97 -0
- package/dist/quantidia-sdk.umd.min.js +1 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/ui.d.ts +115 -0
- package/dist/src/umd.d.ts +1 -0
- package/dist/ui.cjs +1 -0
- package/dist/ui.js +1 -0
- package/package.json +62 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@quantidia/sdk` will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
|
|
6
|
+
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## [1.0.4] - 2024-01-01
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
- Package renamed from `trusthub-sdk-js` to `@quantidia/sdk`
|
|
14
|
+
- Build outputs renamed to `quantidia-sdk.*` for consistency
|
|
15
|
+
- UMD global renamed from `TrustHub` to `Quantidia` (`window.Quantidia`)
|
|
16
|
+
- Added non-minified UMD build (`quantidia-sdk.umd.js`) for debugging
|
|
17
|
+
- Added `LICENSE`, `CHANGELOG.md` to published package files
|
|
18
|
+
- Fixed `types` field path in `package.json`
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
- GitHub Actions workflow for automated NPM publishing
|
|
22
|
+
- `browser`, `jsdelivr`, `unpkg` fields in `package.json`
|
|
23
|
+
- Professional documentation in `docs/`
|
|
24
|
+
- CDN usage example in `examples/html-cdn/`
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## [1.0.3] - 2024-01-01
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
- Initial `./ui` export for embedded signing UI components
|
|
32
|
+
- `openSigningWithLogin` supporting simple (user/pass) and advanced (authLogin) modes
|
|
33
|
+
- Multi-document signing via `docId` / `docIds` parameters
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## [1.0.0] - 2024-01-01
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
- Initial release
|
|
41
|
+
- OpenAPI-generated client for TrustHub REST API
|
|
42
|
+
- TypeScript typings
|
|
43
|
+
- ESM, CJS, and UMD builds via Webpack
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Quantidia
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TrustHub API
|
|
3
|
+
* API pública de TrustHub
|
|
4
|
+
*
|
|
5
|
+
* The version of the OpenAPI document: 1.0.0
|
|
6
|
+
*
|
|
7
|
+
*
|
|
8
|
+
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
|
9
|
+
* https://openapi-generator.tech
|
|
10
|
+
* Do not edit the class manually.
|
|
11
|
+
*/
|
|
12
|
+
import * as runtime from '../runtime';
|
|
13
|
+
import type { ApiRestCoreAuthLoginPostRequest } from '../models/index';
|
|
14
|
+
export interface ApiRestCoreAuthLoginPostOperationRequest {
|
|
15
|
+
apiRestCoreAuthLoginPostRequest: ApiRestCoreAuthLoginPostRequest;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
*
|
|
19
|
+
*/
|
|
20
|
+
export declare class DefaultApi extends runtime.BaseAPI {
|
|
21
|
+
/**
|
|
22
|
+
*/
|
|
23
|
+
apiRestCoreAuthLoginPostRaw(requestParameters: ApiRestCoreAuthLoginPostOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>>;
|
|
24
|
+
/**
|
|
25
|
+
*/
|
|
26
|
+
apiRestCoreAuthLoginPost(requestParameters: ApiRestCoreAuthLoginPostOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void>;
|
|
27
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './DefaultApi';
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TrustHub API
|
|
3
|
+
* API pública de TrustHub
|
|
4
|
+
*
|
|
5
|
+
* The version of the OpenAPI document: 1.0.0
|
|
6
|
+
*
|
|
7
|
+
*
|
|
8
|
+
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
|
9
|
+
* https://openapi-generator.tech
|
|
10
|
+
* Do not edit the class manually.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
*
|
|
14
|
+
* @export
|
|
15
|
+
* @interface ApiRestCoreAuthLoginPostRequest
|
|
16
|
+
*/
|
|
17
|
+
export interface ApiRestCoreAuthLoginPostRequest {
|
|
18
|
+
/**
|
|
19
|
+
*
|
|
20
|
+
* @type {string}
|
|
21
|
+
* @memberof ApiRestCoreAuthLoginPostRequest
|
|
22
|
+
*/
|
|
23
|
+
username?: string;
|
|
24
|
+
/**
|
|
25
|
+
*
|
|
26
|
+
* @type {string}
|
|
27
|
+
* @memberof ApiRestCoreAuthLoginPostRequest
|
|
28
|
+
*/
|
|
29
|
+
password?: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Check if a given object implements the ApiRestCoreAuthLoginPostRequest interface.
|
|
33
|
+
*/
|
|
34
|
+
export declare function instanceOfApiRestCoreAuthLoginPostRequest(value: object): value is ApiRestCoreAuthLoginPostRequest;
|
|
35
|
+
export declare function ApiRestCoreAuthLoginPostRequestFromJSON(json: any): ApiRestCoreAuthLoginPostRequest;
|
|
36
|
+
export declare function ApiRestCoreAuthLoginPostRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): ApiRestCoreAuthLoginPostRequest;
|
|
37
|
+
export declare function ApiRestCoreAuthLoginPostRequestToJSON(json: any): ApiRestCoreAuthLoginPostRequest;
|
|
38
|
+
export declare function ApiRestCoreAuthLoginPostRequestToJSONTyped(value?: ApiRestCoreAuthLoginPostRequest | null, ignoreDiscriminator?: boolean): any;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './ApiRestCoreAuthLoginPostRequest';
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TrustHub API
|
|
3
|
+
* API pública de TrustHub
|
|
4
|
+
*
|
|
5
|
+
* The version of the OpenAPI document: 1.0.0
|
|
6
|
+
*
|
|
7
|
+
*
|
|
8
|
+
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
|
9
|
+
* https://openapi-generator.tech
|
|
10
|
+
* Do not edit the class manually.
|
|
11
|
+
*/
|
|
12
|
+
export declare const BASE_PATH: string;
|
|
13
|
+
export interface ConfigurationParameters {
|
|
14
|
+
basePath?: string;
|
|
15
|
+
fetchApi?: FetchAPI;
|
|
16
|
+
middleware?: Middleware[];
|
|
17
|
+
queryParamsStringify?: (params: HTTPQuery) => string;
|
|
18
|
+
username?: string;
|
|
19
|
+
password?: string;
|
|
20
|
+
apiKey?: string | Promise<string> | ((name: string) => string | Promise<string>);
|
|
21
|
+
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>);
|
|
22
|
+
headers?: HTTPHeaders;
|
|
23
|
+
credentials?: RequestCredentials;
|
|
24
|
+
}
|
|
25
|
+
export declare class Configuration {
|
|
26
|
+
private configuration;
|
|
27
|
+
constructor(configuration?: ConfigurationParameters);
|
|
28
|
+
set config(configuration: Configuration);
|
|
29
|
+
get basePath(): string;
|
|
30
|
+
get fetchApi(): FetchAPI | undefined;
|
|
31
|
+
get middleware(): Middleware[];
|
|
32
|
+
get queryParamsStringify(): (params: HTTPQuery) => string;
|
|
33
|
+
get username(): string | undefined;
|
|
34
|
+
get password(): string | undefined;
|
|
35
|
+
get apiKey(): ((name: string) => string | Promise<string>) | undefined;
|
|
36
|
+
get accessToken(): ((name?: string, scopes?: string[]) => string | Promise<string>) | undefined;
|
|
37
|
+
get headers(): HTTPHeaders | undefined;
|
|
38
|
+
get credentials(): RequestCredentials | undefined;
|
|
39
|
+
}
|
|
40
|
+
export declare const DefaultConfig: Configuration;
|
|
41
|
+
/**
|
|
42
|
+
* This is the base class for all generated API classes.
|
|
43
|
+
*/
|
|
44
|
+
export declare class BaseAPI {
|
|
45
|
+
protected configuration: Configuration;
|
|
46
|
+
private static readonly jsonRegex;
|
|
47
|
+
private middleware;
|
|
48
|
+
constructor(configuration?: Configuration);
|
|
49
|
+
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]): T;
|
|
50
|
+
withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>): T;
|
|
51
|
+
withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>): T;
|
|
52
|
+
/**
|
|
53
|
+
* Check if the given MIME is a JSON MIME.
|
|
54
|
+
* JSON MIME examples:
|
|
55
|
+
* application/json
|
|
56
|
+
* application/json; charset=UTF8
|
|
57
|
+
* APPLICATION/JSON
|
|
58
|
+
* application/vnd.company+json
|
|
59
|
+
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
|
60
|
+
* @return True if the given MIME is JSON, false otherwise.
|
|
61
|
+
*/
|
|
62
|
+
protected isJsonMime(mime: string | null | undefined): boolean;
|
|
63
|
+
protected request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response>;
|
|
64
|
+
private createFetchParams;
|
|
65
|
+
private fetchApi;
|
|
66
|
+
/**
|
|
67
|
+
* Create a shallow clone of `this` by constructing a new instance
|
|
68
|
+
* and then shallow cloning data members.
|
|
69
|
+
*/
|
|
70
|
+
private clone;
|
|
71
|
+
}
|
|
72
|
+
export declare class ResponseError extends Error {
|
|
73
|
+
response: Response;
|
|
74
|
+
name: "ResponseError";
|
|
75
|
+
constructor(response: Response, msg?: string);
|
|
76
|
+
}
|
|
77
|
+
export declare class FetchError extends Error {
|
|
78
|
+
cause: Error;
|
|
79
|
+
name: "FetchError";
|
|
80
|
+
constructor(cause: Error, msg?: string);
|
|
81
|
+
}
|
|
82
|
+
export declare class RequiredError extends Error {
|
|
83
|
+
field: string;
|
|
84
|
+
name: "RequiredError";
|
|
85
|
+
constructor(field: string, msg?: string);
|
|
86
|
+
}
|
|
87
|
+
export declare const COLLECTION_FORMATS: {
|
|
88
|
+
csv: string;
|
|
89
|
+
ssv: string;
|
|
90
|
+
tsv: string;
|
|
91
|
+
pipes: string;
|
|
92
|
+
};
|
|
93
|
+
export type FetchAPI = WindowOrWorkerGlobalScope['fetch'];
|
|
94
|
+
export type Json = any;
|
|
95
|
+
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
|
|
96
|
+
export type HTTPHeaders = {
|
|
97
|
+
[key: string]: string;
|
|
98
|
+
};
|
|
99
|
+
export type HTTPQuery = {
|
|
100
|
+
[key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery;
|
|
101
|
+
};
|
|
102
|
+
export type HTTPBody = Json | FormData | URLSearchParams;
|
|
103
|
+
export type HTTPRequestInit = {
|
|
104
|
+
headers?: HTTPHeaders;
|
|
105
|
+
method: HTTPMethod;
|
|
106
|
+
credentials?: RequestCredentials;
|
|
107
|
+
body?: HTTPBody;
|
|
108
|
+
};
|
|
109
|
+
export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
|
|
110
|
+
export type InitOverrideFunction = (requestContext: {
|
|
111
|
+
init: HTTPRequestInit;
|
|
112
|
+
context: RequestOpts;
|
|
113
|
+
}) => Promise<RequestInit>;
|
|
114
|
+
export interface FetchParams {
|
|
115
|
+
url: string;
|
|
116
|
+
init: RequestInit;
|
|
117
|
+
}
|
|
118
|
+
export interface RequestOpts {
|
|
119
|
+
path: string;
|
|
120
|
+
method: HTTPMethod;
|
|
121
|
+
headers: HTTPHeaders;
|
|
122
|
+
query?: HTTPQuery;
|
|
123
|
+
body?: HTTPBody;
|
|
124
|
+
}
|
|
125
|
+
export declare function querystring(params: HTTPQuery, prefix?: string): string;
|
|
126
|
+
export declare function exists(json: any, key: string): boolean;
|
|
127
|
+
export declare function mapValues(data: any, fn: (item: any) => any): {
|
|
128
|
+
[key: string]: any;
|
|
129
|
+
};
|
|
130
|
+
export declare function canConsumeForm(consumes: Consume[]): boolean;
|
|
131
|
+
export interface Consume {
|
|
132
|
+
contentType: string;
|
|
133
|
+
}
|
|
134
|
+
export interface RequestContext {
|
|
135
|
+
fetch: FetchAPI;
|
|
136
|
+
url: string;
|
|
137
|
+
init: RequestInit;
|
|
138
|
+
}
|
|
139
|
+
export interface ResponseContext {
|
|
140
|
+
fetch: FetchAPI;
|
|
141
|
+
url: string;
|
|
142
|
+
init: RequestInit;
|
|
143
|
+
response: Response;
|
|
144
|
+
}
|
|
145
|
+
export interface ErrorContext {
|
|
146
|
+
fetch: FetchAPI;
|
|
147
|
+
url: string;
|
|
148
|
+
init: RequestInit;
|
|
149
|
+
error: unknown;
|
|
150
|
+
response?: Response;
|
|
151
|
+
}
|
|
152
|
+
export interface Middleware {
|
|
153
|
+
pre?(context: RequestContext): Promise<FetchParams | void>;
|
|
154
|
+
post?(context: ResponseContext): Promise<Response | void>;
|
|
155
|
+
onError?(context: ErrorContext): Promise<Response | void>;
|
|
156
|
+
}
|
|
157
|
+
export interface ApiResponse<T> {
|
|
158
|
+
raw: Response;
|
|
159
|
+
value(): Promise<T>;
|
|
160
|
+
}
|
|
161
|
+
export interface ResponseTransformer<T> {
|
|
162
|
+
(json: any): T;
|
|
163
|
+
}
|
|
164
|
+
export declare class JSONApiResponse<T> {
|
|
165
|
+
raw: Response;
|
|
166
|
+
private transformer;
|
|
167
|
+
constructor(raw: Response, transformer?: ResponseTransformer<T>);
|
|
168
|
+
value(): Promise<T>;
|
|
169
|
+
}
|
|
170
|
+
export declare class VoidApiResponse {
|
|
171
|
+
raw: Response;
|
|
172
|
+
constructor(raw: Response);
|
|
173
|
+
value(): Promise<void>;
|
|
174
|
+
}
|
|
175
|
+
export declare class BlobApiResponse {
|
|
176
|
+
raw: Response;
|
|
177
|
+
constructor(raw: Response);
|
|
178
|
+
value(): Promise<Blob>;
|
|
179
|
+
}
|
|
180
|
+
export declare class TextApiResponse {
|
|
181
|
+
raw: Response;
|
|
182
|
+
constructor(raw: Response);
|
|
183
|
+
value(): Promise<string>;
|
|
184
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{ApiRestCoreAuthLoginPostRequestFromJSON:()=>A,ApiRestCoreAuthLoginPostRequestFromJSONTyped:()=>b,ApiRestCoreAuthLoginPostRequestToJSON:()=>P,ApiRestCoreAuthLoginPostRequestToJSONTyped:()=>C,BASE_PATH:()=>n,BaseAPI:()=>s,BlobApiResponse:()=>m,COLLECTION_FORMATS:()=>u,Configuration:()=>r,DefaultApi:()=>q,DefaultConfig:()=>o,FetchError:()=>a,JSONApiResponse:()=>g,RequiredError:()=>c,ResponseError:()=>i,TextApiResponse:()=>y,VoidApiResponse:()=>w,canConsumeForm:()=>l,exists:()=>f,instanceOfApiRestCoreAuthLoginPostRequest:()=>R,mapValues:()=>p,querystring:()=>h});const n="https://api.dev.trusthub.cloud".replace(/\/+$/,"");class r{constructor(t={}){this.configuration=t}set config(t){this.configuration=t}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:n}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||h}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const t=this.configuration.apiKey;if(t)return"function"==typeof t?t:()=>t}get accessToken(){const t=this.configuration.accessToken;if(t)return"function"==typeof t?t:async()=>t}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const o=new r;class s{constructor(t=o){this.configuration=t,this.fetchApi=async(t,e)=>{let n,r={url:t,init:e};for(const t of this.middleware)t.pre&&(r=await t.pre({fetch:this.fetchApi,...r})||r);try{n=await(this.configuration.fetchApi||fetch)(r.url,r.init)}catch(t){for(const e of this.middleware)e.onError&&(n=await e.onError({fetch:this.fetchApi,url:r.url,init:r.init,error:t,response:n?n.clone():void 0})||n);if(void 0===n)throw t instanceof Error?new a(t,"The request failed and the interceptors did not return an alternative response"):t}for(const t of this.middleware)t.post&&(n=await t.post({fetch:this.fetchApi,url:r.url,init:r.init,response:n.clone()})||n);return n},this.middleware=t.middleware}withMiddleware(...t){const e=this.clone();return e.middleware=e.middleware.concat(...t),e}withPreMiddleware(...t){const e=t.map(t=>({pre:t}));return this.withMiddleware(...e)}withPostMiddleware(...t){const e=t.map(t=>({post:t}));return this.withMiddleware(...e)}isJsonMime(t){return!!t&&s.jsonRegex.test(t)}async request(t,e){const{url:n,init:r}=await this.createFetchParams(t,e),o=await this.fetchApi(n,r);if(o&&o.status>=200&&o.status<300)return o;throw new i(o,"Response returned an error code")}async createFetchParams(t,e){let n=this.configuration.basePath+t.path;void 0!==t.query&&0!==Object.keys(t.query).length&&(n+="?"+this.configuration.queryParamsStringify(t.query));const r=Object.assign({},this.configuration.headers,t.headers);Object.keys(r).forEach(t=>void 0===r[t]?delete r[t]:{});const o="function"==typeof e?e:async()=>e,s={method:t.method,headers:r,body:t.body,credentials:this.configuration.credentials},i={...s,...await o({init:s,context:t})};let a;var c;c=i.body,a="undefined"!=typeof FormData&&c instanceof FormData||i.body instanceof URLSearchParams||function(t){return"undefined"!=typeof Blob&&t instanceof Blob}(i.body)?i.body:this.isJsonMime(r["Content-Type"])?JSON.stringify(i.body):i.body;return{url:n,init:{...i,body:a}}}clone(){const t=new(0,this.constructor)(this.configuration);return t.middleware=this.middleware.slice(),t}}s.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");class i extends Error{constructor(t,e){super(e),this.response=t,this.name="ResponseError"}}class a extends Error{constructor(t,e){super(e),this.cause=t,this.name="FetchError"}}class c extends Error{constructor(t,e){super(e),this.field=t,this.name="RequiredError"}}const u={csv:",",ssv:" ",tsv:"\t",pipes:"|"};function h(t,e=""){return Object.keys(t).map(n=>d(n,t[n],e)).filter(t=>t.length>0).join("&")}function d(t,e,n=""){const r=n+(n.length?`[${t}]`:t);if(e instanceof Array){const t=e.map(t=>encodeURIComponent(String(t))).join(`&${encodeURIComponent(r)}=`);return`${encodeURIComponent(r)}=${t}`}if(e instanceof Set){return d(t,Array.from(e),n)}return e instanceof Date?`${encodeURIComponent(r)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?h(e,r):`${encodeURIComponent(r)}=${encodeURIComponent(String(e))}`}function f(t,e){const n=t[e];return null!=n}function p(t,e){const n={};for(const r of Object.keys(t))n[r]=e(t[r]);return n}function l(t){for(const e of t)if("multipart/form-data"===e.contentType)return!0;return!1}class g{constructor(t,e=t=>t){this.raw=t,this.transformer=e}async value(){return this.transformer(await this.raw.json())}}class w{constructor(t){this.raw=t}async value(){}}class m{constructor(t){this.raw=t}async value(){return await this.raw.blob()}}class y{constructor(t){this.raw=t}async value(){return await this.raw.text()}}function R(t){return!0}function A(t){return b(t,!1)}function b(t,e){return null==t?t:{username:null==t.username?void 0:t.username,password:null==t.password?void 0:t.password}}function P(t){return C(t,!1)}function C(t,e=!1){return null==t?t:{username:t.username,password:t.password}}class q extends s{async apiRestCoreAuthLoginPostRaw(t,e){if(null==t.apiRestCoreAuthLoginPostRequest)throw new c("apiRestCoreAuthLoginPostRequest",'Required parameter "apiRestCoreAuthLoginPostRequest" was null or undefined when calling apiRestCoreAuthLoginPost().');const n={"Content-Type":"application/json"};const r=await this.request({path:"/api/rest/core/auth/login",method:"POST",headers:n,query:{},body:P(t.apiRestCoreAuthLoginPostRequest)},e);return new w(r)}async apiRestCoreAuthLoginPost(t,e){await this.apiRestCoreAuthLoginPostRaw(t,e)}}module.exports=e})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="https://api.dev.trusthub.cloud".replace(/\/+$/,"");class e{constructor(t={}){this.configuration=t}set config(t){this.configuration=t}get basePath(){return null!=this.configuration.basePath?this.configuration.basePath:t}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||c}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){const t=this.configuration.apiKey;if(t)return"function"==typeof t?t:()=>t}get accessToken(){const t=this.configuration.accessToken;if(t)return"function"==typeof t?t:async()=>t}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}}const n=new e;class r{constructor(t=n){this.configuration=t,this.fetchApi=async(t,e)=>{let n,r={url:t,init:e};for(const t of this.middleware)t.pre&&(r=await t.pre({fetch:this.fetchApi,...r})||r);try{n=await(this.configuration.fetchApi||fetch)(r.url,r.init)}catch(t){for(const e of this.middleware)e.onError&&(n=await e.onError({fetch:this.fetchApi,url:r.url,init:r.init,error:t,response:n?n.clone():void 0})||n);if(void 0===n)throw t instanceof Error?new s(t,"The request failed and the interceptors did not return an alternative response"):t}for(const t of this.middleware)t.post&&(n=await t.post({fetch:this.fetchApi,url:r.url,init:r.init,response:n.clone()})||n);return n},this.middleware=t.middleware}withMiddleware(...t){const e=this.clone();return e.middleware=e.middleware.concat(...t),e}withPreMiddleware(...t){const e=t.map(t=>({pre:t}));return this.withMiddleware(...e)}withPostMiddleware(...t){const e=t.map(t=>({post:t}));return this.withMiddleware(...e)}isJsonMime(t){return!!t&&r.jsonRegex.test(t)}async request(t,e){const{url:n,init:r}=await this.createFetchParams(t,e),s=await this.fetchApi(n,r);if(s&&s.status>=200&&s.status<300)return s;throw new o(s,"Response returned an error code")}async createFetchParams(t,e){let n=this.configuration.basePath+t.path;void 0!==t.query&&0!==Object.keys(t.query).length&&(n+="?"+this.configuration.queryParamsStringify(t.query));const r=Object.assign({},this.configuration.headers,t.headers);Object.keys(r).forEach(t=>void 0===r[t]?delete r[t]:{});const o="function"==typeof e?e:async()=>e,s={method:t.method,headers:r,body:t.body,credentials:this.configuration.credentials},i={...s,...await o({init:s,context:t})};let a;var c;c=i.body,a="undefined"!=typeof FormData&&c instanceof FormData||i.body instanceof URLSearchParams||function(t){return"undefined"!=typeof Blob&&t instanceof Blob}(i.body)?i.body:this.isJsonMime(r["Content-Type"])?JSON.stringify(i.body):i.body;return{url:n,init:{...i,body:a}}}clone(){const t=new(0,this.constructor)(this.configuration);return t.middleware=this.middleware.slice(),t}}r.jsonRegex=new RegExp("^(:?application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$","i");class o extends Error{constructor(t,e){super(e),this.response=t,this.name="ResponseError"}}class s extends Error{constructor(t,e){super(e),this.cause=t,this.name="FetchError"}}class i extends Error{constructor(t,e){super(e),this.field=t,this.name="RequiredError"}}const a={csv:",",ssv:" ",tsv:"\t",pipes:"|"};function c(t,e=""){return Object.keys(t).map(n=>u(n,t[n],e)).filter(t=>t.length>0).join("&")}function u(t,e,n=""){const r=n+(n.length?`[${t}]`:t);if(e instanceof Array){const t=e.map(t=>encodeURIComponent(String(t))).join(`&${encodeURIComponent(r)}=`);return`${encodeURIComponent(r)}=${t}`}if(e instanceof Set){return u(t,Array.from(e),n)}return e instanceof Date?`${encodeURIComponent(r)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?c(e,r):`${encodeURIComponent(r)}=${encodeURIComponent(String(e))}`}function h(t,e){const n=t[e];return null!=n}function d(t,e){const n={};for(const r of Object.keys(t))n[r]=e(t[r]);return n}function f(t){for(const e of t)if("multipart/form-data"===e.contentType)return!0;return!1}class l{constructor(t,e=t=>t){this.raw=t,this.transformer=e}async value(){return this.transformer(await this.raw.json())}}class p{constructor(t){this.raw=t}async value(){}}class w{constructor(t){this.raw=t}async value(){return await this.raw.blob()}}class g{constructor(t){this.raw=t}async value(){return await this.raw.text()}}function m(t){return!0}function y(t){return R(t,!1)}function R(t,e){return null==t?t:{username:null==t.username?void 0:t.username,password:null==t.password?void 0:t.password}}function b(t){return P(t,!1)}function P(t,e=!1){return null==t?t:{username:t.username,password:t.password}}class A extends r{async apiRestCoreAuthLoginPostRaw(t,e){if(null==t.apiRestCoreAuthLoginPostRequest)throw new i("apiRestCoreAuthLoginPostRequest",'Required parameter "apiRestCoreAuthLoginPostRequest" was null or undefined when calling apiRestCoreAuthLoginPost().');const n={"Content-Type":"application/json"};const r=await this.request({path:"/api/rest/core/auth/login",method:"POST",headers:n,query:{},body:b(t.apiRestCoreAuthLoginPostRequest)},e);return new p(r)}async apiRestCoreAuthLoginPost(t,e){await this.apiRestCoreAuthLoginPostRaw(t,e)}}export{y as ApiRestCoreAuthLoginPostRequestFromJSON,R as ApiRestCoreAuthLoginPostRequestFromJSONTyped,b as ApiRestCoreAuthLoginPostRequestToJSON,P as ApiRestCoreAuthLoginPostRequestToJSONTyped,t as BASE_PATH,r as BaseAPI,w as BlobApiResponse,a as COLLECTION_FORMATS,e as Configuration,A as DefaultApi,n as DefaultConfig,s as FetchError,l as JSONApiResponse,i as RequiredError,o as ResponseError,g as TextApiResponse,p as VoidApiResponse,f as canConsumeForm,h as exists,m as instanceOfApiRestCoreAuthLoginPostRequest,d as mapValues,c as querystring};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
|
|
3
|
+
* This devtool is neither made for production nor for readable output files.
|
|
4
|
+
* It uses "eval()" calls to create a separate source file in the browser devtools.
|
|
5
|
+
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
|
|
6
|
+
* or disable the default devtool with "devtool: false".
|
|
7
|
+
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
|
|
8
|
+
*/
|
|
9
|
+
/******/ (() => { // webpackBootstrap
|
|
10
|
+
/******/ "use strict";
|
|
11
|
+
/******/ var __webpack_modules__ = ({
|
|
12
|
+
|
|
13
|
+
/***/ "./src/ui.ts":
|
|
14
|
+
/*!*******************!*\
|
|
15
|
+
!*** ./src/ui.ts ***!
|
|
16
|
+
\*******************/
|
|
17
|
+
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
18
|
+
|
|
19
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ addDocument: () => (/* binding */ addDocument),\n/* harmony export */ addDocuments: () => (/* binding */ addDocuments),\n/* harmony export */ clearDocuments: () => (/* binding */ clearDocuments),\n/* harmony export */ clearSignedDocuments: () => (/* binding */ clearSignedDocuments),\n/* harmony export */ close: () => (/* binding */ close),\n/* harmony export */ getSignedDocumentBytes: () => (/* binding */ getSignedDocumentBytes),\n/* harmony export */ init: () => (/* binding */ init),\n/* harmony export */ listSignedDocuments: () => (/* binding */ listSignedDocuments),\n/* harmony export */ openSigning: () => (/* binding */ openSigning),\n/* harmony export */ openSigningWithLogin: () => (/* binding */ openSigningWithLogin),\n/* harmony export */ removeDocument: () => (/* binding */ removeDocument),\n/* harmony export */ removeSignedDocument: () => (/* binding */ removeSignedDocument)\n/* harmony export */ });\nlet loaderEl = null;\nlet loaderHideTimer = null;\nlet loaderHardTimeout = null;\nfunction showLoader() {\n if (!loaderEl)\n return;\n loaderEl.style.display = \"flex\";\n}\nfunction hideLoader() {\n if (!loaderEl)\n return;\n loaderEl.style.display = \"none\";\n if (loaderHideTimer)\n window.clearTimeout(loaderHideTimer);\n if (loaderHardTimeout)\n window.clearTimeout(loaderHardTimeout);\n loaderHideTimer = null;\n loaderHardTimeout = null;\n}\nlet cfg = null;\nlet overlayEl = null;\nlet pending = null;\nlet lastInitMsg = null;\nfunction storeInitMsg(msg) {\n if (!msg)\n return;\n lastInitMsg = { ...(lastInitMsg || {}), ...(msg || {}) };\n}\nfunction sendInitTo(win, origin) {\n if (!win || !origin)\n return;\n const view = cfg?.view ?? \"full\";\n const payload = { ...(lastInitMsg || {}), view };\n // si no hay token, igual mandamos INIT para que el iframe sepa que está embebido\n win.postMessage({ source: \"trusthub_sdk\", type: \"INIT\", ...payload }, origin);\n}\nconst signedStore = new Map();\nfunction makeSignedId() {\n return crypto.randomUUID();\n}\n// API pública para el 3ero\nfunction listSignedDocuments() {\n return Array.from(signedStore.values()).map(({ bytes, ...m }) => m);\n}\nfunction getSignedDocumentBytes(id) {\n const d = signedStore.get(id);\n return d ? new Uint8Array(d.bytes) : null; // copia\n}\nfunction removeSignedDocument(id) {\n signedStore.delete(id);\n}\nfunction clearSignedDocuments() {\n signedStore.clear();\n}\nconst docStore = new Map();\nlet currentIframeWin = null;\nlet currentIframeOrigin = null;\nlet currentIframeEl = null;\nlet waitingUiReady = false;\nfunction revealFrame() {\n try {\n if (currentIframeEl)\n currentIframeEl.style.opacity = \"1\";\n }\n catch { }\n}\nfunction concealFrame() {\n try {\n if (currentIframeEl)\n currentIframeEl.style.opacity = \"0\";\n }\n catch { }\n}\nfunction makeDocId() {\n return crypto.randomUUID();\n}\nasync function fileToBytes(file) {\n const ab = await file.arrayBuffer();\n return new Uint8Array(ab);\n}\n// ✅ API pública\nasync function addDocument(file) {\n if (!file)\n throw new Error(\"file requerido\");\n const id = makeDocId();\n const bytes = await fileToBytes(file);\n docStore.set(id, {\n id,\n name: file.name || \"document.pdf\",\n mime: file.type || \"application/pdf\",\n bytes,\n size: bytes.byteLength,\n createdAt: Date.now(),\n });\n return id;\n}\nasync function addDocuments(files) {\n const arr = Array.from(files instanceof FileList ? files : files);\n const ids = [];\n for (const f of arr)\n ids.push(await addDocument(f));\n return ids;\n}\nfunction removeDocument(docId) {\n docStore.delete(docId);\n}\nfunction clearDocuments() {\n docStore.clear();\n}\n/* ========================= */\nconst log = (...a) => console.log(\"[TrustHub SDK]\", ...a);\n// --------- PERF / WARMUP (opt: no rompe nada) ----------\nlet lastFrameT0 = 0;\nlet lastFrameUrl = null;\nfunction safeOrigin(urlStr) {\n try {\n return new URL(urlStr, window.location.origin).origin;\n }\n catch {\n return \"\";\n }\n}\nfunction pickSupportedLng(input) {\n if (!input)\n return null;\n // Soporta \"es-AR,es;q=0.9,en-US;q=0.8\"\n const first = String(input).split(\",\")[0]?.trim();\n if (!first)\n return null;\n const code = first.replace(/_/g, \"-\").toLowerCase();\n if (code.startsWith(\"es\"))\n return \"es-AR\";\n if (code.startsWith(\"it\"))\n return \"it-IT\";\n if (code.startsWith(\"en\"))\n return \"en-US\";\n return null;\n}\nfunction ensureLink(rel, href) {\n try {\n const id = `th-sdk-${rel}-${href}`;\n if (document.getElementById(id))\n return;\n const l = document.createElement(\"link\");\n l.id = id;\n l.rel = rel;\n l.href = href;\n // preconnect cross-origin\n if (rel === \"preconnect\")\n l.crossOrigin = \"anonymous\";\n document.head.appendChild(l);\n }\n catch { }\n}\nfunction warmupOrigin(baseUrl) {\n const o = safeOrigin(baseUrl);\n if (!o)\n return;\n ensureLink(\"dns-prefetch\", o);\n ensureLink(\"preconnect\", o);\n}\n// Warm “best effort”: no bloquea, no rompe si el browser lo ignora\nasync function warmFetch(url) {\n try {\n // no-cors: sirve para calentar handshake/cache en algunos casos\n await fetch(url, { mode: \"no-cors\", cache: \"force-cache\" });\n }\n catch { }\n}\n// -------------------------------------------------------\nconst TRACE_STATE_FIXED = \"es=s:1\";\nfunction hex(bytes) {\n const a = new Uint8Array(bytes);\n crypto.getRandomValues(a);\n return Array.from(a, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n// Nuevo root trace para esta request (válido W3C)\nfunction makeTraceparent() {\n const traceId = hex(16); // 16 bytes => 32 hex\n const spanId = hex(8); // 8 bytes => 16 hex\n return `00-${traceId}-${spanId}-01`;\n}\nfunction operationFromUrl(urlStr) {\n try {\n const u = new URL(urlStr, window.location.origin);\n const p = u.pathname;\n if (p.includes(\"/auth/\"))\n return \"auth\";\n if (p.includes(\"/sign/\"))\n return \"sign\";\n if (p.includes(\"/verify/\"))\n return \"verify\";\n if (p.includes(\"/timestamp/\"))\n return \"timestamp\";\n return \"sdk\";\n }\n catch {\n return \"sdk\";\n }\n}\nfunction buildBaggage(channel, operation) {\n // lo que te pidieron fijo:\n // baggage: tenant=trusthub fijo\n // + tu marca de canal\n // + operation por API\n return `tenant=trusthub,channel=${channel},operation=${operation}`;\n}\nfunction init(opts) {\n cfg = { ...opts };\n listen();\n // ✅ warmup básico de origin (no bloquea)\n warmupOrigin(opts.baseUrl);\n log(\"init\", opts);\n}\nfunction css(el, s) {\n Object.assign(el.style, s);\n}\nfunction ensureLoaderStyles() {\n if (document.getElementById(\"th-sdk-loader-style\"))\n return;\n const st = document.createElement(\"style\");\n st.id = \"th-sdk-loader-style\";\n st.textContent = `\n .th-sdk-loader {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n background: rgba(255,255,255,.92);\n z-index: 1; /* debajo del botón close (zIndex 2) */\n pointer-events: auto;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;\n }\n .th-sdk-spinner {\n width: 28px;\n height: 28px;\n border-radius: 999px;\n border: 3px solid rgba(0,0,0,.15);\n border-top-color: rgba(0,0,0,.75);\n animation: thsdkspin .9s linear infinite;\n }\n @keyframes thsdkspin { to { transform: rotate(360deg); } }\n .th-sdk-loader-text {\n font-size: 14px;\n color: rgba(0,0,0,.75);\n font-weight: 600;\n }\n `;\n document.head.appendChild(st);\n}\nfunction overlayUI() {\n ensureLoaderStyles();\n const bg = document.createElement(\"div\");\n css(bg, {\n position: \"fixed\",\n inset: \"0\",\n background: \"rgba(0,0,0,.45)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n zIndex: \"2147483646\",\n });\n const wrap = document.createElement(\"div\");\n css(wrap, {\n position: \"relative\",\n width: \"90%\",\n height: \"80%\",\n maxWidth: \"1000px\",\n borderRadius: \"12px\",\n overflow: \"hidden\",\n background: \"#fff\",\n boxShadow: \"0 10px 30px rgba(0,0,0,.3)\",\n });\n // ✅ Loader (arranca visible)\n const loader = document.createElement(\"div\");\n loader.className = \"th-sdk-loader\";\n loader.innerHTML = `<div class=\"th-sdk-spinner\"></div><div class=\"th-sdk-loader-text\">Loading Quantidia SDK…</div>`;\n // Close button (tu versión)\n const x = document.createElement(\"button\");\n x.type = \"button\";\n x.setAttribute(\"aria-label\", \"Close\");\n css(x, {\n position: \"absolute\",\n top: \"20px\",\n right: \"18px\",\n margin: \"0\",\n border: \"0\",\n cursor: \"pointer\",\n zIndex: \"2\",\n backgroundColor: \"transparent\",\n backgroundImage: \"url('https://dev.trusthub.cloud/images/icons/Close.svg')\",\n backgroundRepeat: \"no-repeat\",\n backgroundPosition: \"center\",\n width: \"22px\",\n height: \"22px\",\n });\n x.innerHTML = \"\";\n x.onclick = close;\n const f = document.createElement(\"iframe\");\n f.allow = \"hid; usb; serial; clipboard-read; clipboard-write; fullscreen\";\n f.allowFullscreen = true;\n f.referrerPolicy = \"strict-origin-when-cross-origin\";\n css(f, {\n width: \"100%\",\n height: \"100%\",\n border: \"0\",\n opacity: \"0\",\n transition: \"opacity .18s ease\",\n background: \"#fff\",\n });\n wrap.appendChild(f);\n wrap.appendChild(loader);\n wrap.appendChild(x);\n bg.appendChild(wrap);\n return { bg, f, loader };\n}\nfunction close() {\n try {\n overlayEl?.remove();\n }\n catch { }\n overlayEl = null;\n pending = null;\n loaderEl = null;\n currentIframeEl = null;\n waitingUiReady = false;\n // ✅ limpiar refs del iframe actual\n currentIframeWin = null;\n currentIframeOrigin = null;\n if (loaderHideTimer)\n window.clearTimeout(loaderHideTimer);\n if (loaderHardTimeout)\n window.clearTimeout(loaderHardTimeout);\n loaderHideTimer = null;\n loaderHardTimeout = null;\n // perf refs\n lastFrameT0 = 0;\n lastFrameUrl = null;\n}\n// ── Quantidia Desktop WebSocket proxy ───────────────────────────────────────\n// The SDK parent page (file:// or localhost) CAN reach local WS servers.\n// The iframe (HTTPS public origin) cannot due to Chrome's Private Network Access.\nlet _qcWs = null;\nlet _qcReqId = 0;\nconst _qcPending = new Map();\nlet _qcIframeSrc = null;\nlet _qcIframeOrigin = null;\nfunction qcConnect() {\n return new Promise((res, rej) => {\n function tryUrl(url, fallback) {\n const ws = new WebSocket(url);\n const t = setTimeout(() => {\n ws.close();\n if (fallback)\n tryUrl(fallback, null);\n else\n rej(new Error(\"Quantidia not available\"));\n }, 3000);\n ws.onopen = () => {\n clearTimeout(t);\n _qcWs = ws;\n ws.onclose = () => { _qcWs = null; };\n ws.onmessage = (ev) => {\n try {\n const msg = JSON.parse(ev.data);\n if (msg.type === \"pairing:challenge\") {\n _qcIframeSrc?.postMessage({ source: \"trusthub\", type: \"QUANTIDIA_PAIRING\", code: msg.code }, _qcIframeOrigin);\n return;\n }\n if (msg.type === \"pairing:approved\") {\n _qcIframeSrc?.postMessage({ source: \"trusthub\", type: \"QUANTIDIA_PAIRING\", code: null }, _qcIframeOrigin);\n return;\n }\n if (msg.type === \"pairing:denied\") {\n _qcPending.forEach(p => p.rej(new Error(msg.error || \"Pairing denied\")));\n _qcPending.clear();\n _qcWs = null;\n ws.close();\n return;\n }\n const p = _qcPending.get(msg.id);\n if (!p)\n return;\n _qcPending.delete(msg.id);\n msg.ok ? p.res(msg.data) : p.rej(new Error(msg.error || \"QC error\"));\n }\n catch { }\n };\n res(ws);\n };\n ws.onerror = () => { clearTimeout(t); };\n }\n tryUrl(\"wss://127.0.0.1:8847\", \"ws://127.0.0.1:8847\");\n });\n}\nasync function qcSend(action, params) {\n if (!_qcWs || _qcWs.readyState !== WebSocket.OPEN)\n _qcWs = await qcConnect();\n const id = `sdk-qc-${++_qcReqId}`;\n return new Promise((res, rej) => {\n _qcPending.set(id, { res, rej });\n _qcWs.send(JSON.stringify({ id, action, ...params }));\n });\n}\nasync function handleQuantidiaRequest(ev) {\n const d = ev.data || {};\n const { reqId, action, params } = d;\n _qcIframeSrc = ev.source;\n _qcIframeOrigin = ev.origin;\n function reply(ok, data, error) {\n ev.source?.postMessage({ source: \"trusthub\", type: \"QUANTIDIA_RESPONSE\", reqId, ok, data, error }, ev.origin);\n }\n try {\n let result;\n if (action === \"isAvailable\") {\n try {\n await qcConnect();\n result = true;\n }\n catch {\n result = false;\n }\n }\n else {\n result = await qcSend(action, params || {});\n }\n reply(true, result);\n }\n catch (e) {\n reply(false, undefined, e?.message || String(e));\n }\n}\n// ── Fortify WebSocket relay ──────────────────────────────────────────────────\nconst _fortifySessions = new Map();\nfunction handleFortifyWsOpen(ev) {\n const d = ev.data || {};\n const sid = d.sessionId;\n const url = d.url || \"wss://127.0.0.1:1337\";\n const src = ev.source;\n const origin = ev.origin;\n function openWs(wsUrl) {\n try {\n const ws = new WebSocket(wsUrl);\n _fortifySessions.set(sid, { ws, src, origin });\n ws.onopen = () => src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_OPENED\", sessionId: sid }, origin);\n ws.onmessage = (mev) => {\n const data = mev.data;\n if (data instanceof ArrayBuffer) {\n src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_MESSAGE\", sessionId: sid, binary: true, data }, origin, [data]);\n }\n else {\n src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_MESSAGE\", sessionId: sid, binary: false, data }, origin);\n }\n };\n ws.onclose = (cev) => {\n _fortifySessions.delete(sid);\n src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_CLOSED\", sessionId: sid, code: cev.code, reason: cev.reason }, origin);\n };\n ws.onerror = () => {\n _fortifySessions.delete(sid);\n if (wsUrl.startsWith(\"wss://\")) {\n openWs(wsUrl.replace(\"wss://\", \"ws://\"));\n }\n else {\n src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_ERROR\", sessionId: sid, error: \"connection failed\" }, origin);\n }\n };\n }\n catch (e) {\n src.postMessage({ source: \"trusthub\", type: \"FORTIFY_WS_ERROR\", sessionId: sid, error: e?.message || \"error\" }, origin);\n }\n }\n openWs(url);\n}\nasync function handleNexuRequest(ev) {\n const d = ev.data || {};\n const kind = d.kind;\n try {\n if (!cfg)\n throw new Error(\"SDK no inicializado\");\n let res = null;\n // 🔹 CASO 1: certificados (compat total)\n if (!kind || kind === \"cert\") {\n if (!cfg.nexuUrl)\n throw new Error(\"Nexu URL no configurada en SDK\");\n res = await fetch(cfg.nexuUrl, { method: \"GET\", mode: \"cors\" });\n }\n // 🔹 CASO 2: firma (nuevo)\n else if (kind === \"sign\") {\n const url = cfg.nexuSignUrl || cfg.nexuUrl;\n if (!url)\n throw new Error(\"Nexu SIGN URL no configurada en SDK\");\n res = await fetch(url, {\n method: \"POST\",\n mode: \"cors\",\n headers: { \"Content-Type\": \"application/json; charset=utf-8\" },\n body: JSON.stringify(d.body || {}),\n });\n }\n if (!res)\n throw new Error(`Nexu kind desconocido: ${kind ?? \"undefined\"}`);\n if (!res.ok)\n throw new Error(`HTTP ${res.status}`);\n const ct = res.headers.get(\"content-type\") || \"\";\n const text = await res.text();\n const data = ct.includes(\"application/json\") && text ? JSON.parse(text) : text;\n ev.source?.postMessage({ source: \"trusthub\", type: \"NEXU_RESPONSE\", kind: kind || \"cert\", data }, ev.origin);\n }\n catch (e) {\n ev.source?.postMessage({ source: \"trusthub\", type: \"NEXU_ERROR\", kind: kind || \"cert\", error: e?.message || String(e) }, ev.origin);\n }\n}\nfunction listen() {\n if (listen._bound)\n return;\n listen._bound = true;\n window.addEventListener(\"message\", (ev) => {\n const d = ev.data || {};\n // ✅ ready ping\n if (d.source === \"trusthub_iframe\" && d.type === \"INIT_REQUEST\") {\n // seguridad mínima: solo el iframe actual y origin esperado\n if (currentIframeWin && ev.source !== currentIframeWin)\n return;\n if (currentIframeOrigin && ev.origin !== currentIframeOrigin)\n return;\n sendInitTo(ev.source, ev.origin);\n return;\n }\n if (d.source === \"trusthub_iframe\" && d.type === \"TOKENS_UPDATED\") {\n if (currentIframeWin && ev.source !== currentIframeWin)\n return;\n if (currentIframeOrigin && ev.origin !== currentIframeOrigin)\n return;\n const t = typeof d?.t === \"string\" ? d.t : undefined;\n const rt = typeof d?.rt === \"string\" ? d.rt : undefined;\n const id = typeof d?.id === \"string\" ? d.id : undefined;\n const un = typeof d?.un === \"string\" ? d.un : undefined;\n storeInitMsg({ t, rt, id, un });\n return;\n }\n // ✅ UI ready (la app dentro del iframe dice \"ya está lista\")\n if (d.source === \"trusthub_iframe\" && d.type === \"UI_READY\") {\n if (currentIframeWin && ev.source !== currentIframeWin)\n return;\n if (currentIframeOrigin && ev.origin !== currentIframeOrigin)\n return;\n waitingUiReady = false;\n revealFrame();\n hideLoader();\n if (lastFrameT0) {\n log(\"UI_READY in\", Math.round(performance.now() - lastFrameT0), \"ms\", \"|\", lastFrameUrl || \"\");\n }\n return;\n }\n // ✅ DOC REQUEST (iframe pide bytes del docId)\n if (d.source === \"trusthub_iframe\" && d.type === \"DOC_REQUEST\") {\n // seguridad mínima: solo el iframe actual y solo el origin esperado\n if (currentIframeWin && ev.source !== currentIframeWin)\n return;\n if (currentIframeOrigin && ev.origin !== currentIframeOrigin)\n return;\n const docId = String(d.docId || \"\");\n const doc = docStore.get(docId);\n if (!doc) {\n ev.source?.postMessage({ source: \"trusthub_sdk\", type: \"DOC_ERROR\", docId, error: \"DOC_NOT_FOUND\" }, ev.origin);\n return;\n }\n // ✅ copiamos para transferir sin vaciar el store\n const copy = new Uint8Array(doc.bytes);\n const buffer = copy.buffer;\n ev.source?.postMessage({ source: \"trusthub_sdk\", type: \"DOC_DATA\", docId, name: doc.name, mime: doc.mime, buffer }, ev.origin, [buffer]);\n return;\n }\n // 1) Mensajes desde el iframe pidiendo token USB vía Nexu\n if (d.source === \"trusthub_iframe\" && d.type === \"NEXU_REQUEST\") {\n handleNexuRequest(ev);\n return;\n }\n // Quantidia Desktop WebSocket proxy\n if (d.source === \"trusthub_iframe\" && d.type === \"QUANTIDIA_REQUEST\") {\n handleQuantidiaRequest(ev);\n return;\n }\n // Fortify WebSocket relay\n if (d.source === \"trusthub_iframe\" && d.type === \"FORTIFY_WS_OPEN\") {\n handleFortifyWsOpen(ev);\n return;\n }\n if (d.source === \"trusthub_iframe\" && d.type === \"FORTIFY_WS_SEND\") {\n const session = _fortifySessions.get(d.sessionId);\n if (session?.ws.readyState === WebSocket.OPEN)\n try {\n session.ws.send(d.data);\n }\n catch { }\n return;\n }\n if (d.source === \"trusthub_iframe\" && d.type === \"FORTIFY_WS_CLOSE\") {\n const session = _fortifySessions.get(d.sessionId);\n if (session)\n try {\n session.ws.close();\n }\n catch { }\n return;\n }\n // ✅ firmados desde iframe → guardar en memoria\n if (d.source === \"trusthub_iframe\" && d.type === \"SIGNED_DOCS\") {\n if (currentIframeWin && ev.source !== currentIframeWin)\n return;\n if (currentIframeOrigin && ev.origin !== currentIframeOrigin)\n return;\n const docs = Array.isArray(d.docs) ? d.docs : [];\n const stored = [];\n for (const it of docs) {\n const ab = it?.buffer instanceof ArrayBuffer ? it.buffer : null;\n if (!ab)\n continue;\n const id = makeSignedId();\n const bytes = new Uint8Array(ab);\n const meta = {\n id,\n name: String(it.name || \"signed.pdf\"),\n mime: String(it.mime || \"application/pdf\"),\n size: bytes.byteLength,\n createdAt: Date.now(),\n sourceDocId: typeof it.sourceDocId === \"string\" ? it.sourceDocId : undefined,\n };\n signedStore.set(id, { ...meta, bytes });\n stored.push(meta);\n }\n // opcional: log\n log(\"SIGNED_DOCS stored:\", stored);\n // opcional: guardarlo en last msg / devolver en resolve\n lastInitMsg = { ...(lastInitMsg || {}), _signed: stored };\n return;\n }\n // 2) Mensajes “clásicos” de la app de firma al SDK\n if (d.source !== \"trusthub\")\n return;\n log(\"message from iframe:\", d);\n if (d.type === \"TRUSTHUB_DONE\") {\n const stored = listSignedDocuments();\n const p = pending; // snapshot\n close(); // esto pone pending = null\n p?.resolve({ status: \"signed\", ...d.data, signed: stored });\n }\n else if (d.type === \"TRUSTHUB_CANCELLED\") {\n const p = pending;\n const reason = d?.data?.reason;\n close();\n p?.reject({ status: reason === \"expired\" ? \"expired\" : \"cancelled\" });\n }\n else if (d.type === \"TRUSTHUB_ERROR\") {\n const p = pending;\n close();\n p?.reject({ status: \"error\", ...d.data });\n }\n });\n window.addEventListener(\"keydown\", (e) => {\n if (e.key === \"Escape\")\n close();\n });\n}\nfunction usbPolicyAllowed() {\n try {\n const allowed = document?.permissionsPolicy?.allowsFeature?.(\"usb\");\n if (typeof allowed === \"boolean\")\n return allowed;\n }\n catch { }\n return true;\n}\nfunction hidPolicyAllowed() {\n try {\n const allowed = document?.permissionsPolicy?.allowsFeature?.(\"hid\");\n if (typeof allowed === \"boolean\")\n return allowed;\n }\n catch { }\n return true;\n}\nfunction isSecure() {\n try {\n return window.isSecureContext === true;\n }\n catch {\n return false;\n }\n}\nfunction buildUrl(baseUrl, path, qs) {\n const url = new URL(baseUrl);\n if (path)\n url.pathname = path;\n url.searchParams.set(\"integration\", \"true\");\n url.searchParams.set(\"sdk\", \"1\");\n Object.entries(qs).forEach(([k, v]) => {\n if (v !== undefined && v !== null && v !== \"\")\n url.searchParams.set(k, String(v));\n });\n return url.toString();\n}\nfunction openFrame({ path, qs, initMsg, }) {\n if (!cfg)\n throw new Error(\"init() primero\");\n clearSignedDocuments();\n function pushTokensToIframe(tokens) {\n if (!currentIframeWin || !currentIframeOrigin)\n return;\n currentIframeWin.postMessage({ source: \"trusthub_sdk\", type: \"TH_AUTH_TOKENS\", tokens }, currentIframeOrigin);\n }\n const view = cfg.view ?? \"full\";\n qs.view = qs.view ?? view;\n const finalInitMsg = { ...(initMsg || {}), view };\n // ✅ guardamos tokens/INIT para reinyectar si el iframe refresca\n storeInitMsg(finalInitMsg);\n const { baseUrl, forceNexu } = cfg;\n // ✅ warmup origin (no bloquea)\n warmupOrigin(baseUrl);\n const { bg, f, loader } = overlayUI();\n loaderEl = loader;\n showLoader();\n overlayEl = bg;\n document.body.appendChild(bg);\n // ✅ guardar referencia al iframe actual (para DOC_REQUEST)\n currentIframeWin = f.contentWindow;\n currentIframeOrigin = new URL(baseUrl).origin;\n const needNexu = !!forceNexu || !usbPolicyAllowed() || !hidPolicyAllowed() || !isSecure();\n if (needNexu)\n qs.forceNexu = \"1\";\n qs.embed = \"1\";\n qs.parent = location.origin;\n let src = buildUrl(baseUrl, path, qs);\n // ✅ token en hash UNA sola vez (si existe)\n if (finalInitMsg?.t) {\n src += `#t=${encodeURIComponent(finalInitMsg.t)}`;\n }\n // ✅ perf marks\n lastFrameT0 = performance.now();\n lastFrameUrl = src;\n // ✅ warm fetch best-effort (no bloquea)\n // (se usa la URL SIN hash para warm, para no mandar token al fetch)\n void warmFetch(src.split(\"#\")[0]);\n currentIframeEl = f;\n // si estamos entrando a la pantalla de firma (docId/docIds o ruta /sign) esperamos UI_READY\n waitingUiReady = false;\n const isSigningRoute = (path || \"\").includes(\"/sign\");\n const hasDocs = !!qs.docId || !!qs.docIds;\n if (isSigningRoute || hasDocs)\n waitingUiReady = true;\n // mientras esperamos, mantenemos iframe invisible + loader arriba\n concealFrame();\n showLoader();\n f.src = src;\n // si el iframe ya existe / se reusa, le avisamos que arranque de nuevo\n // (no rompe el primer load; si todavía no escuchan, no pasa nada)\n try {\n f.contentWindow?.postMessage({\n source: \"trusthub_sdk\",\n type: \"SIGN_START\",\n docId: qs.docId || null,\n docIds: qs.docIds ? String(qs.docIds).split(\",\").filter(Boolean) : null,\n // opcional: reenviar rect para evitar depender del query\n rect: qs.page && qs.x && qs.y ? { page: Number(qs.page), x: Number(qs.x), y: Number(qs.y), w: qs.w ? Number(qs.w) : undefined, h: qs.h ? Number(qs.h) : undefined } : null,\n }, currentIframeOrigin || new URL(baseUrl).origin);\n }\n catch { }\n // cuando el iframe termina de cargar, avisamos START (sirve también para reuso)\n f.addEventListener(\"load\", () => {\n // 🔁 importantísimo: resync de referencias (evita filtro con contentWindow viejo)\n currentIframeWin = f.contentWindow;\n currentIframeOrigin = new URL(baseUrl).origin;\n try {\n f.contentWindow?.postMessage({\n source: \"trusthub_sdk\",\n type: \"SIGN_START\",\n docId: qs.docId || null,\n docIds: qs.docIds ? String(qs.docIds).split(\",\").filter(Boolean) : null,\n rect: qs.page && qs.x && qs.y\n ? {\n page: Number(qs.page),\n x: Number(qs.x),\n y: Number(qs.y),\n w: qs.w ? Number(qs.w) : undefined,\n h: qs.h ? Number(qs.h) : undefined,\n }\n : null,\n }, currentIframeOrigin || new URL(baseUrl).origin);\n }\n catch { }\n }, { once: true });\n // ✅ fallback 2: si por algo nunca llega ready\n loaderHardTimeout = window.setTimeout(() => {\n // fallback: si nunca llegó UI_READY\n revealFrame();\n hideLoader();\n waitingUiReady = false;\n }, 15000);\n // ✅ Mandamos INIT SIEMPRE\n const targetOrigin = new URL(baseUrl).origin;\n // ✅ cada vez que el iframe carga (incluye refresh), re-enviamos INIT hasta ACK\n f.addEventListener(\"load\", () => {\n let acked = false;\n const onAck = (ev) => {\n const d = ev.data || {};\n if (ev.origin !== targetOrigin)\n return;\n if (d?.source === \"trusthub_iframe\" && d?.type === \"INIT_ACK\") {\n acked = true;\n window.removeEventListener(\"message\", onAck);\n }\n };\n window.addEventListener(\"message\", onAck);\n let tries = 0;\n const timer = window.setInterval(() => {\n if (acked || tries > 20) {\n window.clearInterval(timer);\n window.removeEventListener(\"message\", onAck);\n return;\n }\n tries++;\n sendInitTo(f.contentWindow, targetOrigin);\n }, 250);\n });\n}\nasync function postJSON(url, body) {\n log(\"POST\", url, body);\n const headers = new Headers();\n headers.set(\"Content-Type\", \"application/json\");\n // ✅ Trace headers para requests hechas por el SDK (fuera del iframe)\n headers.set(\"tracestate\", TRACE_STATE_FIXED);\n headers.set(\"baggage\", buildBaggage(\"sdk\", operationFromUrl(url)));\n headers.set(\"traceparent\", makeTraceparent());\n const res = await fetch(url, {\n method: \"POST\",\n mode: \"cors\",\n credentials: \"include\",\n headers,\n body: JSON.stringify(body),\n });\n const ct = res.headers.get(\"content-type\") || \"\";\n let json = null;\n try {\n if (ct.includes(\"application/json\"))\n json = await res.clone().json();\n }\n catch { }\n log(\"POST result\", res.status, json || \"(no-json)\");\n if (!res.ok)\n throw new Error(`HTTP ${res.status}`);\n return json || {};\n}\nasync function openSigningWithLogin(params) {\n if (!cfg)\n throw new Error(\"init() primero\");\n const uiLng = \"headersOverride\" in params\n ? pickSupportedLng(params.headersOverride?.acceptLanguage)\n : null;\n const origin = cfg.apiBase || new URL(cfg.baseUrl).origin;\n const loginUrl = `${origin}/api/rest/core/auth/login`;\n const body = {};\n // MODO AVANZADO: viene authLogin completo\n if (\"authLogin\" in params && params.authLogin) {\n body.authLogin = params.authLogin;\n }\n else {\n // MODO SIMPLE: username/password como antes\n const { username, password, environmentId, companyId, agencyId } = params;\n body.username = username;\n body.password = password;\n if (environmentId)\n body.environmentId = environmentId;\n // ✅ nuevo\n if (companyId)\n body.companyId = companyId;\n if (agencyId)\n body.agencyId = agencyId;\n }\n // Headers override\n if (\"headersOverride\" in params && params.headersOverride) {\n body.headersOverride = params.headersOverride;\n }\n const json = await postJSON(loginUrl, body).catch((e) => {\n log(\"login error:\", e);\n return null;\n });\n const ok = json?.ok || json?.success || json?.data?.success || json?.data?.data?.success;\n const access_token = json?.data?.data?.oidc?.access_token ||\n json?.data?.oidc?.access_token ||\n json?.oidc?.access_token ||\n json?.access_token;\n const refresh_token = json?.data?.data?.oidc?.refresh_token ||\n json?.data?.oidc?.refresh_token ||\n json?.oidc?.refresh_token ||\n json?.refresh_token;\n const id_token = json?.data?.data?.oidc?.id_token ||\n json?.data?.oidc?.id_token ||\n json?.oidc?.id_token ||\n json?.id_token;\n const displayName = json?.user?.name || json?.id_tokenDecoded?.name || json?.id_tokenDecoded?.preferred_username || undefined;\n log(\"login ok?\", ok, \"| access_token?\", !!access_token, \"| displayName?\", displayName);\n const qs = { sdk: \"1\", integration: \"true\" };\n if (uiLng)\n qs.lng = uiLng;\n // ✅ nuevo: docs en memoria\n if (\"docId\" in params && params.docId)\n qs.docId = params.docId;\n if (\"docIds\" in params && params.docIds?.length)\n qs.docIds = params.docIds.join(\",\");\n // compat viejo (si querés seguir soportando pdfUrl)\n if (\"pdfUrl\" in params && params.pdfUrl) {\n qs.pdfUrl = params.pdfUrl;\n }\n if (\"signatureRect\" in params && params.signatureRect) {\n Object.assign(qs, params.signatureRect);\n }\n if (displayName)\n qs.un = displayName;\n // ✅ OPT: abrimos directo /integration/dashboard/sign (evita redirects extra)\n const path = ok ? \"/integration/dashboard/sign\" : \"/integration/login\";\n openFrame({\n path,\n qs,\n initMsg: access_token\n ? {\n t: access_token, // access\n rt: refresh_token, // refresh ✅\n id: id_token, // id_token ✅\n un: displayName,\n }\n : undefined,\n });\n const p = new Promise((resolve, reject) => (pending = { resolve, reject }));\n return p;\n}\nfunction openSigning(params) {\n if (!cfg)\n throw new Error(\"init() primero\");\n const qs = {};\n if (params.pdfUrl)\n qs.pdfUrl = params.pdfUrl;\n if (params.signatureRect)\n Object.assign(qs, params.signatureRect);\n const p = new Promise((resolve, reject) => (pending = { resolve, reject }));\n openFrame({ path: null, qs });\n return p;\n}\n\n\n\n//# sourceURL=webpack://Quantidia/./src/ui.ts?\n}");
|
|
20
|
+
|
|
21
|
+
/***/ }),
|
|
22
|
+
|
|
23
|
+
/***/ "./src/umd.ts":
|
|
24
|
+
/*!********************!*\
|
|
25
|
+
!*** ./src/umd.ts ***!
|
|
26
|
+
\********************/
|
|
27
|
+
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
28
|
+
|
|
29
|
+
eval("{__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ addDocuments: () => (/* reexport safe */ _ui__WEBPACK_IMPORTED_MODULE_0__.addDocuments),\n/* harmony export */ close: () => (/* reexport safe */ _ui__WEBPACK_IMPORTED_MODULE_0__.close),\n/* harmony export */ init: () => (/* reexport safe */ _ui__WEBPACK_IMPORTED_MODULE_0__.init),\n/* harmony export */ openSigning: () => (/* reexport safe */ _ui__WEBPACK_IMPORTED_MODULE_0__.openSigning),\n/* harmony export */ openSigningWithLogin: () => (/* reexport safe */ _ui__WEBPACK_IMPORTED_MODULE_0__.openSigningWithLogin)\n/* harmony export */ });\n/* harmony import */ var _ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ui */ \"./src/ui.ts\");\n// sdk/src/umd.ts\n\n\n\n//# sourceURL=webpack://Quantidia/./src/umd.ts?\n}");
|
|
30
|
+
|
|
31
|
+
/***/ })
|
|
32
|
+
|
|
33
|
+
/******/ });
|
|
34
|
+
/************************************************************************/
|
|
35
|
+
/******/ // The module cache
|
|
36
|
+
/******/ var __webpack_module_cache__ = {};
|
|
37
|
+
/******/
|
|
38
|
+
/******/ // The require function
|
|
39
|
+
/******/ function __webpack_require__(moduleId) {
|
|
40
|
+
/******/ // Check if module is in cache
|
|
41
|
+
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
42
|
+
/******/ if (cachedModule !== undefined) {
|
|
43
|
+
/******/ return cachedModule.exports;
|
|
44
|
+
/******/ }
|
|
45
|
+
/******/ // Create a new module (and put it into the cache)
|
|
46
|
+
/******/ var module = __webpack_module_cache__[moduleId] = {
|
|
47
|
+
/******/ // no module.id needed
|
|
48
|
+
/******/ // no module.loaded needed
|
|
49
|
+
/******/ exports: {}
|
|
50
|
+
/******/ };
|
|
51
|
+
/******/
|
|
52
|
+
/******/ // Execute the module function
|
|
53
|
+
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
54
|
+
/******/
|
|
55
|
+
/******/ // Return the exports of the module
|
|
56
|
+
/******/ return module.exports;
|
|
57
|
+
/******/ }
|
|
58
|
+
/******/
|
|
59
|
+
/************************************************************************/
|
|
60
|
+
/******/ /* webpack/runtime/define property getters */
|
|
61
|
+
/******/ (() => {
|
|
62
|
+
/******/ // define getter functions for harmony exports
|
|
63
|
+
/******/ __webpack_require__.d = (exports, definition) => {
|
|
64
|
+
/******/ for(var key in definition) {
|
|
65
|
+
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
|
|
66
|
+
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
|
|
67
|
+
/******/ }
|
|
68
|
+
/******/ }
|
|
69
|
+
/******/ };
|
|
70
|
+
/******/ })();
|
|
71
|
+
/******/
|
|
72
|
+
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
|
73
|
+
/******/ (() => {
|
|
74
|
+
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
|
|
75
|
+
/******/ })();
|
|
76
|
+
/******/
|
|
77
|
+
/******/ /* webpack/runtime/make namespace object */
|
|
78
|
+
/******/ (() => {
|
|
79
|
+
/******/ // define __esModule on exports
|
|
80
|
+
/******/ __webpack_require__.r = (exports) => {
|
|
81
|
+
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
|
|
82
|
+
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
83
|
+
/******/ }
|
|
84
|
+
/******/ Object.defineProperty(exports, '__esModule', { value: true });
|
|
85
|
+
/******/ };
|
|
86
|
+
/******/ })();
|
|
87
|
+
/******/
|
|
88
|
+
/************************************************************************/
|
|
89
|
+
/******/
|
|
90
|
+
/******/ // startup
|
|
91
|
+
/******/ // Load entry module and return exports
|
|
92
|
+
/******/ // This entry module can't be inlined because the eval devtool is used.
|
|
93
|
+
/******/ var __webpack_exports__ = __webpack_require__("./src/umd.ts");
|
|
94
|
+
/******/ window.Quantidia = __webpack_exports__;
|
|
95
|
+
/******/
|
|
96
|
+
/******/ })()
|
|
97
|
+
;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{addDocuments:()=>_,close:()=>D,init:()=>N,openSigning:()=>H,openSigningWithLogin:()=>G});let n=null,r=null,o=null;function s(){n&&(n.style.display="flex")}function i(){n&&(n.style.display="none",r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null)}let a=null,c=null,d=null,u=null;function l(e){e&&(u={...u||{},...e||{}})}function p(e,t){if(!e||!t)return;const n={...u||{},view:a?.view??"full"};e.postMessage({source:"trusthub_sdk",type:"INIT",...n},t)}const f=new Map;function g(){return crypto.randomUUID()}const h=new Map;let y=null,m=null,w=null,b=!1;function I(){try{w&&(w.style.opacity="1")}catch{}}async function S(e){if(!e)throw new Error("file requerido");const t=crypto.randomUUID(),n=await async function(e){const t=await e.arrayBuffer();return new Uint8Array(t)}(e);return h.set(t,{id:t,name:e.name||"document.pdf",mime:e.type||"application/pdf",bytes:n,size:n.byteLength,createdAt:Date.now()}),t}async function _(e){const t=Array.from((FileList,e)),n=[];for(const e of t)n.push(await S(e));return n}const E=(...e)=>console.log("[TrustHub SDK]",...e);let v=0,k=null;function R(e,t){try{const n=`th-sdk-${e}-${t}`;if(document.getElementById(n))return;const r=document.createElement("link");r.id=n,r.rel=e,r.href=t,"preconnect"===e&&(r.crossOrigin="anonymous"),document.head.appendChild(r)}catch{}}function T(e){const t=function(e){try{return new URL(e,window.location.origin).origin}catch{return""}}(e);t&&(R("dns-prefetch",t),R("preconnect",t))}const O="es=s:1";function U(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function N(e){a={...e},B(),T(e.baseUrl),E("init",e)}function x(e,t){Object.assign(e.style,t)}function A(){!function(){if(document.getElementById("th-sdk-loader-style"))return;const e=document.createElement("style");e.id="th-sdk-loader-style",e.textContent="\n .th-sdk-loader {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n background: rgba(255,255,255,.92);\n z-index: 1; /* debajo del botón close (zIndex 2) */\n pointer-events: auto;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;\n }\n .th-sdk-spinner {\n width: 28px;\n height: 28px;\n border-radius: 999px;\n border: 3px solid rgba(0,0,0,.15);\n border-top-color: rgba(0,0,0,.75);\n animation: thsdkspin .9s linear infinite;\n }\n @keyframes thsdkspin { to { transform: rotate(360deg); } }\n .th-sdk-loader-text {\n font-size: 14px;\n color: rgba(0,0,0,.75);\n font-weight: 600;\n }\n ",document.head.appendChild(e)}();const e=document.createElement("div");x(e,{position:"fixed",inset:"0",background:"rgba(0,0,0,.45)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"2147483646"});const t=document.createElement("div");x(t,{position:"relative",width:"90%",height:"80%",maxWidth:"1000px",borderRadius:"12px",overflow:"hidden",background:"#fff",boxShadow:"0 10px 30px rgba(0,0,0,.3)"});const n=document.createElement("div");n.className="th-sdk-loader",n.innerHTML='<div class="th-sdk-spinner"></div><div class="th-sdk-loader-text">Loading Quantidia SDK…</div>';const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),x(r,{position:"absolute",top:"20px",right:"18px",margin:"0",border:"0",cursor:"pointer",zIndex:"2",backgroundColor:"transparent",backgroundImage:"url('https://dev.trusthub.cloud/images/icons/Close.svg')",backgroundRepeat:"no-repeat",backgroundPosition:"center",width:"22px",height:"22px"}),r.innerHTML="",r.onclick=D;const o=document.createElement("iframe");return o.allow="hid; usb; serial; clipboard-read; clipboard-write; fullscreen",o.allowFullscreen=!0,o.referrerPolicy="strict-origin-when-cross-origin",x(o,{width:"100%",height:"100%",border:"0",opacity:"0",transition:"opacity .18s ease",background:"#fff"}),t.appendChild(o),t.appendChild(n),t.appendChild(r),e.appendChild(t),{bg:e,f:o,loader:n}}function D(){try{c?.remove()}catch{}c=null,d=null,n=null,w=null,b=!1,y=null,m=null,r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null,v=0,k=null}let L=null,P=0;const C=new Map;let M=null,j=null;function W(){return new Promise((e,t)=>{!function n(r,o){const s=new WebSocket(r),i=setTimeout(()=>{s.close(),o?n(o,null):t(new Error("Quantidia not available"))},3e3);s.onopen=()=>{clearTimeout(i),L=s,s.onclose=()=>{L=null},s.onmessage=e=>{try{const t=JSON.parse(e.data);if("pairing:challenge"===t.type)return void M?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:t.code},j);if("pairing:approved"===t.type)return void M?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:null},j);if("pairing:denied"===t.type)return C.forEach(e=>e.rej(new Error(t.error||"Pairing denied"))),C.clear(),L=null,void s.close();const n=C.get(t.id);if(!n)return;C.delete(t.id),t.ok?n.res(t.data):n.rej(new Error(t.error||"QC error"))}catch{}},e(s)},s.onerror=()=>{clearTimeout(i)}}("wss://127.0.0.1:8847","ws://127.0.0.1:8847")})}async function F(e){const t=e.data||{},{reqId:n,action:r,params:o}=t;function s(t,r,o){e.source?.postMessage({source:"trusthub",type:"QUANTIDIA_RESPONSE",reqId:n,ok:t,data:r,error:o},e.origin)}M=e.source,j=e.origin;try{let e;if("isAvailable"===r)try{await W(),e=!0}catch{e=!1}else e=await async function(e,t){L&&L.readyState===WebSocket.OPEN||(L=await W());const n="sdk-qc-"+ ++P;return new Promise((r,o)=>{C.set(n,{res:r,rej:o}),L.send(JSON.stringify({id:n,action:e,...t}))})}(r,o||{});s(!0,e)}catch(e){s(!1,void 0,e?.message||String(e))}}const Q=new Map;function B(){B._bound||(B._bound=!0,window.addEventListener("message",e=>{const t=e.data||{};if("trusthub_iframe"!==t.source||"INIT_REQUEST"!==t.type){if("trusthub_iframe"===t.source&&"TOKENS_UPDATED"===t.type){if(y&&e.source!==y)return;if(m&&e.origin!==m)return;return void l({t:"string"==typeof t?.t?t.t:void 0,rt:"string"==typeof t?.rt?t.rt:void 0,id:"string"==typeof t?.id?t.id:void 0,un:"string"==typeof t?.un?t.un:void 0})}if("trusthub_iframe"===t.source&&"UI_READY"===t.type){if(y&&e.source!==y)return;if(m&&e.origin!==m)return;return b=!1,I(),i(),void(v&&E("UI_READY in",Math.round(performance.now()-v),"ms","|",k||""))}if("trusthub_iframe"===t.source&&"DOC_REQUEST"===t.type){if(y&&e.source!==y)return;if(m&&e.origin!==m)return;const n=String(t.docId||""),r=h.get(n);if(!r)return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_ERROR",docId:n,error:"DOC_NOT_FOUND"},e.origin);const o=new Uint8Array(r.bytes).buffer;return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_DATA",docId:n,name:r.name,mime:r.mime,buffer:o},e.origin,[o])}if("trusthub_iframe"!==t.source||"NEXU_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"QUANTIDIA_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"FORTIFY_WS_OPEN"!==t.type){if("trusthub_iframe"===t.source&&"FORTIFY_WS_SEND"===t.type){const e=Q.get(t.sessionId);if(e?.ws.readyState===WebSocket.OPEN)try{e.ws.send(t.data)}catch{}return}if("trusthub_iframe"===t.source&&"FORTIFY_WS_CLOSE"===t.type){const e=Q.get(t.sessionId);if(e)try{e.ws.close()}catch{}return}if("trusthub_iframe"===t.source&&"SIGNED_DOCS"===t.type){if(y&&e.source!==y)return;if(m&&e.origin!==m)return;const n=Array.isArray(t.docs)?t.docs:[],r=[];for(const e of n){const t=e?.buffer instanceof ArrayBuffer?e.buffer:null;if(!t)continue;const n=g(),o=new Uint8Array(t),s={id:n,name:String(e.name||"signed.pdf"),mime:String(e.mime||"application/pdf"),size:o.byteLength,createdAt:Date.now(),sourceDocId:"string"==typeof e.sourceDocId?e.sourceDocId:void 0};f.set(n,{...s,bytes:o}),r.push(s)}return E("SIGNED_DOCS stored:",r),void(u={...u||{},_signed:r})}if("trusthub"===t.source)if(E("message from iframe:",t),"TRUSTHUB_DONE"===t.type){const e=Array.from(f.values()).map(({bytes:e,...t})=>t),n=d;D(),n?.resolve({status:"signed",...t.data,signed:e})}else if("TRUSTHUB_CANCELLED"===t.type){const e=d,n=t?.data?.reason;D(),e?.reject({status:"expired"===n?"expired":"cancelled"})}else if("TRUSTHUB_ERROR"===t.type){const e=d;D(),e?.reject({status:"error",...t.data})}}else!function(e){const t=e.data||{},n=t.sessionId,r=t.url||"wss://127.0.0.1:1337",o=e.source,s=e.origin;!function e(t){try{const r=new WebSocket(t);Q.set(n,{ws:r,src:o,origin:s}),r.onopen=()=>o.postMessage({source:"trusthub",type:"FORTIFY_WS_OPENED",sessionId:n},s),r.onmessage=e=>{const t=e.data;t instanceof ArrayBuffer?o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!0,data:t},s,[t]):o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!1,data:t},s)},r.onclose=e=>{Q.delete(n),o.postMessage({source:"trusthub",type:"FORTIFY_WS_CLOSED",sessionId:n,code:e.code,reason:e.reason},s)},r.onerror=()=>{Q.delete(n),t.startsWith("wss://")?e(t.replace("wss://","ws://")):o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:"connection failed"},s)}}catch(e){o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:e?.message||"error"},s)}}(r)}(e);else F(e);else!async function(e){const t=e.data||{},n=t.kind;try{if(!a)throw new Error("SDK no inicializado");let r=null;if(n&&"cert"!==n){if("sign"===n){const e=a.nexuSignUrl||a.nexuUrl;if(!e)throw new Error("Nexu SIGN URL no configurada en SDK");r=await fetch(e,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t.body||{})})}}else{if(!a.nexuUrl)throw new Error("Nexu URL no configurada en SDK");r=await fetch(a.nexuUrl,{method:"GET",mode:"cors"})}if(!r)throw new Error(`Nexu kind desconocido: ${n??"undefined"}`);if(!r.ok)throw new Error(`HTTP ${r.status}`);const o=r.headers.get("content-type")||"",s=await r.text(),i=o.includes("application/json")&&s?JSON.parse(s):s;e.source?.postMessage({source:"trusthub",type:"NEXU_RESPONSE",kind:n||"cert",data:i},e.origin)}catch(t){e.source?.postMessage({source:"trusthub",type:"NEXU_ERROR",kind:n||"cert",error:t?.message||String(t)},e.origin)}}(e)}else{if(y&&e.source!==y)return;if(m&&e.origin!==m)return;p(e.source,e.origin)}}),window.addEventListener("keydown",e=>{"Escape"===e.key&&D()}))}function Y({path:e,qs:t,initMsg:r}){if(!a)throw new Error("init() primero");f.clear();const d=a.view??"full";t.view=t.view??d;const u={...r||{},view:d};l(u);const{baseUrl:g,forceNexu:h}=a;T(g);const{bg:S,f:_,loader:E}=A();n=E,s(),c=S,document.body.appendChild(S),y=_.contentWindow,m=new URL(g).origin;!(!h&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("usb");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("hid");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{return!0===window.isSecureContext}catch{return!1}}())&&(t.forceNexu="1"),t.embed="1",t.parent=location.origin;let R=function(e,t,n){const r=new URL(e);return t&&(r.pathname=t),r.searchParams.set("integration","true"),r.searchParams.set("sdk","1"),Object.entries(n).forEach(([e,t])=>{null!=t&&""!==t&&r.searchParams.set(e,String(t))}),r.toString()}(g,e,t);u?.t&&(R+=`#t=${encodeURIComponent(u.t)}`),v=performance.now(),k=R,async function(e){try{await fetch(e,{mode:"no-cors",cache:"force-cache"})}catch{}}(R.split("#")[0]),w=_,b=!1;const O=(e||"").includes("/sign"),U=!!t.docId||!!t.docIds;(O||U)&&(b=!0),function(){try{w&&(w.style.opacity="0")}catch{}}(),s(),_.src=R;try{_.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},m||new URL(g).origin)}catch{}_.addEventListener("load",()=>{y=_.contentWindow,m=new URL(g).origin;try{_.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},m||new URL(g).origin)}catch{}},{once:!0}),o=window.setTimeout(()=>{I(),i(),b=!1},15e3);const N=new URL(g).origin;_.addEventListener("load",()=>{let e=!1;const t=n=>{const r=n.data||{};n.origin===N&&"trusthub_iframe"===r?.source&&"INIT_ACK"===r?.type&&(e=!0,window.removeEventListener("message",t))};window.addEventListener("message",t);let n=0;const r=window.setInterval(()=>{if(e||n>20)return window.clearInterval(r),void window.removeEventListener("message",t);n++,p(_.contentWindow,N)},250)})}async function $(e,t){E("POST",e,t);const n=new Headers;var r,o;n.set("Content-Type","application/json"),n.set("tracestate",O),n.set("baggage",(r="sdk",o=function(e){try{const t=new URL(e,window.location.origin).pathname;return t.includes("/auth/")?"auth":t.includes("/sign/")?"sign":t.includes("/verify/")?"verify":t.includes("/timestamp/")?"timestamp":"sdk"}catch{return"sdk"}}(e),`tenant=trusthub,channel=${r},operation=${o}`)),n.set("traceparent",`00-${U(16)}-${U(8)}-01`);const s=await fetch(e,{method:"POST",mode:"cors",credentials:"include",headers:n,body:JSON.stringify(t)}),i=s.headers.get("content-type")||"";let a=null;try{i.includes("application/json")&&(a=await s.clone().json())}catch{}if(E("POST result",s.status,a||"(no-json)"),!s.ok)throw new Error(`HTTP ${s.status}`);return a||{}}async function G(e){if(!a)throw new Error("init() primero");const t="headersOverride"in e?function(e){if(!e)return null;const t=String(e).split(",")[0]?.trim();if(!t)return null;const n=t.replace(/_/g,"-").toLowerCase();return n.startsWith("es")?"es-AR":n.startsWith("it")?"it-IT":n.startsWith("en")?"en-US":null}(e.headersOverride?.acceptLanguage):null,n=`${a.apiBase||new URL(a.baseUrl).origin}/api/rest/core/auth/login`,r={};if("authLogin"in e&&e.authLogin)r.authLogin=e.authLogin;else{const{username:t,password:n,environmentId:o,companyId:s,agencyId:i}=e;r.username=t,r.password=n,o&&(r.environmentId=o),s&&(r.companyId=s),i&&(r.agencyId=i)}"headersOverride"in e&&e.headersOverride&&(r.headersOverride=e.headersOverride);const o=await $(n,r).catch(e=>(E("login error:",e),null)),s=o?.ok||o?.success||o?.data?.success||o?.data?.data?.success,i=o?.data?.data?.oidc?.access_token||o?.data?.oidc?.access_token||o?.oidc?.access_token||o?.access_token,c=o?.data?.data?.oidc?.refresh_token||o?.data?.oidc?.refresh_token||o?.oidc?.refresh_token||o?.refresh_token,u=o?.data?.data?.oidc?.id_token||o?.data?.oidc?.id_token||o?.oidc?.id_token||o?.id_token,l=o?.user?.name||o?.id_tokenDecoded?.name||o?.id_tokenDecoded?.preferred_username||void 0;E("login ok?",s,"| access_token?",!!i,"| displayName?",l);const p={sdk:"1",integration:"true"};t&&(p.lng=t),"docId"in e&&e.docId&&(p.docId=e.docId),"docIds"in e&&e.docIds?.length&&(p.docIds=e.docIds.join(",")),"pdfUrl"in e&&e.pdfUrl&&(p.pdfUrl=e.pdfUrl),"signatureRect"in e&&e.signatureRect&&Object.assign(p,e.signatureRect),l&&(p.un=l);Y({path:s?"/integration/dashboard/sign":"/integration/login",qs:p,initMsg:i?{t:i,rt:c,id:u,un:l}:void 0});return new Promise((e,t)=>d={resolve:e,reject:t})}function H(e){if(!a)throw new Error("init() primero");const t={};e.pdfUrl&&(t.pdfUrl=e.pdfUrl),e.signatureRect&&Object.assign(t,e.signatureRect);const n=new Promise((e,t)=>d={resolve:e,reject:t});return Y({path:null,qs:t}),n}window.Quantidia=t})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "../client";
|
package/dist/src/ui.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
export type SignatureRect = {
|
|
2
|
+
x: number;
|
|
3
|
+
y: number;
|
|
4
|
+
w: number;
|
|
5
|
+
h: number;
|
|
6
|
+
page: number;
|
|
7
|
+
};
|
|
8
|
+
type OpenSigningWithLoginParams = {
|
|
9
|
+
username: string;
|
|
10
|
+
password: string;
|
|
11
|
+
environmentId?: string;
|
|
12
|
+
companyId?: string;
|
|
13
|
+
agencyId?: string;
|
|
14
|
+
pdfUrl?: string;
|
|
15
|
+
signatureRect?: SignatureRect;
|
|
16
|
+
authLogin?: never;
|
|
17
|
+
headersOverride?: HeadersOverride;
|
|
18
|
+
docId?: string;
|
|
19
|
+
docIds?: string[];
|
|
20
|
+
} | {
|
|
21
|
+
authLogin: AuthLoginPayload;
|
|
22
|
+
pdfUrl?: string;
|
|
23
|
+
signatureRect?: SignatureRect;
|
|
24
|
+
headersOverride?: HeadersOverride;
|
|
25
|
+
username?: never;
|
|
26
|
+
password?: never;
|
|
27
|
+
environmentId?: never;
|
|
28
|
+
docId?: string;
|
|
29
|
+
docIds?: string[];
|
|
30
|
+
};
|
|
31
|
+
export type InitOptions = {
|
|
32
|
+
baseUrl: string;
|
|
33
|
+
apiBase?: string;
|
|
34
|
+
forceNexu?: boolean;
|
|
35
|
+
nexuUrl?: string;
|
|
36
|
+
nexuSignUrl?: string;
|
|
37
|
+
view?: "full" | "restricted" | "gateway";
|
|
38
|
+
};
|
|
39
|
+
type CredentialItem = {
|
|
40
|
+
field: string;
|
|
41
|
+
type?: string;
|
|
42
|
+
format?: string;
|
|
43
|
+
value: string;
|
|
44
|
+
};
|
|
45
|
+
type AuthLoginDetail = {
|
|
46
|
+
username: string;
|
|
47
|
+
password: string;
|
|
48
|
+
access_token?: never;
|
|
49
|
+
} | {
|
|
50
|
+
access_token: string;
|
|
51
|
+
username?: never;
|
|
52
|
+
password?: never;
|
|
53
|
+
} | {
|
|
54
|
+
method?: string;
|
|
55
|
+
credentials?: CredentialItem[];
|
|
56
|
+
context?: any;
|
|
57
|
+
options?: any;
|
|
58
|
+
username?: string;
|
|
59
|
+
password?: string;
|
|
60
|
+
access_token?: string;
|
|
61
|
+
};
|
|
62
|
+
type AuthLoginPayload = {
|
|
63
|
+
authReference: {
|
|
64
|
+
environmentId: string;
|
|
65
|
+
userId?: string;
|
|
66
|
+
subscriptionId?: string;
|
|
67
|
+
companyId?: string;
|
|
68
|
+
agencyId?: string;
|
|
69
|
+
};
|
|
70
|
+
authModal?: {
|
|
71
|
+
type?: string;
|
|
72
|
+
mode?: string;
|
|
73
|
+
};
|
|
74
|
+
authLogin: AuthLoginDetail;
|
|
75
|
+
authCallback?: {
|
|
76
|
+
url?: string;
|
|
77
|
+
userId?: string;
|
|
78
|
+
password?: string;
|
|
79
|
+
auth?: string;
|
|
80
|
+
retries?: string;
|
|
81
|
+
};
|
|
82
|
+
authNotify?: {
|
|
83
|
+
email?: string;
|
|
84
|
+
sms?: string;
|
|
85
|
+
push?: string;
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
type HeadersOverride = {
|
|
89
|
+
apiKey?: string;
|
|
90
|
+
acceptLanguage?: string;
|
|
91
|
+
};
|
|
92
|
+
export type SignedDocMeta = {
|
|
93
|
+
id: string;
|
|
94
|
+
name: string;
|
|
95
|
+
mime: string;
|
|
96
|
+
size: number;
|
|
97
|
+
createdAt: number;
|
|
98
|
+
sourceDocId?: string;
|
|
99
|
+
};
|
|
100
|
+
export declare function listSignedDocuments(): SignedDocMeta[];
|
|
101
|
+
export declare function getSignedDocumentBytes(id: string): Uint8Array | null;
|
|
102
|
+
export declare function removeSignedDocument(id: string): void;
|
|
103
|
+
export declare function clearSignedDocuments(): void;
|
|
104
|
+
export declare function addDocument(file: File): Promise<`${string}-${string}-${string}-${string}-${string}`>;
|
|
105
|
+
export declare function addDocuments(files: FileList | File[]): Promise<string[]>;
|
|
106
|
+
export declare function removeDocument(docId: string): void;
|
|
107
|
+
export declare function clearDocuments(): void;
|
|
108
|
+
export declare function init(opts: InitOptions): void;
|
|
109
|
+
declare function close(): void;
|
|
110
|
+
export declare function openSigningWithLogin(params: OpenSigningWithLoginParams): Promise<unknown>;
|
|
111
|
+
export declare function openSigning(params: {
|
|
112
|
+
pdfUrl?: string;
|
|
113
|
+
signatureRect?: SignatureRect;
|
|
114
|
+
}): Promise<unknown>;
|
|
115
|
+
export { close };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { init, openSigningWithLogin, openSigning, addDocuments, close } from "./ui";
|
package/dist/ui.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{addDocument:()=>k,addDocuments:()=>R,clearDocuments:()=>U,clearSignedDocuments:()=>w,close:()=>W,getSignedDocumentBytes:()=>m,init:()=>C,listSignedDocuments:()=>h,openSigning:()=>V,openSigningWithLogin:()=>X,removeDocument:()=>T,removeSignedDocument:()=>y});let n=null,r=null,o=null;function s(){n&&(n.style.display="flex")}function i(){n&&(n.style.display="none",r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null)}let a=null,c=null,d=null,u=null;function l(e){e&&(u={...u||{},...e||{}})}function f(e,t){if(!e||!t)return;const n={...u||{},view:a?.view??"full"};e.postMessage({source:"trusthub_sdk",type:"INIT",...n},t)}const p=new Map;function g(){return crypto.randomUUID()}function h(){return Array.from(p.values()).map(({bytes:e,...t})=>t)}function m(e){const t=p.get(e);return t?new Uint8Array(t.bytes):null}function y(e){p.delete(e)}function w(){p.clear()}const b=new Map;let I=null,S=null,_=null,v=!1;function E(){try{_&&(_.style.opacity="1")}catch{}}async function k(e){if(!e)throw new Error("file requerido");const t=crypto.randomUUID(),n=await async function(e){const t=await e.arrayBuffer();return new Uint8Array(t)}(e);return b.set(t,{id:t,name:e.name||"document.pdf",mime:e.type||"application/pdf",bytes:n,size:n.byteLength,createdAt:Date.now()}),t}async function R(e){const t=Array.from((FileList,e)),n=[];for(const e of t)n.push(await k(e));return n}function T(e){b.delete(e)}function U(){b.clear()}const O=(...e)=>console.log("[TrustHub SDK]",...e);let N=0,x=null;function D(e,t){try{const n=`th-sdk-${e}-${t}`;if(document.getElementById(n))return;const r=document.createElement("link");r.id=n,r.rel=e,r.href=t,"preconnect"===e&&(r.crossOrigin="anonymous"),document.head.appendChild(r)}catch{}}function A(e){const t=function(e){try{return new URL(e,window.location.origin).origin}catch{return""}}(e);t&&(D("dns-prefetch",t),D("preconnect",t))}const L="es=s:1";function P(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function C(e){a={...e},q(),A(e.baseUrl),O("init",e)}function M(e,t){Object.assign(e.style,t)}function j(){!function(){if(document.getElementById("th-sdk-loader-style"))return;const e=document.createElement("style");e.id="th-sdk-loader-style",e.textContent="\n .th-sdk-loader {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n background: rgba(255,255,255,.92);\n z-index: 1; /* debajo del botón close (zIndex 2) */\n pointer-events: auto;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;\n }\n .th-sdk-spinner {\n width: 28px;\n height: 28px;\n border-radius: 999px;\n border: 3px solid rgba(0,0,0,.15);\n border-top-color: rgba(0,0,0,.75);\n animation: thsdkspin .9s linear infinite;\n }\n @keyframes thsdkspin { to { transform: rotate(360deg); } }\n .th-sdk-loader-text {\n font-size: 14px;\n color: rgba(0,0,0,.75);\n font-weight: 600;\n }\n ",document.head.appendChild(e)}();const e=document.createElement("div");M(e,{position:"fixed",inset:"0",background:"rgba(0,0,0,.45)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"2147483646"});const t=document.createElement("div");M(t,{position:"relative",width:"90%",height:"80%",maxWidth:"1000px",borderRadius:"12px",overflow:"hidden",background:"#fff",boxShadow:"0 10px 30px rgba(0,0,0,.3)"});const n=document.createElement("div");n.className="th-sdk-loader",n.innerHTML='<div class="th-sdk-spinner"></div><div class="th-sdk-loader-text">Loading Quantidia SDK…</div>';const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),M(r,{position:"absolute",top:"20px",right:"18px",margin:"0",border:"0",cursor:"pointer",zIndex:"2",backgroundColor:"transparent",backgroundImage:"url('https://dev.trusthub.cloud/images/icons/Close.svg')",backgroundRepeat:"no-repeat",backgroundPosition:"center",width:"22px",height:"22px"}),r.innerHTML="",r.onclick=W;const o=document.createElement("iframe");return o.allow="hid; usb; serial; clipboard-read; clipboard-write; fullscreen",o.allowFullscreen=!0,o.referrerPolicy="strict-origin-when-cross-origin",M(o,{width:"100%",height:"100%",border:"0",opacity:"0",transition:"opacity .18s ease",background:"#fff"}),t.appendChild(o),t.appendChild(n),t.appendChild(r),e.appendChild(t),{bg:e,f:o,loader:n}}function W(){try{c?.remove()}catch{}c=null,d=null,n=null,_=null,v=!1,I=null,S=null,r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null,N=0,x=null}let F=null,B=0;const Q=new Map;let Y=null,$=null;function G(){return new Promise((e,t)=>{!function n(r,o){const s=new WebSocket(r),i=setTimeout(()=>{s.close(),o?n(o,null):t(new Error("Quantidia not available"))},3e3);s.onopen=()=>{clearTimeout(i),F=s,s.onclose=()=>{F=null},s.onmessage=e=>{try{const t=JSON.parse(e.data);if("pairing:challenge"===t.type)return void Y?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:t.code},$);if("pairing:approved"===t.type)return void Y?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:null},$);if("pairing:denied"===t.type)return Q.forEach(e=>e.rej(new Error(t.error||"Pairing denied"))),Q.clear(),F=null,void s.close();const n=Q.get(t.id);if(!n)return;Q.delete(t.id),t.ok?n.res(t.data):n.rej(new Error(t.error||"QC error"))}catch{}},e(s)},s.onerror=()=>{clearTimeout(i)}}("wss://127.0.0.1:8847","ws://127.0.0.1:8847")})}async function H(e){const t=e.data||{},{reqId:n,action:r,params:o}=t;function s(t,r,o){e.source?.postMessage({source:"trusthub",type:"QUANTIDIA_RESPONSE",reqId:n,ok:t,data:r,error:o},e.origin)}Y=e.source,$=e.origin;try{let e;if("isAvailable"===r)try{await G(),e=!0}catch{e=!1}else e=await async function(e,t){F&&F.readyState===WebSocket.OPEN||(F=await G());const n="sdk-qc-"+ ++B;return new Promise((r,o)=>{Q.set(n,{res:r,rej:o}),F.send(JSON.stringify({id:n,action:e,...t}))})}(r,o||{});s(!0,e)}catch(e){s(!1,void 0,e?.message||String(e))}}const z=new Map;function q(){q._bound||(q._bound=!0,window.addEventListener("message",e=>{const t=e.data||{};if("trusthub_iframe"!==t.source||"INIT_REQUEST"!==t.type){if("trusthub_iframe"===t.source&&"TOKENS_UPDATED"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;return void l({t:"string"==typeof t?.t?t.t:void 0,rt:"string"==typeof t?.rt?t.rt:void 0,id:"string"==typeof t?.id?t.id:void 0,un:"string"==typeof t?.un?t.un:void 0})}if("trusthub_iframe"===t.source&&"UI_READY"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;return v=!1,E(),i(),void(N&&O("UI_READY in",Math.round(performance.now()-N),"ms","|",x||""))}if("trusthub_iframe"===t.source&&"DOC_REQUEST"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;const n=String(t.docId||""),r=b.get(n);if(!r)return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_ERROR",docId:n,error:"DOC_NOT_FOUND"},e.origin);const o=new Uint8Array(r.bytes).buffer;return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_DATA",docId:n,name:r.name,mime:r.mime,buffer:o},e.origin,[o])}if("trusthub_iframe"!==t.source||"NEXU_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"QUANTIDIA_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"FORTIFY_WS_OPEN"!==t.type){if("trusthub_iframe"===t.source&&"FORTIFY_WS_SEND"===t.type){const e=z.get(t.sessionId);if(e?.ws.readyState===WebSocket.OPEN)try{e.ws.send(t.data)}catch{}return}if("trusthub_iframe"===t.source&&"FORTIFY_WS_CLOSE"===t.type){const e=z.get(t.sessionId);if(e)try{e.ws.close()}catch{}return}if("trusthub_iframe"===t.source&&"SIGNED_DOCS"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;const n=Array.isArray(t.docs)?t.docs:[],r=[];for(const e of n){const t=e?.buffer instanceof ArrayBuffer?e.buffer:null;if(!t)continue;const n=g(),o=new Uint8Array(t),s={id:n,name:String(e.name||"signed.pdf"),mime:String(e.mime||"application/pdf"),size:o.byteLength,createdAt:Date.now(),sourceDocId:"string"==typeof e.sourceDocId?e.sourceDocId:void 0};p.set(n,{...s,bytes:o}),r.push(s)}return O("SIGNED_DOCS stored:",r),void(u={...u||{},_signed:r})}if("trusthub"===t.source)if(O("message from iframe:",t),"TRUSTHUB_DONE"===t.type){const e=h(),n=d;W(),n?.resolve({status:"signed",...t.data,signed:e})}else if("TRUSTHUB_CANCELLED"===t.type){const e=d,n=t?.data?.reason;W(),e?.reject({status:"expired"===n?"expired":"cancelled"})}else if("TRUSTHUB_ERROR"===t.type){const e=d;W(),e?.reject({status:"error",...t.data})}}else!function(e){const t=e.data||{},n=t.sessionId,r=t.url||"wss://127.0.0.1:1337",o=e.source,s=e.origin;!function e(t){try{const r=new WebSocket(t);z.set(n,{ws:r,src:o,origin:s}),r.onopen=()=>o.postMessage({source:"trusthub",type:"FORTIFY_WS_OPENED",sessionId:n},s),r.onmessage=e=>{const t=e.data;t instanceof ArrayBuffer?o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!0,data:t},s,[t]):o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!1,data:t},s)},r.onclose=e=>{z.delete(n),o.postMessage({source:"trusthub",type:"FORTIFY_WS_CLOSED",sessionId:n,code:e.code,reason:e.reason},s)},r.onerror=()=>{z.delete(n),t.startsWith("wss://")?e(t.replace("wss://","ws://")):o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:"connection failed"},s)}}catch(e){o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:e?.message||"error"},s)}}(r)}(e);else H(e);else!async function(e){const t=e.data||{},n=t.kind;try{if(!a)throw new Error("SDK no inicializado");let r=null;if(n&&"cert"!==n){if("sign"===n){const e=a.nexuSignUrl||a.nexuUrl;if(!e)throw new Error("Nexu SIGN URL no configurada en SDK");r=await fetch(e,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t.body||{})})}}else{if(!a.nexuUrl)throw new Error("Nexu URL no configurada en SDK");r=await fetch(a.nexuUrl,{method:"GET",mode:"cors"})}if(!r)throw new Error(`Nexu kind desconocido: ${n??"undefined"}`);if(!r.ok)throw new Error(`HTTP ${r.status}`);const o=r.headers.get("content-type")||"",s=await r.text(),i=o.includes("application/json")&&s?JSON.parse(s):s;e.source?.postMessage({source:"trusthub",type:"NEXU_RESPONSE",kind:n||"cert",data:i},e.origin)}catch(t){e.source?.postMessage({source:"trusthub",type:"NEXU_ERROR",kind:n||"cert",error:t?.message||String(t)},e.origin)}}(e)}else{if(I&&e.source!==I)return;if(S&&e.origin!==S)return;f(e.source,e.origin)}}),window.addEventListener("keydown",e=>{"Escape"===e.key&&W()}))}function K({path:e,qs:t,initMsg:r}){if(!a)throw new Error("init() primero");w();const d=a.view??"full";t.view=t.view??d;const u={...r||{},view:d};l(u);const{baseUrl:p,forceNexu:g}=a;A(p);const{bg:h,f:m,loader:y}=j();n=y,s(),c=h,document.body.appendChild(h),I=m.contentWindow,S=new URL(p).origin;!(!g&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("usb");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("hid");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{return!0===window.isSecureContext}catch{return!1}}())&&(t.forceNexu="1"),t.embed="1",t.parent=location.origin;let b=function(e,t,n){const r=new URL(e);return t&&(r.pathname=t),r.searchParams.set("integration","true"),r.searchParams.set("sdk","1"),Object.entries(n).forEach(([e,t])=>{null!=t&&""!==t&&r.searchParams.set(e,String(t))}),r.toString()}(p,e,t);u?.t&&(b+=`#t=${encodeURIComponent(u.t)}`),N=performance.now(),x=b,async function(e){try{await fetch(e,{mode:"no-cors",cache:"force-cache"})}catch{}}(b.split("#")[0]),_=m,v=!1;const k=(e||"").includes("/sign"),R=!!t.docId||!!t.docIds;(k||R)&&(v=!0),function(){try{_&&(_.style.opacity="0")}catch{}}(),s(),m.src=b;try{m.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},S||new URL(p).origin)}catch{}m.addEventListener("load",()=>{I=m.contentWindow,S=new URL(p).origin;try{m.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},S||new URL(p).origin)}catch{}},{once:!0}),o=window.setTimeout(()=>{E(),i(),v=!1},15e3);const T=new URL(p).origin;m.addEventListener("load",()=>{let e=!1;const t=n=>{const r=n.data||{};n.origin===T&&"trusthub_iframe"===r?.source&&"INIT_ACK"===r?.type&&(e=!0,window.removeEventListener("message",t))};window.addEventListener("message",t);let n=0;const r=window.setInterval(()=>{if(e||n>20)return window.clearInterval(r),void window.removeEventListener("message",t);n++,f(m.contentWindow,T)},250)})}async function J(e,t){O("POST",e,t);const n=new Headers;var r,o;n.set("Content-Type","application/json"),n.set("tracestate",L),n.set("baggage",(r="sdk",o=function(e){try{const t=new URL(e,window.location.origin).pathname;return t.includes("/auth/")?"auth":t.includes("/sign/")?"sign":t.includes("/verify/")?"verify":t.includes("/timestamp/")?"timestamp":"sdk"}catch{return"sdk"}}(e),`tenant=trusthub,channel=${r},operation=${o}`)),n.set("traceparent",`00-${P(16)}-${P(8)}-01`);const s=await fetch(e,{method:"POST",mode:"cors",credentials:"include",headers:n,body:JSON.stringify(t)}),i=s.headers.get("content-type")||"";let a=null;try{i.includes("application/json")&&(a=await s.clone().json())}catch{}if(O("POST result",s.status,a||"(no-json)"),!s.ok)throw new Error(`HTTP ${s.status}`);return a||{}}async function X(e){if(!a)throw new Error("init() primero");const t="headersOverride"in e?function(e){if(!e)return null;const t=String(e).split(",")[0]?.trim();if(!t)return null;const n=t.replace(/_/g,"-").toLowerCase();return n.startsWith("es")?"es-AR":n.startsWith("it")?"it-IT":n.startsWith("en")?"en-US":null}(e.headersOverride?.acceptLanguage):null,n=`${a.apiBase||new URL(a.baseUrl).origin}/api/rest/core/auth/login`,r={};if("authLogin"in e&&e.authLogin)r.authLogin=e.authLogin;else{const{username:t,password:n,environmentId:o,companyId:s,agencyId:i}=e;r.username=t,r.password=n,o&&(r.environmentId=o),s&&(r.companyId=s),i&&(r.agencyId=i)}"headersOverride"in e&&e.headersOverride&&(r.headersOverride=e.headersOverride);const o=await J(n,r).catch(e=>(O("login error:",e),null)),s=o?.ok||o?.success||o?.data?.success||o?.data?.data?.success,i=o?.data?.data?.oidc?.access_token||o?.data?.oidc?.access_token||o?.oidc?.access_token||o?.access_token,c=o?.data?.data?.oidc?.refresh_token||o?.data?.oidc?.refresh_token||o?.oidc?.refresh_token||o?.refresh_token,u=o?.data?.data?.oidc?.id_token||o?.data?.oidc?.id_token||o?.oidc?.id_token||o?.id_token,l=o?.user?.name||o?.id_tokenDecoded?.name||o?.id_tokenDecoded?.preferred_username||void 0;O("login ok?",s,"| access_token?",!!i,"| displayName?",l);const f={sdk:"1",integration:"true"};t&&(f.lng=t),"docId"in e&&e.docId&&(f.docId=e.docId),"docIds"in e&&e.docIds?.length&&(f.docIds=e.docIds.join(",")),"pdfUrl"in e&&e.pdfUrl&&(f.pdfUrl=e.pdfUrl),"signatureRect"in e&&e.signatureRect&&Object.assign(f,e.signatureRect),l&&(f.un=l);K({path:s?"/integration/dashboard/sign":"/integration/login",qs:f,initMsg:i?{t:i,rt:c,id:u,un:l}:void 0});return new Promise((e,t)=>d={resolve:e,reject:t})}function V(e){if(!a)throw new Error("init() primero");const t={};e.pdfUrl&&(t.pdfUrl=e.pdfUrl),e.signatureRect&&Object.assign(t,e.signatureRect);const n=new Promise((e,t)=>d={resolve:e,reject:t});return K({path:null,qs:t}),n}module.exports=t})();
|
package/dist/ui.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{D5:()=>h,Ki:()=>y,Ou:()=>X,Ts:()=>P,VN:()=>W,ZM:()=>m,_S:()=>U,cM:()=>R,kP:()=>w,sR:()=>T,tI:()=>k,v3:()=>V});let n=null,r=null,o=null;function s(){n&&(n.style.display="flex")}function i(){n&&(n.style.display="none",r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null)}let a=null,c=null,d=null,u=null;function l(e){e&&(u={...u||{},...e||{}})}function p(e,t){if(!e||!t)return;const n={...u||{},view:a?.view??"full"};e.postMessage({source:"trusthub_sdk",type:"INIT",...n},t)}const f=new Map;function g(){return crypto.randomUUID()}function h(){return Array.from(f.values()).map(({bytes:e,...t})=>t)}function m(e){const t=f.get(e);return t?new Uint8Array(t.bytes):null}function y(e){f.delete(e)}function w(){f.clear()}const b=new Map;let I=null,S=null,_=null,v=!1;function E(){try{_&&(_.style.opacity="1")}catch{}}async function k(e){if(!e)throw new Error("file requerido");const t=crypto.randomUUID(),n=await async function(e){const t=await e.arrayBuffer();return new Uint8Array(t)}(e);return b.set(t,{id:t,name:e.name||"document.pdf",mime:e.type||"application/pdf",bytes:n,size:n.byteLength,createdAt:Date.now()}),t}async function R(e){const t=Array.from((FileList,e)),n=[];for(const e of t)n.push(await k(e));return n}function T(e){b.delete(e)}function U(){b.clear()}const O=(...e)=>console.log("[TrustHub SDK]",...e);let N=0,x=null;function D(e,t){try{const n=`th-sdk-${e}-${t}`;if(document.getElementById(n))return;const r=document.createElement("link");r.id=n,r.rel=e,r.href=t,"preconnect"===e&&(r.crossOrigin="anonymous"),document.head.appendChild(r)}catch{}}function A(e){const t=function(e){try{return new URL(e,window.location.origin).origin}catch{return""}}(e);t&&(D("dns-prefetch",t),D("preconnect",t))}const L="es=s:1";function M(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function P(e){a={...e},z(),A(e.baseUrl),O("init",e)}function C(e,t){Object.assign(e.style,t)}function j(){!function(){if(document.getElementById("th-sdk-loader-style"))return;const e=document.createElement("style");e.id="th-sdk-loader-style",e.textContent="\n .th-sdk-loader {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n background: rgba(255,255,255,.92);\n z-index: 1; /* debajo del botón close (zIndex 2) */\n pointer-events: auto;\n font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;\n }\n .th-sdk-spinner {\n width: 28px;\n height: 28px;\n border-radius: 999px;\n border: 3px solid rgba(0,0,0,.15);\n border-top-color: rgba(0,0,0,.75);\n animation: thsdkspin .9s linear infinite;\n }\n @keyframes thsdkspin { to { transform: rotate(360deg); } }\n .th-sdk-loader-text {\n font-size: 14px;\n color: rgba(0,0,0,.75);\n font-weight: 600;\n }\n ",document.head.appendChild(e)}();const e=document.createElement("div");C(e,{position:"fixed",inset:"0",background:"rgba(0,0,0,.45)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"2147483646"});const t=document.createElement("div");C(t,{position:"relative",width:"90%",height:"80%",maxWidth:"1000px",borderRadius:"12px",overflow:"hidden",background:"#fff",boxShadow:"0 10px 30px rgba(0,0,0,.3)"});const n=document.createElement("div");n.className="th-sdk-loader",n.innerHTML='<div class="th-sdk-spinner"></div><div class="th-sdk-loader-text">Loading Quantidia SDK…</div>';const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),C(r,{position:"absolute",top:"20px",right:"18px",margin:"0",border:"0",cursor:"pointer",zIndex:"2",backgroundColor:"transparent",backgroundImage:"url('https://dev.trusthub.cloud/images/icons/Close.svg')",backgroundRepeat:"no-repeat",backgroundPosition:"center",width:"22px",height:"22px"}),r.innerHTML="",r.onclick=W;const o=document.createElement("iframe");return o.allow="hid; usb; serial; clipboard-read; clipboard-write; fullscreen",o.allowFullscreen=!0,o.referrerPolicy="strict-origin-when-cross-origin",C(o,{width:"100%",height:"100%",border:"0",opacity:"0",transition:"opacity .18s ease",background:"#fff"}),t.appendChild(o),t.appendChild(n),t.appendChild(r),e.appendChild(t),{bg:e,f:o,loader:n}}function W(){try{c?.remove()}catch{}c=null,d=null,n=null,_=null,v=!1,I=null,S=null,r&&window.clearTimeout(r),o&&window.clearTimeout(o),r=null,o=null,N=0,x=null}let F=null,B=0;const Q=new Map;let Y=null,$=null;function G(){return new Promise((e,t)=>{!function n(r,o){const s=new WebSocket(r),i=setTimeout(()=>{s.close(),o?n(o,null):t(new Error("Quantidia not available"))},3e3);s.onopen=()=>{clearTimeout(i),F=s,s.onclose=()=>{F=null},s.onmessage=e=>{try{const t=JSON.parse(e.data);if("pairing:challenge"===t.type)return void Y?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:t.code},$);if("pairing:approved"===t.type)return void Y?.postMessage({source:"trusthub",type:"QUANTIDIA_PAIRING",code:null},$);if("pairing:denied"===t.type)return Q.forEach(e=>e.rej(new Error(t.error||"Pairing denied"))),Q.clear(),F=null,void s.close();const n=Q.get(t.id);if(!n)return;Q.delete(t.id),t.ok?n.res(t.data):n.rej(new Error(t.error||"QC error"))}catch{}},e(s)},s.onerror=()=>{clearTimeout(i)}}("wss://127.0.0.1:8847","ws://127.0.0.1:8847")})}async function H(e){const t=e.data||{},{reqId:n,action:r,params:o}=t;function s(t,r,o){e.source?.postMessage({source:"trusthub",type:"QUANTIDIA_RESPONSE",reqId:n,ok:t,data:r,error:o},e.origin)}Y=e.source,$=e.origin;try{let e;if("isAvailable"===r)try{await G(),e=!0}catch{e=!1}else e=await async function(e,t){F&&F.readyState===WebSocket.OPEN||(F=await G());const n="sdk-qc-"+ ++B;return new Promise((r,o)=>{Q.set(n,{res:r,rej:o}),F.send(JSON.stringify({id:n,action:e,...t}))})}(r,o||{});s(!0,e)}catch(e){s(!1,void 0,e?.message||String(e))}}const K=new Map;function z(){z._bound||(z._bound=!0,window.addEventListener("message",e=>{const t=e.data||{};if("trusthub_iframe"!==t.source||"INIT_REQUEST"!==t.type){if("trusthub_iframe"===t.source&&"TOKENS_UPDATED"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;return void l({t:"string"==typeof t?.t?t.t:void 0,rt:"string"==typeof t?.rt?t.rt:void 0,id:"string"==typeof t?.id?t.id:void 0,un:"string"==typeof t?.un?t.un:void 0})}if("trusthub_iframe"===t.source&&"UI_READY"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;return v=!1,E(),i(),void(N&&O("UI_READY in",Math.round(performance.now()-N),"ms","|",x||""))}if("trusthub_iframe"===t.source&&"DOC_REQUEST"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;const n=String(t.docId||""),r=b.get(n);if(!r)return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_ERROR",docId:n,error:"DOC_NOT_FOUND"},e.origin);const o=new Uint8Array(r.bytes).buffer;return void e.source?.postMessage({source:"trusthub_sdk",type:"DOC_DATA",docId:n,name:r.name,mime:r.mime,buffer:o},e.origin,[o])}if("trusthub_iframe"!==t.source||"NEXU_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"QUANTIDIA_REQUEST"!==t.type)if("trusthub_iframe"!==t.source||"FORTIFY_WS_OPEN"!==t.type){if("trusthub_iframe"===t.source&&"FORTIFY_WS_SEND"===t.type){const e=K.get(t.sessionId);if(e?.ws.readyState===WebSocket.OPEN)try{e.ws.send(t.data)}catch{}return}if("trusthub_iframe"===t.source&&"FORTIFY_WS_CLOSE"===t.type){const e=K.get(t.sessionId);if(e)try{e.ws.close()}catch{}return}if("trusthub_iframe"===t.source&&"SIGNED_DOCS"===t.type){if(I&&e.source!==I)return;if(S&&e.origin!==S)return;const n=Array.isArray(t.docs)?t.docs:[],r=[];for(const e of n){const t=e?.buffer instanceof ArrayBuffer?e.buffer:null;if(!t)continue;const n=g(),o=new Uint8Array(t),s={id:n,name:String(e.name||"signed.pdf"),mime:String(e.mime||"application/pdf"),size:o.byteLength,createdAt:Date.now(),sourceDocId:"string"==typeof e.sourceDocId?e.sourceDocId:void 0};f.set(n,{...s,bytes:o}),r.push(s)}return O("SIGNED_DOCS stored:",r),void(u={...u||{},_signed:r})}if("trusthub"===t.source)if(O("message from iframe:",t),"TRUSTHUB_DONE"===t.type){const e=h(),n=d;W(),n?.resolve({status:"signed",...t.data,signed:e})}else if("TRUSTHUB_CANCELLED"===t.type){const e=d,n=t?.data?.reason;W(),e?.reject({status:"expired"===n?"expired":"cancelled"})}else if("TRUSTHUB_ERROR"===t.type){const e=d;W(),e?.reject({status:"error",...t.data})}}else!function(e){const t=e.data||{},n=t.sessionId,r=t.url||"wss://127.0.0.1:1337",o=e.source,s=e.origin;!function e(t){try{const r=new WebSocket(t);K.set(n,{ws:r,src:o,origin:s}),r.onopen=()=>o.postMessage({source:"trusthub",type:"FORTIFY_WS_OPENED",sessionId:n},s),r.onmessage=e=>{const t=e.data;t instanceof ArrayBuffer?o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!0,data:t},s,[t]):o.postMessage({source:"trusthub",type:"FORTIFY_WS_MESSAGE",sessionId:n,binary:!1,data:t},s)},r.onclose=e=>{K.delete(n),o.postMessage({source:"trusthub",type:"FORTIFY_WS_CLOSED",sessionId:n,code:e.code,reason:e.reason},s)},r.onerror=()=>{K.delete(n),t.startsWith("wss://")?e(t.replace("wss://","ws://")):o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:"connection failed"},s)}}catch(e){o.postMessage({source:"trusthub",type:"FORTIFY_WS_ERROR",sessionId:n,error:e?.message||"error"},s)}}(r)}(e);else H(e);else!async function(e){const t=e.data||{},n=t.kind;try{if(!a)throw new Error("SDK no inicializado");let r=null;if(n&&"cert"!==n){if("sign"===n){const e=a.nexuSignUrl||a.nexuUrl;if(!e)throw new Error("Nexu SIGN URL no configurada en SDK");r=await fetch(e,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(t.body||{})})}}else{if(!a.nexuUrl)throw new Error("Nexu URL no configurada en SDK");r=await fetch(a.nexuUrl,{method:"GET",mode:"cors"})}if(!r)throw new Error(`Nexu kind desconocido: ${n??"undefined"}`);if(!r.ok)throw new Error(`HTTP ${r.status}`);const o=r.headers.get("content-type")||"",s=await r.text(),i=o.includes("application/json")&&s?JSON.parse(s):s;e.source?.postMessage({source:"trusthub",type:"NEXU_RESPONSE",kind:n||"cert",data:i},e.origin)}catch(t){e.source?.postMessage({source:"trusthub",type:"NEXU_ERROR",kind:n||"cert",error:t?.message||String(t)},e.origin)}}(e)}else{if(I&&e.source!==I)return;if(S&&e.origin!==S)return;p(e.source,e.origin)}}),window.addEventListener("keydown",e=>{"Escape"===e.key&&W()}))}function q({path:e,qs:t,initMsg:r}){if(!a)throw new Error("init() primero");w();const d=a.view??"full";t.view=t.view??d;const u={...r||{},view:d};l(u);const{baseUrl:f,forceNexu:g}=a;A(f);const{bg:h,f:m,loader:y}=j();n=y,s(),c=h,document.body.appendChild(h),I=m.contentWindow,S=new URL(f).origin;!(!g&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("usb");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{const e=document?.permissionsPolicy?.allowsFeature?.("hid");if("boolean"==typeof e)return e}catch{}return!0}()&&function(){try{return!0===window.isSecureContext}catch{return!1}}())&&(t.forceNexu="1"),t.embed="1",t.parent=location.origin;let b=function(e,t,n){const r=new URL(e);return t&&(r.pathname=t),r.searchParams.set("integration","true"),r.searchParams.set("sdk","1"),Object.entries(n).forEach(([e,t])=>{null!=t&&""!==t&&r.searchParams.set(e,String(t))}),r.toString()}(f,e,t);u?.t&&(b+=`#t=${encodeURIComponent(u.t)}`),N=performance.now(),x=b,async function(e){try{await fetch(e,{mode:"no-cors",cache:"force-cache"})}catch{}}(b.split("#")[0]),_=m,v=!1;const k=(e||"").includes("/sign"),R=!!t.docId||!!t.docIds;(k||R)&&(v=!0),function(){try{_&&(_.style.opacity="0")}catch{}}(),s(),m.src=b;try{m.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},S||new URL(f).origin)}catch{}m.addEventListener("load",()=>{I=m.contentWindow,S=new URL(f).origin;try{m.contentWindow?.postMessage({source:"trusthub_sdk",type:"SIGN_START",docId:t.docId||null,docIds:t.docIds?String(t.docIds).split(",").filter(Boolean):null,rect:t.page&&t.x&&t.y?{page:Number(t.page),x:Number(t.x),y:Number(t.y),w:t.w?Number(t.w):void 0,h:t.h?Number(t.h):void 0}:null},S||new URL(f).origin)}catch{}},{once:!0}),o=window.setTimeout(()=>{E(),i(),v=!1},15e3);const T=new URL(f).origin;m.addEventListener("load",()=>{let e=!1;const t=n=>{const r=n.data||{};n.origin===T&&"trusthub_iframe"===r?.source&&"INIT_ACK"===r?.type&&(e=!0,window.removeEventListener("message",t))};window.addEventListener("message",t);let n=0;const r=window.setInterval(()=>{if(e||n>20)return window.clearInterval(r),void window.removeEventListener("message",t);n++,p(m.contentWindow,T)},250)})}async function J(e,t){O("POST",e,t);const n=new Headers;var r,o;n.set("Content-Type","application/json"),n.set("tracestate",L),n.set("baggage",(r="sdk",o=function(e){try{const t=new URL(e,window.location.origin).pathname;return t.includes("/auth/")?"auth":t.includes("/sign/")?"sign":t.includes("/verify/")?"verify":t.includes("/timestamp/")?"timestamp":"sdk"}catch{return"sdk"}}(e),`tenant=trusthub,channel=${r},operation=${o}`)),n.set("traceparent",`00-${M(16)}-${M(8)}-01`);const s=await fetch(e,{method:"POST",mode:"cors",credentials:"include",headers:n,body:JSON.stringify(t)}),i=s.headers.get("content-type")||"";let a=null;try{i.includes("application/json")&&(a=await s.clone().json())}catch{}if(O("POST result",s.status,a||"(no-json)"),!s.ok)throw new Error(`HTTP ${s.status}`);return a||{}}async function V(e){if(!a)throw new Error("init() primero");const t="headersOverride"in e?function(e){if(!e)return null;const t=String(e).split(",")[0]?.trim();if(!t)return null;const n=t.replace(/_/g,"-").toLowerCase();return n.startsWith("es")?"es-AR":n.startsWith("it")?"it-IT":n.startsWith("en")?"en-US":null}(e.headersOverride?.acceptLanguage):null,n=`${a.apiBase||new URL(a.baseUrl).origin}/api/rest/core/auth/login`,r={};if("authLogin"in e&&e.authLogin)r.authLogin=e.authLogin;else{const{username:t,password:n,environmentId:o,companyId:s,agencyId:i}=e;r.username=t,r.password=n,o&&(r.environmentId=o),s&&(r.companyId=s),i&&(r.agencyId=i)}"headersOverride"in e&&e.headersOverride&&(r.headersOverride=e.headersOverride);const o=await J(n,r).catch(e=>(O("login error:",e),null)),s=o?.ok||o?.success||o?.data?.success||o?.data?.data?.success,i=o?.data?.data?.oidc?.access_token||o?.data?.oidc?.access_token||o?.oidc?.access_token||o?.access_token,c=o?.data?.data?.oidc?.refresh_token||o?.data?.oidc?.refresh_token||o?.oidc?.refresh_token||o?.refresh_token,u=o?.data?.data?.oidc?.id_token||o?.data?.oidc?.id_token||o?.oidc?.id_token||o?.id_token,l=o?.user?.name||o?.id_tokenDecoded?.name||o?.id_tokenDecoded?.preferred_username||void 0;O("login ok?",s,"| access_token?",!!i,"| displayName?",l);const p={sdk:"1",integration:"true"};t&&(p.lng=t),"docId"in e&&e.docId&&(p.docId=e.docId),"docIds"in e&&e.docIds?.length&&(p.docIds=e.docIds.join(",")),"pdfUrl"in e&&e.pdfUrl&&(p.pdfUrl=e.pdfUrl),"signatureRect"in e&&e.signatureRect&&Object.assign(p,e.signatureRect),l&&(p.un=l);q({path:s?"/integration/dashboard/sign":"/integration/login",qs:p,initMsg:i?{t:i,rt:c,id:u,un:l}:void 0});return new Promise((e,t)=>d={resolve:e,reject:t})}function X(e){if(!a)throw new Error("init() primero");const t={};e.pdfUrl&&(t.pdfUrl=e.pdfUrl),e.signatureRect&&Object.assign(t,e.signatureRect);const n=new Promise((e,t)=>d={resolve:e,reject:t});return q({path:null,qs:t}),n}const Z=t.tI,ee=t.cM,te=t._S,ne=t.kP,re=t.VN,oe=t.ZM,se=t.Ts,ie=t.D5,ae=t.Ou,ce=t.v3,de=t.sR,ue=t.Ki;export{Z as addDocument,ee as addDocuments,te as clearDocuments,ne as clearSignedDocuments,re as close,oe as getSignedDocumentBytes,se as init,ie as listSignedDocuments,ae as openSigning,ce as openSigningWithLogin,de as removeDocument,ue as removeSignedDocument};
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@quantidia/sdk",
|
|
3
|
+
"version": "1.0.4",
|
|
4
|
+
"description": "Quantidia SDK for digital signature integrations (Fortify, Nexu, cloud signing)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/quantidia-sdk.cjs",
|
|
7
|
+
"module": "./dist/quantidia-sdk.es.js",
|
|
8
|
+
"types": "./dist/src/index.d.ts",
|
|
9
|
+
"browser": "./dist/quantidia-sdk.umd.min.js",
|
|
10
|
+
"jsdelivr": "./dist/quantidia-sdk.umd.min.js",
|
|
11
|
+
"unpkg": "./dist/quantidia-sdk.umd.min.js",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/src/index.d.ts",
|
|
15
|
+
"import": "./dist/quantidia-sdk.es.js",
|
|
16
|
+
"require": "./dist/quantidia-sdk.cjs"
|
|
17
|
+
},
|
|
18
|
+
"./ui": {
|
|
19
|
+
"types": "./dist/src/ui.d.ts",
|
|
20
|
+
"import": "./dist/ui.mjs",
|
|
21
|
+
"require": "./dist/ui.cjs"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"CHANGELOG.md"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "npm run build:types && webpack --config webpack.config.js",
|
|
32
|
+
"build:types": "tsc --emitDeclarationOnly",
|
|
33
|
+
"test": "echo \"No tests configured yet\" && exit 0",
|
|
34
|
+
"prepublishOnly": "npm run build",
|
|
35
|
+
"copy:umd": "node -e \"require('fs').copyFileSync('dist/quantidia-sdk.umd.min.js','../public/quantidia-sdk.js')\""
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"quantidia",
|
|
39
|
+
"sdk",
|
|
40
|
+
"digital-signature",
|
|
41
|
+
"signature",
|
|
42
|
+
"trusthub",
|
|
43
|
+
"fortify",
|
|
44
|
+
"nexu",
|
|
45
|
+
"pades",
|
|
46
|
+
"pkcs11",
|
|
47
|
+
"esignature"
|
|
48
|
+
],
|
|
49
|
+
"author": "Quantidia",
|
|
50
|
+
"license": "MIT",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "git",
|
|
53
|
+
"url": "https://github.com/quantidia/quantidia-sdk-js"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"typescript": "^5",
|
|
57
|
+
"ts-loader": "^9",
|
|
58
|
+
"webpack": "^5",
|
|
59
|
+
"webpack-cli": "^5",
|
|
60
|
+
"terser-webpack-plugin": "^5"
|
|
61
|
+
}
|
|
62
|
+
}
|