@subnoto/api-client 2.0.7 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  var Qe=Object.defineProperty;var de=(e,t)=>{for(var i in t)Qe(e,i,{get:t[i],enumerable:!0})};import m1 from"openapi-fetch";var _={};de(_,{generateDigestHeaders:()=>Me,generateSignatureHeader:()=>Be});var le=typeof Uint8Array=="function",T,U=class e{static decode(t){let i=typeof t=="string",r;if(T===void 0){let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=`= \f
2
2
  \r \xA0\u2028\u2029`;for(T=[],r=0;r<64;++r)T[a.charCodeAt(r)]=r;for(r=0;r<u.length;++r)T[u.charCodeAt(r)]=-1;T[45]=T[43],T[95]=T[47]}let s=le?new Uint8Array(t.length*3>>2):[],o=0,d=0,n=0;for(r=0;r<t.length;++r){let a=i?t.charCodeAt(r):t[r];if(a==61)break;if(a=T[a],a!=-1){if(a===void 0)throw"Illegal character at offset "+r;o|=a,++d>=4?(s[n++]=o>>16,s[n++]=o>>8&255,s[n++]=o&255,o=0,d=0):o<<=6}}switch(d){case 1:throw"Base64 encoding incomplete: at least 2 bits missing";case 2:s[n++]=o>>10;break;case 3:s[n++]=o>>16,s[n++]=o>>8&255;break}return le&&s.length>n&&(s=s.subarray(0,n)),s}static pretty(t){let i=4-t.length%4;return i<4&&(t+="===".slice(0,i)),t=t.replace(/-/g,"+").replace(/_/g,"/"),t.replace(/.{80}/g,`$&
3
3
  `)}static unarmor(t){let i=e.re.exec(t);if(i)if(i[1])t=i[1];else if(i[2])t=i[2];else if(i[3])t=i[3];else throw"RegExp out of sync";return e.decode(t)}};U.re=/-----BEGIN [^-]+-----([A-Za-z0-9+/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+/=\s]+)====|^([A-Za-z0-9+/=\s]+)$/;var ue={chars:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bits:6};var P={parse:function(t,i){return Ze(t,ue,i)},stringify:function(t,i){return Je(t,ue,i)}};function Ze(e,t,i){var r;if(i===void 0&&(i={}),!t.codes){t.codes={};for(var s=0;s<t.chars.length;++s)t.codes[t.chars[s]]=s}if(!i.loose&&e.length*t.bits&7)throw new SyntaxError("Invalid padding");for(var o=e.length;e[o-1]==="=";)if(--o,!i.loose&&!((e.length-o)*t.bits&7))throw new SyntaxError("Invalid padding");for(var d=new((r=i.out)!=null?r:Uint8Array)(o*t.bits/8|0),n=0,a=0,u=0,S=0;S<o;++S){var c=t.codes[e[S]];if(c===void 0)throw new SyntaxError("Invalid character "+e[S]);a=a<<t.bits|c,n+=t.bits,n>=8&&(n-=8,d[u++]=255&a>>n)}if(n>=t.bits||255&a<<8-n)throw new SyntaxError("Unexpected end of data");return d}function Je(e,t,i){i===void 0&&(i={});for(var r=i,s=r.pad,o=s===void 0?!0:s,d=(1<<t.bits)-1,n="",a=0,u=0,S=0;S<e.length;++S)for(u=u<<8|255&e[S],a+=8;a>t.bits;)a-=t.bits,n+=t.chars[d&u>>a];if(a&&(n+=t.chars[d&u<<t.bits-a]),o)for(;n.length*t.bits&7;)n+="=";return n}var Ye=Object.create,ge=Object.defineProperty,et=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyNames,tt=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty,k=(e,t)=>function(){return t||(0,e[Ce(e)[0]])((t={exports:{}}).exports,t),t.exports},rt=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ce(t))!it.call(e,s)&&s!==i&&ge(e,s,{get:()=>t[s],enumerable:!(r=et(t,s))||r.enumerable});return e},V=(e,t,i)=>(i=e!=null?Ye(tt(e)):{},rt(t||!e||!e.__esModule?ge(i,"default",{value:e,enumerable:!0}):i,e)),ee=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/types.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ByteSequence=void 0;var t=class{constructor(i){this.base64Value=i}toBase64(){return this.base64Value}};e.ByteSequence=t}}),L=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/util.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isByteSequence=e.isInnerList=e.isValidKeyStr=e.isValidTokenStr=e.isAscii=void 0;var t=/^[\x20-\x7E]*$/,i=/^[a-zA-Z*][:/!#$%&'*+\-.^_`|~A-Za-z0-9]*$/,r=/^[a-z*][*\-_.a-z0-9]*$/;function s(u){return t.test(u)}e.isAscii=s;function o(u){return i.test(u)}e.isValidTokenStr=o;function d(u){return r.test(u)}e.isValidKeyStr=d;function n(u){return Array.isArray(u[0])}e.isInnerList=n;function a(u){return typeof u=="object"&&"base64Value"in u}e.isByteSequence=a}}),te=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/token.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Token=void 0;var t=L(),i=class{constructor(r){if(!(0,t.isValidTokenStr)(r))throw new TypeError("Invalid character in Token string. Tokens must start with *, A-Z and the rest of the string may only contain a-z, A-Z, 0-9, :/!#$%&'*+-.^_`|~");this.value=r}toString(){return this.value}};e.Token=i}}),st=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/serializer.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.serializeKey=e.serializeParameters=e.serializeToken=e.serializeByteSequence=e.serializeBoolean=e.serializeString=e.serializeDecimal=e.serializeInteger=e.serializeBareItem=e.serializeInnerList=e.serializeItem=e.serializeDictionary=e.serializeList=e.SerializeError=void 0;var t=ee(),i=te(),r=L(),s=class extends Error{};e.SerializeError=s;function o(l){return l.map(g=>(0,r.isInnerList)(g)?a(g):n(g)).join(", ")}e.serializeList=o;function d(l){return Array.from(l.entries()).map(([g,A])=>{let E=b(g);return A[0]===!0?E+=I(A[1]):(E+="=",(0,r.isInnerList)(A)?E+=a(A):E+=n(A)),E}).join(", ")}e.serializeDictionary=d;function n(l){return u(l[0])+I(l[1])}e.serializeItem=n;function a(l){return`(${l[0].map(g=>n(g)).join(" ")})${I(l[1])}`}e.serializeInnerList=a;function u(l){if(typeof l=="number")return Number.isInteger(l)?S(l):c(l);if(typeof l=="string")return p(l);if(l instanceof i.Token)return v(l);if(l instanceof t.ByteSequence)return y(l);if(typeof l=="boolean")return f(l);throw new s(`Cannot serialize values of type ${typeof l}`)}e.serializeBareItem=u;function S(l){if(l<-999999999999999||l>999999999999999)throw new s("Structured headers can only encode integers in the range range of -999,999,999,999,999 to 999,999,999,999,999 inclusive");return l.toString()}e.serializeInteger=S;function c(l){let g=l.toFixed(3).replace(/0+$/,"");if(g.split(".")[0].replace("-","").length>12)throw new s("Fractional numbers are not allowed to have more than 12 significant digits before the decimal point");return g}e.serializeDecimal=c;function p(l){if(!(0,r.isAscii)(l))throw new s("Only ASCII strings may be serialized");return`"${l.replace(/("|\\)/g,g=>"\\"+g)}"`}e.serializeString=p;function f(l){return l?"?1":"?0"}e.serializeBoolean=f;function y(l){return`:${l.toBase64()}:`}e.serializeByteSequence=y;function v(l){return l.toString()}e.serializeToken=v;function I(l){return Array.from(l).map(([g,A])=>{let E=";"+b(g);return A!==!0&&(E+="="+u(A)),E}).join("")}e.serializeParameters=I;function b(l){if(!(0,r.isValidKeyStr)(l))throw new s("Keys in dictionaries must only contain lowercase letter, numbers, _-*. and must start with a letter or *");return l}e.serializeKey=b}}),nt=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/parser.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ParseError=e.parseItem=e.parseList=e.parseDictionary=void 0;var t=ee(),i=te(),r=L();function s(c){return new a(c).parseDictionary()}e.parseDictionary=s;function o(c){return new a(c).parseList()}e.parseList=o;function d(c){return new a(c).parseItem()}e.parseItem=d;var n=class extends Error{constructor(c,p){super(`Parse error: ${p} at offset ${c}`)}};e.ParseError=n;var a=class{constructor(c){this.input=c,this.pos=0}parseDictionary(){this.skipWS();let c=new Map;for(;!this.eof();){let p=this.parseKey(),f;if(this.lookChar()==="="?(this.pos++,f=this.parseItemOrInnerList()):f=[!0,this.parseParameters()],c.set(p,f),this.skipOWS(),this.eof())return c;if(this.expectChar(","),this.pos++,this.skipOWS(),this.eof())throw new n(this.pos,"Dictionary contained a trailing comma")}return c}parseList(){this.skipWS();let c=[];for(;!this.eof();){if(c.push(this.parseItemOrInnerList()),this.skipOWS(),this.eof())return c;if(this.expectChar(","),this.pos++,this.skipOWS(),this.eof())throw new n(this.pos,"A list may not end with a trailing comma")}return c}parseItem(c=!0){c&&this.skipWS();let p=[this.parseBareItem(),this.parseParameters()];return c&&this.checkTrail(),p}parseItemOrInnerList(){return this.lookChar()==="("?this.parseInnerList():this.parseItem(!1)}parseInnerList(){this.expectChar("("),this.pos++;let c=[];for(;!this.eof();){if(this.skipWS(),this.lookChar()===")")return this.pos++,[c,this.parseParameters()];c.push(this.parseItem(!1));let p=this.lookChar();if(p!==" "&&p!==")")throw new n(this.pos,"Expected a whitespace or ) after every item in an inner list")}throw new n(this.pos,"Could not find end of inner list")}parseBareItem(){let c=this.lookChar();if(c===void 0)throw new n(this.pos,"Unexpected end of string");if(c.match(/^[-0-9]/))return this.parseIntegerOrDecimal();if(c==='"')return this.parseString();if(c.match(/^[A-Za-z*]/))return this.parseToken();if(c===":")return this.parseByteSequence();if(c==="?")return this.parseBoolean();throw new n(this.pos,"Unexpected input")}parseParameters(){let c=new Map;for(;!this.eof()&&this.lookChar()===";";){this.pos++,this.skipWS();let f=this.parseKey(),y=!0;this.lookChar()==="="&&(this.pos++,y=this.parseBareItem()),c.set(f,y)}return c}parseIntegerOrDecimal(){let c="integer",p=1,f="";if(this.lookChar()==="-"&&(p=-1,this.pos++),!S(this.lookChar()))throw new n(this.pos,"Expected a digit (0-9)");for(;!this.eof();){let y=this.getChar();if(S(y))f+=y;else if(c==="integer"&&y==="."){if(f.length>12)throw new n(this.pos,"Exceeded maximum decimal length");f+=".",c="decimal"}else{this.pos--;break}if(c==="integer"&&f.length>15)throw new n(this.pos,"Exceeded maximum integer length");if(c==="decimal"&&f.length>16)throw new n(this.pos,"Exceeded maximum decimal length")}if(c==="integer")return parseInt(f,10)*p;if(f.endsWith("."))throw new n(this.pos,"Decimal cannot end on a period");if(f.split(".")[1].length>3)throw new n(this.pos,"Number of digits after the decimal point cannot exceed 3");return parseFloat(f)*p}parseString(){let c="";for(this.expectChar('"'),this.pos++;!this.eof();){let p=this.getChar();if(p==="\\"){if(this.eof())throw new n(this.pos,"Unexpected end of input");let f=this.getChar();if(f!=="\\"&&f!=='"')throw new n(this.pos,"A backslash must be followed by another backslash or double quote");c+=f}else{if(p==='"')return c;if((0,r.isAscii)(p))c+=p;else throw new n(this.pos,"Strings must be in the ASCII range")}}throw new n(this.pos,"Unexpected end of input")}parseToken(){let c="";for(;!this.eof();){let p=this.lookChar();if(p===void 0||!/^[:/!#$%&'*+\-.^_`|~A-Za-z0-9]$/.test(p))return new i.Token(c);c+=this.getChar()}return new i.Token(c)}parseByteSequence(){this.expectChar(":"),this.pos++;let c=this.input.indexOf(":",this.pos);if(c===-1)throw new n(this.pos,'Could not find a closing ":" character to mark end of Byte Sequence');let p=this.input.substring(this.pos,c);if(this.pos+=p.length+1,!/^[A-Za-z0-9+/=]*$/.test(p))throw new n(this.pos,"ByteSequence does not contain a valid base64 string");return new t.ByteSequence(p)}parseBoolean(){this.expectChar("?"),this.pos++;let c=this.getChar();if(c==="1")return!0;if(c==="0")return!1;throw new n(this.pos,'Unexpected character. Expected a "1" or a "0"')}parseKey(){var c;if(!(!((c=this.lookChar())===null||c===void 0)&&c.match(/^[a-z*]/)))throw new n(this.pos,"A key must begin with an asterisk or letter (a-z)");let p="";for(;!this.eof();){let f=this.lookChar();if(f===void 0||!/^[a-z0-9_\-.*]$/.test(f))return p;p+=this.getChar()}return p}lookChar(){return this.input[this.pos]}expectChar(c){if(this.lookChar()!==c)throw new n(this.pos,`Expected ${c}`)}getChar(){return this.input[this.pos++]}eof(){return this.pos>=this.input.length}skipOWS(){for(;;){let c=this.input.substr(this.pos,1);if(c===" "||c===" ")this.pos++;else break}}skipWS(){for(;this.lookChar()===" ";)this.pos++}checkTrail(){if(this.skipWS(),!this.eof())throw new n(this.pos,"Unexpected characters at end of input")}};e.default=a;var u=/^[0-9]$/;function S(c){return c===void 0?!1:u.test(c)}}}),z=k({"node_modules/.pnpm/structured-headers@1.0.1/node_modules/structured-headers/dist/index.js"(e){"use strict";var t=e&&e.__createBinding||(Object.create?function(s,o,d,n){n===void 0&&(n=d);var a=Object.getOwnPropertyDescriptor(o,d);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[d]}}),Object.defineProperty(s,n,a)}:function(s,o,d,n){n===void 0&&(n=d),s[n]=o[d]}),i=e&&e.__exportStar||function(s,o){for(var d in s)d!=="default"&&!Object.prototype.hasOwnProperty.call(o,d)&&t(o,s,d)};Object.defineProperty(e,"__esModule",{value:!0}),e.Token=void 0,i(st(),e),i(nt(),e),i(ee(),e),i(L(),e);var r=te();Object.defineProperty(e,"Token",{enumerable:!0,get:function(){return r.Token}})}});var x1=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);var ye=new TextEncoder;async function ct(){return globalThis.crypto??(await import("node:crypto")).webcrypto}var ot=/[^\S\r\n]*\r?\n[^\S\r\n]+/g;function pe(e){return e.replaceAll(ot," ")}function N(e){if(typeof e=="number")return e.toString();if(!e)return"";if(typeof e=="string")return pe(e).trim();if(Array.isArray(e))return e.map(t=>{if(t==null)return"";if(typeof t=="number")return t.toString();if(typeof t=="string")return pe(t).trim();throw new Error(`Invalid header value type ${t}`)}).join(", ");throw new Error(`Invalid header value type ${e}`)}function q(e){return Object.entries(e).reduce((t,[i,r])=>(i==="__proto__"||(t[i.toLowerCase()]=r),t),{})}function he(e,t){t=t.toLowerCase();for(let[i,r]of Object.entries(e))if(i.toLowerCase()===t)return r}function at(e){return typeof e=="number"?e.toString():typeof e=="string"?e.toLowerCase():""}function Y(e){return e.reduce((t,i,r)=>{if(r%2===0){if(typeof i!="string")throw new Error(`Invalid header key type '${typeof i}' of ${i}`);if(i.toLowerCase()in t)return t;t[i.toLowerCase()]=[]}else t[at(e[r-1])].push(i==null?"":i.toString());return t},{})}function B(e){if("rawHeaders"in e&&e.rawHeaders)return Y(e.rawHeaders.flat(1));if("getHeaders"in e&&typeof e.getHeaders=="function")return q(e.getHeaders());if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Error("headers must be an object");return Ae(e.headers)?Y(Array.from(e.headers.entries()).flat(1)):Array.isArray(e.headers)?Y(e.headers.flat(1)):q(e.headers)}throw new Error("Cannot get headers from request object")}function Ie(e,t,i){if("setHeader"in e&&typeof e.setHeader=="function")e.setHeader(t,i.toString());else if("headers"in e&&typeof e.headers=="object")Ae(e.headers)?e.headers.set(t,i.toString()):e.headers[t]=i.toString();else throw new Error("Cannot set headers to request object")}function Se(e){return"Response"in globalThis&&typeof e=="object"&&e instanceof Response}function dt(e){return"Request"in globalThis&&typeof e=="object"&&e instanceof Request}function Ae(e){return"Headers"in globalThis&&typeof e=="object"&&e instanceof Headers}function be(e){let t=new Uint8Array(e);return P.stringify(t)}var lt={hash:"SHA-256",ec:"DSA"};function ut(e,t){return{hash:t,...e}}function ie(e){return e instanceof Map?new Map(e):Array.isArray(e)?new Map(e):new Map(Object.entries(e))}function fe(e){let t=ie(e);for(let[i,r]of t.entries())r===void 0&&t.delete(i);return t}var C=V(z(),1),pt={signature:"dict","signature-input":"dict","accept-signature":"dict","content-digest":"dict","repr-digest":"dict","want-content-digest":"dict","want-repr-digest":"dict","accept-ch":"list","proxy-status":"list","cache-status":"list",priority:"dict","client-cert":"bs","client-cert-chain":"list"},ht=["@method","@authority","@scheme","@target-uri","@request-target","@path","@query"],St=["@status"],Ee=class{isRequest(){return this.response===null}isResponse(){return this.response!==null}constructor(e,t="https",i={},r,s=null){if(s&&!Array.isArray(s))throw new Error("requiredComponents must be an array");if(s&&s.length>0?this.requiredComponents=s.map(n=>{let a;return n.startsWith('"')?a=C.parseItem(n):a=[n,new Map],C.serializeItem(a)}):this.requiredComponents=null,this.sfvTypeDictionary=q({...pt,...i}),"req"in e)this.response=e,this.responseHeaders=B(e),this.request=e.req,this.requestHeaders=B(this.request);else if(Se(e)){if(!r)throw new Error("Request is not provided");this.response=e,this.responseHeaders=B(e),this.request=r,this.requestHeaders=B(this.request)}else this.response=null,this.responseHeaders=null,this.request=e,this.requestHeaders=B(e);if(!this.request.url)throw new Error("Request URL is empty");if(!this.request.method)throw new Error("Request method is empty");if(!("signature-input"in this.requestHeaders))throw new Error("Signature-Input header is not found in request");if(this.requestSignatureInput=C.parseDictionary(N(this.requestHeaders["signature-input"])),this.isResponse()){if(!this.responseHeaders)throw new Error("responseHeaders is empty");if(!("signature-input"in this.responseHeaders))throw new Error("Signature-Input header is not found in response");this.responseSignatureInput=C.parseDictionary(N(this.responseHeaders["signature-input"]))}this.sfvTypeDictionary=q(i),this.scheme=this.request.url.startsWith("/")?t:new URL(this.request.url).protocol.replace(":","");let o="httpVersionMajor"in this.request&&this.request.httpVersionMajor===2?this.requestHeaders[":authority"]:this.requestHeaders.host;if(!dt(this.request)&&!o)throw new Error("Host header is empty");let d=N(o);this.targetUri=this.request.url.startsWith("/")?new URL(this.request.url,`${t}://${d}`).href:this.request.url,this.url=new URL(this.targetUri)}get(e,t=new Map){let i=ie(t),r=C.serializeItem([e,i]);if(!e)throw new Error(`Type is empty: ${r}`);if(e.startsWith('"'))if(e.endsWith('"'))e=e.slice(1,-1);else throw new Error(`Invalid component type string: ${r}`);if(this.isResponse()&&i.get("req")!==!0&&ht.includes(e))throw new Error(`component is not available in response (must use with ;req, or provided object is unintentionally treated as response (existing req prop.)): ${e}`);if(this.isRequest()&&St.includes(e))throw new Error(`component is not available in request (provided object is unintentionally treated as request (including req prop.)): ${e}`);if(this.isRequest()&&i.get("req")===!0)throw new Error("req param is not available in request (provided object is treated as request, please set req param with Request)");let s=this.isRequest()||i.get("req")===!0;if(e==="@signature-params")throw new Error(`@signature-params is not available in get method: ${r}`);if(e==="@method"){if(!this.request.method)throw new Error("Request method is empty");return this.request.method.toUpperCase()}else{if(e==="@authority")return this.url.host;if(e==="@scheme")return this.scheme.toLocaleLowerCase();if(e==="@target-uri")return this.targetUri;if(e==="@request-target"){if(!this.request.method)throw new Error("Request method is empty");return`${this.request.method.toLowerCase()} ${this.url.pathname}`}else{if(e==="@path")return this.url.pathname;if(e==="@query")return this.url.search;if(e==="@query-param"){let o=i.get("name");if(o===void 0)throw new Error("Query parameter name not found or invalid");let d=this.url.searchParams.get(o.toString());if(d===null)throw new Error(`Query parameter not found: ${o} (${r})`);return d}else if(e==="@status"){if(!this.response)throw new Error("response is empty (@status)");return Se(this.response)?this.response.status.toString():this.response.statusCode.toString()}else{if(e.startsWith("@"))throw new Error(`Unknown derived component: ${e}`);{let o=i.get("key"),d=i.get("sf")===!0,n=i.get("bs")===!0,a=i.get("tr")===!0;if([o,d,n].filter(S=>S).length>1)throw new Error(`Invalid component: ${r} (multiple params are specified)`);let u=(()=>{if(s)if(a){if("trailers"in this.request&&this.request.trailers)return he(this.request.trailers,e);throw new Error(`Trailers not found in request object (${r})`)}else return this.requestHeaders[e];else{if(!this.response||!this.responseHeaders)throw new Error("response is not provided");if(a){if("trailers"in this.response&&this.response.trailers)return he(this.response.trailers,e);throw new Error(`Trailers not found in response object (${r})`)}else return this.responseHeaders[e]}})();if(u===void 0)throw new Error(`Header not found: ${r}`);if(d){if(!(e in this.sfvTypeDictionary))throw new Error(`Type not found in SFV type dictionary: ${e}`);let S=N(u);if(this.sfvTypeDictionary[e]==="dict")return C.serializeDictionary(C.parseDictionary(S));if(this.sfvTypeDictionary[e]==="list")return C.serializeList(C.parseList(S));if(["item","bs","int","dec","str","bool","token"].includes(this.sfvTypeDictionary[e]))return C.serializeItem(C.parseItem(S))}if(o){if(!(e in this.sfvTypeDictionary))throw new Error(`key specified but type unknown (Type not found in SFV type dictionary): ${r}`);if(typeof u!="string")throw new Error(`Key specified but value is not a string: ${r}`);if(this.sfvTypeDictionary[e]==="dict"){let c=C.parseDictionary(u).get(o);if(c===void 0)throw new Error(`Key not found in dictionary: ${o} (${r})`);return Array.isArray(c[0])?C.serializeList([c]):C.serializeItem(c)}else throw new Error(`"${e}" is not dict: ${this.sfvTypeDictionary[e]} (${r})`)}if(n){let S=(Array.isArray(u)?u:[u]).map(c=>{if(typeof c!="string")throw new Error(`Invalid header value type: ${typeof c}`);return[new C.ByteSequence(be(ye.encode(N(c)).buffer)),new Map]});return C.serializeList(S)}return N(u)}}}}}generate(e){let t=this.isRequest()?this.requestSignatureInput?.get(e):this.responseSignatureInput?.get(e);if(!t)throw new Error(`label not found: ${e}`);if(!Array.isArray(t[0]))throw new Error(`item is not InnerList: ${C.serializeDictionary(new Map([[e,t]]))}`);let i=new Map;for(let r of t[0]){let s=r[0];if(s.startsWith('"'))if(s.endsWith('"'))s=s.slice(1,-1);else throw new Error(`Invalid component identifier name: ${s}`);r[0]=s;let o=C.serializeItem(r);if(i.has(o))throw new Error(`Duplicate key: ${s}`);i.set(o,this.get(s,r[1]))}if(this.requiredComponents){for(let r of this.requiredComponents)if(!i.has(r))throw new Error(`Required component not found: ${r}`)}return i.set('"@signature-params"',C.serializeInnerList(t)),Array.from(i.entries(),([r,s])=>`${r}: ${s}`).join(`
4
- `)}};function Te(e){let t=ie(e),i=new Map;for(let[r,s]of t){if(!Array.isArray(s))throw new Error("item is not array");let[o,d]=s;i.set(r,[o.map(n=>typeof n=="string"?[n,new Map]:[n[0],fe(n[1])]),fe(d)])}return C.serializeDictionary(i)}var F1=V(z(),1);async function Pe(e,t,i=lt){let r=await(await ct()).subtle.sign(ut(e.algorithm,i.hash),e,ye.encode(t));return be(r)}var G1=V(z(),1);function we(e){let t=e.toUpperCase();if(t==="SHA-256")return"sha-256";if(t==="SHA-512")return"sha-512";throw new Error(`Unsupported hash algorithm: ${e}`)}var q1=V(z(),1);async function j(){return globalThis.crypto??(await import("node:crypto")).webcrypto}var De=e=>{let t=new Uint8Array(e);return P.stringify(t)};var ft=async(e,t="SHA-256")=>(t==="SHA"&&(t="SHA-1"),typeof e=="string"&&(e=new TextEncoder().encode(e)),(await j()).subtle.digest(t,e)),Me=async e=>{let t="SHA-256",i=await ft(e.body,t).then(De),r=`${t}=${i}`,s=`${we(t)}=:${i}:`;return{digest:r,contentDigest:s}};var mt=/^[\x20-\x7E]*$/,gt=/^[a-zA-Z*][:/!#$%&'*+\-.^_`|~A-Za-z0-9]*$/,Ct=/^[a-z*][*\-_.a-z0-9]*$/;function re(e){return mt.test(e)}function ve(e){return gt.test(e)}function Ne(e){return Ct.test(e)}function ke(e){return Array.isArray(e[0])}function Ke(e){let t=new Uint8Array(e),i="";for(let r of t)i+=String.fromCharCode(r);return btoa(i)}function se(e){let t=atob(e),i=t.length,r=new Uint8Array(i);for(let s=0;s<i;s++)r[s]=t.charCodeAt(s);return r.buffer}var K=class{constructor(t){if(!ve(t))throw new TypeError("Invalid character in Token string. Tokens must start with *, A-Z and the rest of the string may only contain a-z, A-Z, 0-9, :/!#$%&'*+-.^_`|~");this.value=t}toString(){return this.value}};var R=class{constructor(t){this.value=t}toString(){return this.value}};var D=class extends Error{};function Re(e){let t=e instanceof Map?e.entries():Object.entries(e);return Array.from(t).map(([i,r])=>{let s=xe(i);return Array.isArray(r)?r[0]===!0?s+Q(r[1]):ke(r)?s+"="+yt(r):s+"="+Oe(r):r===!0?s:s+"="+$(r)}).join(", ")}function Oe(e,t){return Array.isArray(e)?$(e[0])+Q(e[1]):$(e)+(t?Q(t):"")}function yt(e){return`(${e[0].map(t=>Oe(t)).join(" ")})${Q(e[1])}`}function $(e){if(typeof e=="number")return Number.isInteger(e)?It(e):At(e);if(typeof e=="string")return bt(e);if(e instanceof K)return wt(e);if(e instanceof ArrayBuffer)return Pt(e);if(e instanceof R)return Et(e);if(e instanceof Date)return Dt(e);if(typeof e=="boolean")return Tt(e);throw new D(`Cannot serialize values of type ${typeof e}`)}function It(e){if(e<-999999999999999||e>999999999999999)throw new D("Structured headers can only encode integers in the range range of -999,999,999,999,999 to 999,999,999,999,999 inclusive");return e.toString()}function At(e){let t=e.toFixed(3).replace(/0+$/,"");if(t.split(".")[0].replace("-","").length>12)throw new D("Fractional numbers are not allowed to have more than 12 significant digits before the decimal point");return t}function bt(e){if(!re(e))throw new D("Only ASCII strings may be serialized");return`"${e.replace(/("|\\)/g,t=>"\\"+t)}"`}function Et(e){let t='%"',i=new TextEncoder;for(let r of i.encode(e.toString()))r===37||r===34||r<=31||r>=127?t+="%"+r.toString(16):t+=String.fromCharCode(r);return t+'"'}function Tt(e){return e?"?1":"?0"}function Pt(e){return`:${Ke(e)}:`}function wt(e){return e.toString()}function Dt(e){return"@"+Math.floor(e.getTime()/1e3)}function Q(e){return Array.from(e).map(([t,i])=>{let r=";"+xe(t);return i!==!0&&(r+="="+$(i)),r}).join("")}function xe(e){if(!Ne(e))throw new D("Keys in dictionaries must only contain lowercase letter, numbers, _-*. and must start with a letter or *");return e}var Be=async e=>{let{request:t,authenticationType:i,accessKey:r,secretKey:s,creationDate:o}=e,d={key_ops:["sign","verify"],ext:!0,kty:"oct",k:s,alg:"HS256"},n=await(await j()).subtle.importKey("jwk",d,{name:"HMAC",hash:"SHA-256"},!0,["sign","verify"]),a=new Map,u=new Map;a.set(i,n),u.set(i,[["x-timestamp","@authority","content-type","content-digest","content-length"],{keyid:r,created:o,alg:"hmac-sha256"}]);let S=Te(u);Ie(t,"Signature-Input",S);let c=new Ee(t),p=(c.isRequest()?c.requestSignatureInput:c.responseSignatureInput)?.keys();if(!p)throw new Error("signaturesEntries is undefined");let f=new Map,y=new Map;for(let I of p){let b=c.generate(I),l=a.get(I);if(!l)throw new Error(`key not found: ${I}`);y.set(I,b),f.set(I,[se(await Pe(l,b,{hash:"SHA-256",ec:"DSA"})),new Map])}let v=Re(f);return{signatureInputHeader:S,signatureHeader:v}};function _e(e){return{async onRequest({request:t}){let i=t.clone(),r=i.url,s=await i.arrayBuffer()??JSON.stringify({}),o=i.method??"POST",d=await _.generateDigestHeaders({body:s}),n={headers:{"X-Timestamp":Date.now().toString(),Host:new URL(r).host,"Content-Type":i.headers.get("Content-Type")??"application/json","Content-Length":i.headers.get("Content-Length")??s.byteLength.toString(),Digest:d.digest,"Content-Digest":d.contentDigest},body:s.toString(),method:o,url:r},{signatureHeader:a,signatureInputHeader:u}=await _.generateSignatureHeader({request:n,authenticationType:"team",accessKey:e.accessKey,secretKey:Buffer.from(e.secretKey,"hex").toString("base64"),creationDate:Math.floor(Date.now()/1e3)});return t.headers.set("Signature",a),t.headers.set("Signature-Input",u),t.headers.set("X-Timestamp",n.headers["X-Timestamp"]),t.headers.set("Content-Type",n.headers["Content-Type"]),t.headers.set("Digest",n.headers.Digest),t.headers.set("Content-Digest",n.headers["Content-Digest"]),t}}}var m=class extends Error{statusCode;code;constructor(t,i,r){super(t),this.statusCode=i,this.code=r,this.name="SubnotoError"}};function Xe(e){return{async onRequest({request:t}){if(!t.url.includes("/tunnel/")&&!t.url.includes("/public/")||t.url.includes("/tunnel/session"))return t;try{await e.ensureSession();let i=t.clone(),r=Buffer.from(await i.arrayBuffer());if(!r||r.byteLength===0)throw new m("EMPTY_REQUEST_BODY");let s=e.encryptRequest(r);if(!s||s.byteLength===0)throw new m("Empty encrypted message");let o=e.getSessionId();if(!o)throw new m("Session ID not available");let d=new Headers(i.headers);d.set("X-Session-Id",o),d.set("Content-Type","application/octet-stream"),d.set("Content-Length",s.byteLength.toString());let n=await e.getCookies(i.url);return n&&d.set("Cookie",n),new Request(i.url,{method:i.method,headers:d,body:s,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,integrity:i.integrity,keepalive:i.keepalive})}catch(i){throw console.error(`Error in tunnel middleware for ${t.url}:`,i),i}},async onResponse({response:t,request:i}){if(!i.url.includes("/tunnel/")&&!i.url.includes("/public/")||i.url.includes("/tunnel/session"))return t;try{if(!(t.headers.get("x-subnoto-encrypted-response")?.includes("true")&&t.headers.get("content-type")?.includes("application/octet-stream")))return t;let s=t.clone(),o=Buffer.from(await s.arrayBuffer());if(o.byteLength===0)throw new m("Empty encrypted response");let d=e.decryptResponse(o),n=new Headers(t.headers);return n.get("x-subnoto-content-type-response")?.includes("application/octet-stream")?(n.set("Content-Type","application/octet-stream"),n.delete("x-subnoto-encrypted-response"),new Response(d,{status:t.status,statusText:t.statusText,headers:n})):(n.set("Content-Type","application/json"),n.delete("x-subnoto-encrypted-response"),n.delete("x-subnoto-content-type-response"),new Response(d,{status:t.status,statusText:t.statusText,headers:n}))}catch(r){throw console.error(`Error decrypting response for ${i.url}:`,r),r}}}}import{fileURLToPath as Mt}from"url";import{dirname as vt,join as Nt}from"path";var kt=Mt(import.meta.url),Kt=vt(kt),Fe=Nt(Kt,"oak_session_wasm_nodejs_bg.wasm");var ce={};de(ce,{PutIncomingMessageResult:()=>Bt,WasmClientSession:()=>H,__wbg_buffer_609cc3eee51ed158:()=>_t,__wbg_call_672a4d21634d4a24:()=>Xt,__wbg_call_7cccdd69e0791ae2:()=>Ft,__wbg_crypto_574e78ad8b13b65f:()=>Ht,__wbg_getRandomValues_b8f5dbd5f3995a9e:()=>Gt,__wbg_msCrypto_a61aeb35a24c1329:()=>Wt,__wbg_new_a12002a7f91c75be:()=>Ut,__wbg_newnoargs_105ed471475aaf50:()=>qt,__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a:()=>Vt,__wbg_newwithlength_a381634e90c276d4:()=>Lt,__wbg_node_905d3e251edff8a2:()=>zt,__wbg_now_807e54c39636c349:()=>jt,__wbg_process_dc0fbacc7c1c06f7:()=>$t,__wbg_randomFillSync_ac0988aba3254290:()=>Qt,__wbg_require_60cc747a6bc5215a:()=>Zt,__wbg_set_65595bdd868b3009:()=>Jt,__wbg_set_wasm:()=>xt,__wbg_static_accessor_GLOBAL_88a902d13a557d07:()=>Yt,__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0:()=>e1,__wbg_static_accessor_SELF_37c5d418e4bf5819:()=>t1,__wbg_static_accessor_WINDOW_5de37043a91a9c40:()=>i1,__wbg_subarray_aa9065fa9dc5df96:()=>r1,__wbg_versions_c01dfd4722a88165:()=>s1,__wbindgen_init_externref_table:()=>n1,__wbindgen_is_function:()=>c1,__wbindgen_is_object:()=>o1,__wbindgen_is_string:()=>a1,__wbindgen_is_undefined:()=>d1,__wbindgen_memory:()=>l1,__wbindgen_string_new:()=>u1,__wbindgen_throw:()=>p1});import{TextDecoder as Rt}from"util";var h,Ot;function xt(e,t){h=e,Ot=t}function G(e){let t=h.__externref_table_alloc();return h.__wbindgen_export_2.set(t,e),t}function W(e,t){try{return e.apply(this,t)}catch(i){let r=G(i);h.__wbindgen_exn_store(r)}}var Ge=new Rt("utf-8",{ignoreBOM:!0,fatal:!0});Ge.decode();var Z=null;function ne(){return(Z===null||Z.byteLength===0)&&(Z=new Uint8Array(h.memory.buffer)),Z}function F(e,t){return e=e>>>0,Ge.decode(ne().subarray(e,e+t))}function x(e){return e==null}var M=0;function O(e,t){let i=t(e.length*1,1)>>>0;return ne().set(e,i/1),M=e.length,i}function w(e){let t=h.__wbindgen_export_2.get(e);return h.__externref_table_dealloc(e),t}function X(e,t){return e=e>>>0,ne().subarray(e/1,e/1+t)}var Bt=Object.freeze({NoIncomingMessageExpected:0,0:"NoIncomingMessageExpected",Success:1,1:"Success"}),He=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>h.__wbg_wasmclientsession_free(e>>>0,1)),H=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,He.unregister(this),t}free(){let t=this.__destroy_into_raw();h.__wbg_wasmclientsession_free(t,0)}constructor(t,i){var r=x(i)?0:O(i,h.__wbindgen_malloc),s=M;let o=h.wasmclientsession_new(x(t)?16777215:t?1:0,r,s);if(o[2])throw w(o[1]);return this.__wbg_ptr=o[0]>>>0,He.register(this,this.__wbg_ptr,this),this}is_open(){return h.wasmclientsession_is_open(this.__wbg_ptr)!==0}write(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_write(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}read(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_read(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}write_buffer(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_write_buffer(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}read_buffer(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_read_buffer(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}put_incoming_message(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_put_incoming_message(this.__wbg_ptr,i,r);if(s[2])throw w(s[1]);return s[0]}get_outgoing_message(){let t=h.wasmclientsession_get_outgoing_message(this.__wbg_ptr);if(t[3])throw w(t[2]);let i;return t[0]!==0&&(i=X(t[0],t[1]).slice(),h.__wbindgen_free(t[0],t[1]*1,1)),i}get_attestation_results_json(){let t=h.wasmclientsession_get_attestation_results_json(this.__wbg_ptr);if(t[3])throw w(t[2]);let i;return t[0]!==0&&(i=F(t[0],t[1]).slice(),h.__wbindgen_free(t[0],t[1]*1,1)),i}get_attestation_status(){let t,i;try{let r=h.wasmclientsession_get_attestation_status(this.__wbg_ptr);return t=r[0],i=r[1],F(r[0],r[1])}finally{h.__wbindgen_free(t,i,1)}}};function _t(e){return e.buffer}function Xt(){return W(function(e,t){return e.call(t)},arguments)}function Ft(){return W(function(e,t,i){return e.call(t,i)},arguments)}function Ht(e){return e.crypto}function Gt(){return W(function(e,t){e.getRandomValues(t)},arguments)}function Wt(e){return e.msCrypto}function Ut(e){return new Uint8Array(e)}function qt(e,t){return new Function(F(e,t))}function Vt(e,t,i){return new Uint8Array(e,t>>>0,i>>>0)}function Lt(e){return new Uint8Array(e>>>0)}function zt(e){return e.node}function jt(){return Date.now()}function $t(e){return e.process}function Qt(){return W(function(e,t){e.randomFillSync(t)},arguments)}function Zt(){return W(function(){return module.require},arguments)}function Jt(e,t,i){e.set(t,i>>>0)}function Yt(){let e=typeof global>"u"?null:global;return x(e)?0:G(e)}function e1(){let e=typeof globalThis>"u"?null:globalThis;return x(e)?0:G(e)}function t1(){let e=typeof self>"u"?null:self;return x(e)?0:G(e)}function i1(){let e=typeof window>"u"?null:window;return x(e)?0:G(e)}function r1(e,t,i){return e.subarray(t>>>0,i>>>0)}function s1(e){return e.versions}function n1(){let e=h.__wbindgen_export_2,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}function c1(e){return typeof e=="function"}function o1(e){let t=e;return typeof t=="object"&&t!==null}function a1(e){return typeof e=="string"}function d1(e){return e===void 0}function l1(){return h.memory}function u1(e,t){return F(e,t)}function p1(e,t){throw new Error(F(e,t))}import*as Ue from"node:path";import*as qe from"node:fs";import*as Ve from"node:process";var oe={};oe["./oak_session_wasm_nodejs_bg.js"]=ce;var We=Ue.dirname(new URL(import.meta.url).pathname);Ve.platform==="win32"&&(We=We.substring(1));var h1=qe.readFileSync(Fe),Le=new WebAssembly.Module(h1),S1=new WebAssembly.Instance(Le,oe),ze=S1.exports;oe["./oak_session_wasm_nodejs_bg.js"].__wbg_set_wasm(ze,Le);ze.__wbindgen_start();import{CookieJar as f1}from"tough-cookie";var J=class{session=null;sessionId=null;config;handshakeInProgress=!1;cookieJar;constructor(t){this.config=t,this.cookieJar=new f1}async ensureSession(){if(!(this.session&&this.session.is_open())){if(this.handshakeInProgress){for(;this.handshakeInProgress;)await new Promise(t=>setTimeout(t,50));return}await this.handshake()}}async handshake(){this.handshakeInProgress=!0;try{let t=this.config.unattested??!1;this.session=new H(t,t?void 0:this.config.attesterKey);let i=4,r=0;if(!this.session)throw new m("Failed to create session");for(;!this.session.is_open()&&r<i;){r++;let s=this.session.get_outgoing_message();if(!s||this.session.is_open())break;let o=`${this.config.apiBaseUrl}/tunnel/session`,d={"Content-Type":"application/octet-stream"};this.sessionId&&(d["X-Session-Id"]=this.sessionId);let n=await this.cookieJar.getCookieString(o);n&&(d.Cookie=n);let a=await fetch(o,{method:"POST",body:s,headers:d});if(!this.sessionId){let c=a.headers.get("X-Session-Id");if(!c)throw new m("No session ID received from server");this.sessionId=c}if(!a.ok){let c=await a.text().catch(()=>"Unable to read error");throw new m(`Handshake failed with status ${a.status}: ${c}`,a.status)}let u=a.headers.getSetCookie?.()||[];for(let c of u)await this.cookieJar.setCookie(c,o);let S=await a.arrayBuffer();if(S.byteLength>0)this.session.put_incoming_message(Buffer.from(S));else throw new m("Empty response from server during handshake")}if(!this.session.is_open()||!this.sessionId)throw new m("Failed to establish session after handshake")}finally{this.handshakeInProgress=!1}}encryptRequest(t){if(!this.session||!this.session.is_open())throw new m("Session not open");try{let i=typeof t=="string"?Buffer.from(t,"utf-8"):t,r=this.session.write(i);return Buffer.from(r)}catch(i){throw new m(`Encryption failed: ${i instanceof Error?i.message:"Unknown error"}`)}}decryptResponse(t){if(!this.session||!this.session.is_open())throw new m("Session not open");try{let i=Buffer.isBuffer(t)?t:Buffer.from(t),r=this.session.read(i);return Buffer.from(r)}catch(i){throw new m(`Decryption failed: ${i instanceof Error?i.message:"Unknown error"}`)}}getSessionId(){return this.sessionId}getCookies(t){return this.cookieJar.getCookieString(t)}destroy(){this.session=null,this.sessionId=null}getAttestationResults(){return this.session?this.session.get_attestation_results_json()??null:null}getAttestationStatus(){return this.session?this.session.get_attestation_status()??null:null}};function je(e){let t=m1({baseUrl:e.apiBaseUrl}),i=new J(e);return t.use(Xe(i)),t.use(_e({accessKey:e.accessKey,secretKey:e.secretKey})),{client:t,sessionManager:i}}import{createCipheriv as g1,randomBytes as C1}from"crypto";async function $e(e,t){let{workspaceUuid:i,fileBuffer:r,envelopeTitle:s}=t,o=await e.POST("/public/envelope/create",{body:{workspaceUuid:i,envelopeTitle:s}});if(o.error)throw new m(`Failed to create envelope: ${JSON.stringify(o.error)}`,o.response?.status,typeof o.error=="object"&&"code"in o.error?String(o.error.code):void 0);let{envelopeUuid:d,documentUuid:n,presignedS3Params:a,revisionEncryptionKey:u}=o.data;if(!a)throw new m("Missing presigned S3 parameters in response");let S=Buffer.from(u,"base64");if(S.length!==32)throw new m("Encryption key must be 32 bytes (256-bit)");let c=C1(12),p=g1("aes-256-gcm",S,c),f=JSON.stringify({documentUuid:n});p.setAAD(Buffer.from(f));let y=Buffer.concat([p.update(r),p.final()]),v=p.getAuthTag(),I=Buffer.concat([c,y,v]),b=new FormData;Object.entries(a.fields).forEach(([A,E])=>{b.append(A,E)}),b.append("file",new Blob([I]),"document.pdf");let l=await fetch(a.url,{method:"POST",body:b});if(!l.ok)throw new m(`S3 upload failed: ${l.status} ${l.statusText}`,l.status);let g=await e.POST("/public/envelope/complete-document-upload",{body:{workspaceUuid:i,envelopeUuid:d,documentUuid:n}});if(g.error)throw new m(`Failed to confirm upload: ${JSON.stringify(g.error)}`,g.response?.status,typeof g.error=="object"&&"code"in g.error?String(g.error.code):void 0);return{envelopeUuid:d,documentUuid:n}}var ae=class{client;sessionManager;constructor(t){let{client:i,sessionManager:r}=je(t);this.client=i,this.sessionManager=r}get GET(){return this.client.GET}get POST(){return this.client.POST}get PUT(){return this.client.PUT}get DELETE(){return this.client.DELETE}get PATCH(){return this.client.PATCH}uploadDocument(t){return $e(this,t)}getAttestationStatus(){let t=this.sessionManager.getAttestationStatus();return t?JSON.parse(t):null}getAttestationResults(){let t=this.sessionManager.getAttestationResults();return t?JSON.parse(t):null}};export{ae as SubnotoClient,m as SubnotoError};
4
+ `)}};function Te(e){let t=ie(e),i=new Map;for(let[r,s]of t){if(!Array.isArray(s))throw new Error("item is not array");let[o,d]=s;i.set(r,[o.map(n=>typeof n=="string"?[n,new Map]:[n[0],fe(n[1])]),fe(d)])}return C.serializeDictionary(i)}var F1=V(z(),1);async function Pe(e,t,i=lt){let r=await(await ct()).subtle.sign(ut(e.algorithm,i.hash),e,ye.encode(t));return be(r)}var G1=V(z(),1);function we(e){let t=e.toUpperCase();if(t==="SHA-256")return"sha-256";if(t==="SHA-512")return"sha-512";throw new Error(`Unsupported hash algorithm: ${e}`)}var q1=V(z(),1);async function j(){return globalThis.crypto??(await import("node:crypto")).webcrypto}var De=e=>{let t=new Uint8Array(e);return P.stringify(t)};var ft=async(e,t="SHA-256")=>(t==="SHA"&&(t="SHA-1"),typeof e=="string"&&(e=new TextEncoder().encode(e)),(await j()).subtle.digest(t,e)),Me=async e=>{let t="SHA-256",i=await ft(e.body,t).then(De),r=`${t}=${i}`,s=`${we(t)}=:${i}:`;return{digest:r,contentDigest:s}};var mt=/^[\x20-\x7E]*$/,gt=/^[a-zA-Z*][:/!#$%&'*+\-.^_`|~A-Za-z0-9]*$/,Ct=/^[a-z*][*\-_.a-z0-9]*$/;function re(e){return mt.test(e)}function ve(e){return gt.test(e)}function Ne(e){return Ct.test(e)}function ke(e){return Array.isArray(e[0])}function Ke(e){let t=new Uint8Array(e),i="";for(let r of t)i+=String.fromCharCode(r);return btoa(i)}function se(e){let t=atob(e),i=t.length,r=new Uint8Array(i);for(let s=0;s<i;s++)r[s]=t.charCodeAt(s);return r.buffer}var K=class{constructor(t){if(!ve(t))throw new TypeError("Invalid character in Token string. Tokens must start with *, A-Z and the rest of the string may only contain a-z, A-Z, 0-9, :/!#$%&'*+-.^_`|~");this.value=t}toString(){return this.value}};var R=class{constructor(t){this.value=t}toString(){return this.value}};var D=class extends Error{};function Re(e){let t=e instanceof Map?e.entries():Object.entries(e);return Array.from(t).map(([i,r])=>{let s=xe(i);return Array.isArray(r)?r[0]===!0?s+Q(r[1]):ke(r)?s+"="+yt(r):s+"="+Oe(r):r===!0?s:s+"="+$(r)}).join(", ")}function Oe(e,t){return Array.isArray(e)?$(e[0])+Q(e[1]):$(e)+(t?Q(t):"")}function yt(e){return`(${e[0].map(t=>Oe(t)).join(" ")})${Q(e[1])}`}function $(e){if(typeof e=="number")return Number.isInteger(e)?It(e):At(e);if(typeof e=="string")return bt(e);if(e instanceof K)return wt(e);if(e instanceof ArrayBuffer)return Pt(e);if(e instanceof R)return Et(e);if(e instanceof Date)return Dt(e);if(typeof e=="boolean")return Tt(e);throw new D(`Cannot serialize values of type ${typeof e}`)}function It(e){if(e<-999999999999999||e>999999999999999)throw new D("Structured headers can only encode integers in the range range of -999,999,999,999,999 to 999,999,999,999,999 inclusive");return e.toString()}function At(e){let t=e.toFixed(3).replace(/0+$/,"");if(t.split(".")[0].replace("-","").length>12)throw new D("Fractional numbers are not allowed to have more than 12 significant digits before the decimal point");return t}function bt(e){if(!re(e))throw new D("Only ASCII strings may be serialized");return`"${e.replace(/("|\\)/g,t=>"\\"+t)}"`}function Et(e){let t='%"',i=new TextEncoder;for(let r of i.encode(e.toString()))r===37||r===34||r<=31||r>=127?t+="%"+r.toString(16):t+=String.fromCharCode(r);return t+'"'}function Tt(e){return e?"?1":"?0"}function Pt(e){return`:${Ke(e)}:`}function wt(e){return e.toString()}function Dt(e){return"@"+Math.floor(e.getTime()/1e3)}function Q(e){return Array.from(e).map(([t,i])=>{let r=";"+xe(t);return i!==!0&&(r+="="+$(i)),r}).join("")}function xe(e){if(!Ne(e))throw new D("Keys in dictionaries must only contain lowercase letter, numbers, _-*. and must start with a letter or *");return e}var Be=async e=>{let{request:t,authenticationType:i,accessKey:r,secretKey:s,creationDate:o}=e,d={key_ops:["sign","verify"],ext:!0,kty:"oct",k:s,alg:"HS256"},n=await(await j()).subtle.importKey("jwk",d,{name:"HMAC",hash:"SHA-256"},!0,["sign","verify"]),a=new Map,u=new Map;a.set(i,n),u.set(i,[["x-timestamp","@authority","content-type","content-digest","content-length"],{keyid:r,created:o,alg:"hmac-sha256"}]);let S=Te(u);Ie(t,"Signature-Input",S);let c=new Ee(t),p=(c.isRequest()?c.requestSignatureInput:c.responseSignatureInput)?.keys();if(!p)throw new Error("signaturesEntries is undefined");let f=new Map,y=new Map;for(let I of p){let b=c.generate(I),l=a.get(I);if(!l)throw new Error(`key not found: ${I}`);y.set(I,b),f.set(I,[se(await Pe(l,b,{hash:"SHA-256",ec:"DSA"})),new Map])}let v=Re(f);return{signatureInputHeader:S,signatureHeader:v}};function _e(e){return{async onRequest({request:t}){let i=t.clone(),r=i.url,s=await i.arrayBuffer()??JSON.stringify({}),o=i.method??"POST",d=await _.generateDigestHeaders({body:s}),n={headers:{"X-Timestamp":Date.now().toString(),Host:new URL(r).host,"Content-Type":i.headers.get("Content-Type")??"application/json","Content-Length":i.headers.get("Content-Length")??s.byteLength.toString(),Digest:d.digest,"Content-Digest":d.contentDigest},body:s.toString(),method:o,url:r},{signatureHeader:a,signatureInputHeader:u}=await _.generateSignatureHeader({request:n,authenticationType:"team",accessKey:e.accessKey,secretKey:Buffer.from(e.secretKey,"hex").toString("base64"),creationDate:Math.floor(Date.now()/1e3)});return t.headers.set("Signature",a),t.headers.set("Signature-Input",u),t.headers.set("X-Timestamp",n.headers["X-Timestamp"]),t.headers.set("Content-Type",n.headers["Content-Type"]),t.headers.set("Digest",n.headers.Digest),t.headers.set("Content-Digest",n.headers["Content-Digest"]),t}}}var m=class extends Error{statusCode;code;constructor(t,i,r){super(t),this.statusCode=i,this.code=r,this.name="SubnotoError"}};function Xe(e){return{async onRequest({request:t}){if(!t.url.includes("/tunnel/")&&!t.url.includes("/public/")||t.url.includes("/tunnel/session"))return t;try{await e.ensureSession();let i=t.clone(),r=Buffer.from(await i.arrayBuffer());if(!r||r.byteLength===0)throw new m("EMPTY_REQUEST_BODY");let s=e.encryptRequest(r);if(!s||s.byteLength===0)throw new m("Empty encrypted message");let o=e.getSessionId();if(!o)throw new m("Session ID not available");let d=new Headers(i.headers);d.set("X-Session-Id",o);let n=i.headers.get("Content-Type");n&&n.includes("multipart/form-data")&&d.set("X-Original-Content-Type",n),d.set("Content-Type","application/octet-stream"),d.set("Content-Length",s.byteLength.toString());let a=await e.getCookies(i.url);return a&&d.set("Cookie",a),new Request(i.url,{method:i.method,headers:d,body:s,mode:i.mode,credentials:i.credentials,cache:i.cache,redirect:i.redirect,referrer:i.referrer,referrerPolicy:i.referrerPolicy,integrity:i.integrity,keepalive:i.keepalive})}catch(i){throw console.error(`Error in tunnel middleware for ${t.url}:`,i),i}},async onResponse({response:t,request:i}){if(!i.url.includes("/tunnel/")&&!i.url.includes("/public/")||i.url.includes("/tunnel/session"))return t;try{if(!(t.headers.get("x-subnoto-encrypted-response")?.includes("true")&&t.headers.get("content-type")?.includes("application/octet-stream")))return t;let s=t.clone(),o=Buffer.from(await s.arrayBuffer());if(o.byteLength===0)throw new m("Empty encrypted response");let d=e.decryptResponse(o),n=new Headers(t.headers);return n.get("x-subnoto-content-type-response")?.includes("application/octet-stream")?(n.set("Content-Type","application/octet-stream"),n.delete("x-subnoto-encrypted-response"),new Response(d,{status:t.status,statusText:t.statusText,headers:n})):(n.set("Content-Type","application/json"),n.delete("x-subnoto-encrypted-response"),n.delete("x-subnoto-content-type-response"),new Response(d,{status:t.status,statusText:t.statusText,headers:n}))}catch(r){throw console.error(`Error decrypting response for ${i.url}:`,r),r}}}}import{fileURLToPath as Mt}from"url";import{dirname as vt,join as Nt}from"path";var kt=Mt(import.meta.url),Kt=vt(kt),Fe=Nt(Kt,"oak_session_wasm_nodejs_bg.wasm");var ce={};de(ce,{PutIncomingMessageResult:()=>Bt,WasmClientSession:()=>H,__wbg_buffer_609cc3eee51ed158:()=>_t,__wbg_call_672a4d21634d4a24:()=>Xt,__wbg_call_7cccdd69e0791ae2:()=>Ft,__wbg_crypto_574e78ad8b13b65f:()=>Ht,__wbg_getRandomValues_b8f5dbd5f3995a9e:()=>Gt,__wbg_msCrypto_a61aeb35a24c1329:()=>Wt,__wbg_new_a12002a7f91c75be:()=>Ut,__wbg_newnoargs_105ed471475aaf50:()=>qt,__wbg_newwithbyteoffsetandlength_d97e637ebe145a9a:()=>Vt,__wbg_newwithlength_a381634e90c276d4:()=>Lt,__wbg_node_905d3e251edff8a2:()=>zt,__wbg_now_807e54c39636c349:()=>jt,__wbg_process_dc0fbacc7c1c06f7:()=>$t,__wbg_randomFillSync_ac0988aba3254290:()=>Qt,__wbg_require_60cc747a6bc5215a:()=>Zt,__wbg_set_65595bdd868b3009:()=>Jt,__wbg_set_wasm:()=>xt,__wbg_static_accessor_GLOBAL_88a902d13a557d07:()=>Yt,__wbg_static_accessor_GLOBAL_THIS_56578be7e9f832b0:()=>e1,__wbg_static_accessor_SELF_37c5d418e4bf5819:()=>t1,__wbg_static_accessor_WINDOW_5de37043a91a9c40:()=>i1,__wbg_subarray_aa9065fa9dc5df96:()=>r1,__wbg_versions_c01dfd4722a88165:()=>s1,__wbindgen_init_externref_table:()=>n1,__wbindgen_is_function:()=>c1,__wbindgen_is_object:()=>o1,__wbindgen_is_string:()=>a1,__wbindgen_is_undefined:()=>d1,__wbindgen_memory:()=>l1,__wbindgen_string_new:()=>u1,__wbindgen_throw:()=>p1});import{TextDecoder as Rt}from"util";var h,Ot;function xt(e,t){h=e,Ot=t}function G(e){let t=h.__externref_table_alloc();return h.__wbindgen_export_2.set(t,e),t}function W(e,t){try{return e.apply(this,t)}catch(i){let r=G(i);h.__wbindgen_exn_store(r)}}var Ge=new Rt("utf-8",{ignoreBOM:!0,fatal:!0});Ge.decode();var Z=null;function ne(){return(Z===null||Z.byteLength===0)&&(Z=new Uint8Array(h.memory.buffer)),Z}function F(e,t){return e=e>>>0,Ge.decode(ne().subarray(e,e+t))}function x(e){return e==null}var M=0;function O(e,t){let i=t(e.length*1,1)>>>0;return ne().set(e,i/1),M=e.length,i}function w(e){let t=h.__wbindgen_export_2.get(e);return h.__externref_table_dealloc(e),t}function X(e,t){return e=e>>>0,ne().subarray(e/1,e/1+t)}var Bt=Object.freeze({NoIncomingMessageExpected:0,0:"NoIncomingMessageExpected",Success:1,1:"Success"}),He=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>h.__wbg_wasmclientsession_free(e>>>0,1)),H=class{__destroy_into_raw(){let t=this.__wbg_ptr;return this.__wbg_ptr=0,He.unregister(this),t}free(){let t=this.__destroy_into_raw();h.__wbg_wasmclientsession_free(t,0)}constructor(t,i){var r=x(i)?0:O(i,h.__wbindgen_malloc),s=M;let o=h.wasmclientsession_new(x(t)?16777215:t?1:0,r,s);if(o[2])throw w(o[1]);return this.__wbg_ptr=o[0]>>>0,He.register(this,this.__wbg_ptr,this),this}is_open(){return h.wasmclientsession_is_open(this.__wbg_ptr)!==0}write(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_write(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}read(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_read(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}write_buffer(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_write_buffer(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}read_buffer(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_read_buffer(this.__wbg_ptr,i,r);if(s[3])throw w(s[2]);var o=X(s[0],s[1]).slice();return h.__wbindgen_free(s[0],s[1]*1,1),o}put_incoming_message(t){let i=O(t,h.__wbindgen_malloc),r=M,s=h.wasmclientsession_put_incoming_message(this.__wbg_ptr,i,r);if(s[2])throw w(s[1]);return s[0]}get_outgoing_message(){let t=h.wasmclientsession_get_outgoing_message(this.__wbg_ptr);if(t[3])throw w(t[2]);let i;return t[0]!==0&&(i=X(t[0],t[1]).slice(),h.__wbindgen_free(t[0],t[1]*1,1)),i}get_attestation_results_json(){let t=h.wasmclientsession_get_attestation_results_json(this.__wbg_ptr);if(t[3])throw w(t[2]);let i;return t[0]!==0&&(i=F(t[0],t[1]).slice(),h.__wbindgen_free(t[0],t[1]*1,1)),i}get_attestation_status(){let t,i;try{let r=h.wasmclientsession_get_attestation_status(this.__wbg_ptr);return t=r[0],i=r[1],F(r[0],r[1])}finally{h.__wbindgen_free(t,i,1)}}};function _t(e){return e.buffer}function Xt(){return W(function(e,t){return e.call(t)},arguments)}function Ft(){return W(function(e,t,i){return e.call(t,i)},arguments)}function Ht(e){return e.crypto}function Gt(){return W(function(e,t){e.getRandomValues(t)},arguments)}function Wt(e){return e.msCrypto}function Ut(e){return new Uint8Array(e)}function qt(e,t){return new Function(F(e,t))}function Vt(e,t,i){return new Uint8Array(e,t>>>0,i>>>0)}function Lt(e){return new Uint8Array(e>>>0)}function zt(e){return e.node}function jt(){return Date.now()}function $t(e){return e.process}function Qt(){return W(function(e,t){e.randomFillSync(t)},arguments)}function Zt(){return W(function(){return module.require},arguments)}function Jt(e,t,i){e.set(t,i>>>0)}function Yt(){let e=typeof global>"u"?null:global;return x(e)?0:G(e)}function e1(){let e=typeof globalThis>"u"?null:globalThis;return x(e)?0:G(e)}function t1(){let e=typeof self>"u"?null:self;return x(e)?0:G(e)}function i1(){let e=typeof window>"u"?null:window;return x(e)?0:G(e)}function r1(e,t,i){return e.subarray(t>>>0,i>>>0)}function s1(e){return e.versions}function n1(){let e=h.__wbindgen_export_2,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}function c1(e){return typeof e=="function"}function o1(e){let t=e;return typeof t=="object"&&t!==null}function a1(e){return typeof e=="string"}function d1(e){return e===void 0}function l1(){return h.memory}function u1(e,t){return F(e,t)}function p1(e,t){throw new Error(F(e,t))}import*as Ue from"node:path";import*as qe from"node:fs";import*as Ve from"node:process";var oe={};oe["./oak_session_wasm_nodejs_bg.js"]=ce;var We=Ue.dirname(new URL(import.meta.url).pathname);Ve.platform==="win32"&&(We=We.substring(1));var h1=qe.readFileSync(Fe),Le=new WebAssembly.Module(h1),S1=new WebAssembly.Instance(Le,oe),ze=S1.exports;oe["./oak_session_wasm_nodejs_bg.js"].__wbg_set_wasm(ze,Le);ze.__wbindgen_start();import{CookieJar as f1}from"tough-cookie";var J=class{session=null;sessionId=null;config;handshakeInProgress=!1;cookieJar;constructor(t){this.config=t,this.cookieJar=new f1}async ensureSession(){if(!(this.session&&this.session.is_open())){if(this.handshakeInProgress){for(;this.handshakeInProgress;)await new Promise(t=>setTimeout(t,50));return}await this.handshake()}}async handshake(){this.handshakeInProgress=!0;try{let t=this.config.unattested??!1;this.session=new H(t,t?void 0:this.config.attesterKey);let i=4,r=0;if(!this.session)throw new m("Failed to create session");for(;!this.session.is_open()&&r<i;){r++;let s=this.session.get_outgoing_message();if(!s||this.session.is_open())break;let o=`${this.config.apiBaseUrl}/tunnel/session`,d={"Content-Type":"application/octet-stream"};this.sessionId&&(d["X-Session-Id"]=this.sessionId);let n=await this.cookieJar.getCookieString(o);n&&(d.Cookie=n);let a=await fetch(o,{method:"POST",body:s,headers:d});if(!this.sessionId){let c=a.headers.get("X-Session-Id");if(!c)throw new m("No session ID received from server");this.sessionId=c}if(!a.ok){let c=await a.text().catch(()=>"Unable to read error");throw new m(`Handshake failed with status ${a.status}: ${c}`,a.status)}let u=a.headers.getSetCookie?.()||[];for(let c of u)await this.cookieJar.setCookie(c,o);let S=await a.arrayBuffer();if(S.byteLength>0)this.session.put_incoming_message(Buffer.from(S));else throw new m("Empty response from server during handshake")}if(!this.session.is_open()||!this.sessionId)throw new m("Failed to establish session after handshake")}finally{this.handshakeInProgress=!1}}encryptRequest(t){if(!this.session||!this.session.is_open())throw new m("Session not open");try{let i=typeof t=="string"?Buffer.from(t,"utf-8"):t,r=this.session.write(i);return Buffer.from(r)}catch(i){throw new m(`Encryption failed: ${i instanceof Error?i.message:"Unknown error"}`)}}decryptResponse(t){if(!this.session||!this.session.is_open())throw new m("Session not open");try{let i=Buffer.isBuffer(t)?t:Buffer.from(t),r=this.session.read(i);return Buffer.from(r)}catch(i){throw new m(`Decryption failed: ${i instanceof Error?i.message:"Unknown error"}`)}}getSessionId(){return this.sessionId}getCookies(t){return this.cookieJar.getCookieString(t)}destroy(){this.session=null,this.sessionId=null}getAttestationResults(){return this.session?this.session.get_attestation_results_json()??null:null}getAttestationStatus(){return this.session?this.session.get_attestation_status()??null:null}};function je(e){let t=m1({baseUrl:e.apiBaseUrl}),i=new J(e);return t.use(Xe(i)),t.use(_e({accessKey:e.accessKey,secretKey:e.secretKey})),{client:t,sessionManager:i}}import{createCipheriv as g1,randomBytes as C1}from"crypto";async function $e(e,t){let{workspaceUuid:i,fileBuffer:r,envelopeTitle:s}=t,o=await e.POST("/public/envelope/create",{body:{workspaceUuid:i,envelopeTitle:s}});if(o.error)throw new m(`Failed to create envelope: ${JSON.stringify(o.error)}`,o.response?.status,typeof o.error=="object"&&"code"in o.error?String(o.error.code):void 0);let{envelopeUuid:d,documentUuid:n,presignedS3Params:a,revisionEncryptionKey:u}=o.data;if(!a)throw new m("Missing presigned S3 parameters in response");let S=Buffer.from(u,"base64");if(S.length!==32)throw new m("Encryption key must be 32 bytes (256-bit)");let c=C1(12),p=g1("aes-256-gcm",S,c),f=JSON.stringify({documentUuid:n});p.setAAD(Buffer.from(f));let y=Buffer.concat([p.update(r),p.final()]),v=p.getAuthTag(),I=Buffer.concat([c,y,v]),b=new FormData;Object.entries(a.fields).forEach(([A,E])=>{b.append(A,E)}),b.append("file",new Blob([I]),"document.pdf");let l=await fetch(a.url,{method:"POST",body:b});if(!l.ok)throw new m(`S3 upload failed: ${l.status} ${l.statusText}`,l.status);let g=await e.POST("/public/envelope/complete-document-upload",{body:{workspaceUuid:i,envelopeUuid:d,documentUuid:n}});if(g.error)throw new m(`Failed to confirm upload: ${JSON.stringify(g.error)}`,g.response?.status,typeof g.error=="object"&&"code"in g.error?String(g.error.code):void 0);return{envelopeUuid:d,documentUuid:n}}var ae=class{client;sessionManager;constructor(t){let{client:i,sessionManager:r}=je(t);this.client=i,this.sessionManager=r}get GET(){return this.client.GET}get POST(){return this.client.POST}get PUT(){return this.client.PUT}get DELETE(){return this.client.DELETE}get PATCH(){return this.client.PATCH}uploadDocument(t){return $e(this,t)}getAttestationStatus(){let t=this.sessionManager.getAttestationStatus();return t?JSON.parse(t):null}getAttestationResults(){let t=this.sessionManager.getAttestationResults();return t?JSON.parse(t):null}};export{ae as SubnotoClient,m as SubnotoError};
Binary file
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@subnoto/api-client",
3
3
  "private": false,
4
- "version": "2.0.7",
4
+ "version": "2.1.1",
5
5
  "description": "TypeScript SDK for Subnoto Public API",
6
6
  "author": "Subnoto",
7
7
  "homepage": "https://subnoto.com",
@@ -1079,7 +1079,7 @@ export interface paths {
1079
1079
  envelopeUuid: string;
1080
1080
  /** @description The title of the document attachment. */
1081
1081
  documentTitle: string;
1082
- /** @description The file to attach (PDF or Word document, max 11MB). */
1082
+ /** @description The file to attach (PDF or Word document, max 50MB). */
1083
1083
  file: unknown;
1084
1084
  };
1085
1085
  };