@decaf-ts/for-fabric 0.1.64 → 0.1.66

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.
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,i,a,n,s,o,c,l,d,u,h,p,g,f,y,m,w){"use strict";function b(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function C(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var E=b(o),A=b(u),v=C(h),S=C(g),_=b(f),I=b(y),M=b(m);class x extends t.Repository{constructor(e,t){super(e,t),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}async paginateBy(e,i,a={offset:1,limit:10},...n){const{log:s,ctxArgs:o}=(await this.logCtx(n,t.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return s.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${a.limit}`),this.statement(this.paginateBy.name,e,i,{limit:a.limit,offset:a.offset,bookmark:a.bookmark},...o)}async listBy(e,i,...a){const{log:n,ctxArgs:s}=(await this.logCtx(a,t.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return n.verbose(`listing ${r.Model.tableName(this.class)} by ${e} ${i}`),await this.statement(this.listBy.name,e,i,...s)}async findBy(e,i,...a){const{log:n,ctxArgs:s}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findBy.name,e,i,...s)}async findOneBy(e,i,...a){const{log:n,ctxArgs:s}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findOneBy.name,e,i,...s)}async statement(e,...i){const{log:n,ctx:s,ctxArgs:o}=(await this.logCtx(i,t.PersistenceKeys.STATEMENT,!0)).for(this.statement);n.verbose("Executing prepared statement "+e);const c=o.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(s,t.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[a.CouchDBKeys.TABLE]&&e[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(e):e):l[a.CouchDBKeys.TABLE]&&l[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(l):t.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async create(e,...t){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`);let{record:s,id:o,transient:c}=this.adapter.prepare(e,i);return s=await this.adapter.create(this.class,o,s,c,...n),this.adapter.revert(s,this.class,o,c,i)}async update(e,...t){const{ctxArgs:i,log:a,ctx:n}=this.logCtx(t,this.update);let{record:s,id:o,transient:c}=this.adapter.prepare(e,n);return a.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),s=await this.adapter.update(this.class,o,s,c,...i),this.adapter.revert(s,this.class,o,c,n)}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a}=(await this.logCtx(t,i.OperationKeys.CREATE,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),s=r.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),n||await i.enforceDBDecorators(this,r,e,i.OperationKeys.CREATE,i.OperationKeys.ON),e))),!s){const t=r.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=i.reduceErrorsToPrint(a);if(n)throw new i.ValidationError(n)}return[e,...a]}async createAll(e,...t){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:n}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const s=e.map(e=>this.adapter.prepare(e,i)),o=s.map(e=>e.id);let c=s.map(e=>e.record);const l=s.map(e=>e.transient);return c=await this.adapter.createAll(this.class,o,c,l,...n),c.map((e,t)=>this.adapter.revert(e,this.class,o[t],i.get("rebuildWithTransient")?s[t].transient:void 0,i))}async updateAll(e,...t){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const s=e.map(e=>this.adapter.prepare(e,i));return(await this.adapter.updateAll(this.class,s.map(e=>e.id),s.map(e=>e.record),s.map(e=>e.transient),...n)).map((e,t)=>this.adapter.revert(e,this.class,s[t].id,i.get("rebuildWithTransient")?s[t].transient:void 0,i))}}let O=class extends t.BaseModel{constructor(e){super(e)}};n.__decorate([t.pk({type:String}),n.__metadata("design:type",String)],O.prototype,"name",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",String)],O.prototype,"owner",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",String)],O.prototype,"symbol",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",Number)],O.prototype,"decimals",void 0),O=n.__decorate([t.table("erc20_tokens"),r.model(),n.__metadata("design:paramtypes",[Object])],O);let N=class extends t.BaseModel{constructor(e){super(e)}};n.__decorate([t.pk({type:String}),n.__metadata("design:type",String)],N.prototype,"id",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",String)],N.prototype,"token",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",Number)],N.prototype,"balance",void 0),n.__decorate([t.column(),n.__metadata("design:type",String)],N.prototype,"captive",void 0),N=n.__decorate([t.table("erc20_wallets"),r.model(),n.__metadata("design:paramtypes",[Object])],N);let T=class extends t.BaseModel{constructor(e){super(e)}};n.__decorate([t.pk({type:String}),t.column(),r.required(),n.__metadata("design:type",String)],T.prototype,"owner",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",String)],T.prototype,"spender",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",Number)],T.prototype,"value",void 0),T=n.__decorate([t.table("erc20_allowances"),r.model(),n.__metadata("design:paramtypes",[Object])],T);class F extends r.JSONSerializer{constructor(){super()}preSerialize(e,t){const a=Object.assign({},e);let n=s.Metadata.modelName(e.constructor);if(!n||"Object"===n){if(!t)throw new i.SerializationError("Could not find metadata for "+e.constructor.name);n=t}return a[r.ModelKeys.ANCHOR]=n,a}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class R extends x{static{this.serializer=new F}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,a,n,...s){if(!this.observerHandler)throw new i.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:c}=this.logCtx(s,this.updateObservers);let l;o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?r.Model.get(e):e,l=void 0===n?void 0:Array.isArray(n)?n.map(i=>t.Sequence.parseValue(r.Model.sequenceFor(e).type,i)):t.Sequence.parseValue(r.Model.sequenceFor(e).type,n),await this.observerHandler.updateObservers(e,a,l,...c)}decode(e){return R.decoder.decode(e)}constructor(e){super(e,N),this.serializer=R.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,r,i){const a=await t.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(a.args,this.transferFrom),s=await this.adapter.submitTransaction(n,"TransferFrom",[e,r,i.toString()]);return"true"===this.decode(s)}async approve(e,r){const i=await t.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.approve),n=await this.adapter.submitTransaction(a,"Approve",[e,r.toString()]);return"true"===this.decode(n)}async allowance(e,r){const i=await t.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.allowance),n=await this.adapter.submitTransaction(a,"Allowance",[e,r]);return Number(this.decode(n))}async initialize(e){const r=await t.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.initialize),a=await this.adapter.submitTransaction(i,"Initialize",[R.serializer.serialize(e)]);return"true"===this.decode(a)}async checkInitialized(){const e=await t.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(r,"CheckInitialized")}async mint(e){const r=await t.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.mint);await this.adapter.submitTransaction(i,"Mint",[e.toString()])}async burn(e){const r=await t.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burn);await this.adapter.submitTransaction(i,"Burn",[e.toString()])}async burnFrom(e,r){const i=await t.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.burnFrom);await this.adapter.submitTransaction(a,"BurnFrom",[e,r.toString()])}async clientAccountBalance(){const e=await t.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountBalance),i=await this.adapter.evaluateTransaction(r,"ClientAccountBalance");return Number(this.decode(i))}async clientAccountID(){const e=await t.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountID),i=await this.adapter.evaluateTransaction(r,"ClientAccountID");return this.decode(i)}}function B(e,t,r){return[...e.map(e=>e===a.CouchDBKeys.TABLE?"table":e),...r||[],...t?[t]:[],"index"].join(s.Metadata.splitter)}function K(e,t,r,i){const n=t.pop();n&&n!==a.CouchDBKeys.TABLE?t.push(n):n===a.CouchDBKeys.TABLE&&t.unshift(n);const s=B(t,r,i);let o=[...t,...i||[]];r&&(o=o.reduce((e,t)=>{const i={};return i[t]=r,e.push(i),e},[]));const c={index:{fields:o},name:s,ddoc:s,type:"json"};e[s]=c}function $(e){const t=require("path"),i=require(t.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof r.Model}catch(e){return!1}})}var P;e.IdentityCredentials=class extends t.BaseModel{constructor(e){super(e)}},n.__decorate([s.description("Unique identifier of the credentials record"),t.column(),t.pk(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),n.__decorate([s.description("PEM-encoded X.509 certificate for the identity"),t.column(),r.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),n.__decorate([s.description("PEM-encoded root or intermediate certificate"),t.column(),r.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),n.__decorate([s.description("PEM-encoded private key"),t.column(),r.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=n.__decorate([r.model(),n.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(P=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",P.SHARED="shared",P.FABRIC="fabric",P.OWNED_BY="owned-by",P.TRANSACTION_ID="transaction-id",P.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const k="hlf-fabric";e.Identity=class extends t.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},n.__decorate([s.description("Unique identifier of the identity"),t.pk(),n.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),n.__decorate([t.oneToOne(e.IdentityCredentials,{update:t.Cascade.CASCADE,delete:t.Cascade.CASCADE}),n.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),n.__decorate([t.column(),r.required(),t.index(),n.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),n.__decorate([t.column(),r.required(),n.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=n.__decorate([r.model(),n.__metadata("design:paramtypes",[Object])],e.Identity);class z{static{this.logger=new c.MiniLogger(z.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e)}static async getCAUser(e,t,i,a,n){this.logger.debug(r.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const s=new d.User(e),o=n?.hsm?{software:!1,lib:n.hsm.library,slot:n.hsm.slot,label:n.hsm.tokenLabel,pin:n.hsm.pin+""}:void 0,c=this.getCryptoSuite(o);s.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,i,n.hsm):this.getSoftwareEnrollmentKey(c,t);return await s.setEnrollment(l,i,a),s}static getCryptoSuite(e){return e?(z.cryptoSuite||(z.cryptoSuite=d.User.newCryptoSuite(e)),z.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return A.default.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,r){const i=await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)});return{mspId:e,credentials:i}}static async getFirstDirFileName(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}static async getFileContent(e){const{promises:r}=await t.normalizeImport(import("fs"));return(await r.readFile(e)).toString()}static async getSigner(e){const r=await this.contentOfLoadFile(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)}),i=await this.extractPrivateKey(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}static async extractPrivateKey(e){let r;if(globalThis.window&&globalThis.window.Crypto)r=globalThis.Crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),a=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));return await r.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const j=new p.Crypto;var L,H,U,q,Y;v.cryptoProvider.set(j),e.BASE_ALPHABET=void 0,(L=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",L.BASE8="01234567",L.BASE11="0123456789a",L.BASE16="0123456789abcdef",L.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",L.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",L.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",L.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",L.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",L.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(H=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",H[H.ITERATIONS=1e3]="ITERATIONS",H[H.KEYLENGTH=48]="KEYLENGTH",H[H.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",H[H.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",H.ALGORYTHM="AES-GCM",H.KEY_ALGORYTHM="PBKDF2";class G{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const n=(a-i)*this.iFactor+1>>>0,s=new Uint8Array(n);for(;i!==a;){let t=e[i],a=0;for(let e=n-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*s[e]>>>0,s[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let o=n-r;for(;o!==n&&0===s[o];)o++;let c=this.leader.repeat(t);for(;n>o;++o)c+=this.alphabet.charAt(s[o]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,n=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let s=0;for(let e=a-1;(0!==r||i>s)&&-1!==e;e--,s++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=s,t++}let s=a-i;for(;s!==a&&0===n[s];)s++;const o=new Uint8Array(r+(a-s));let c=r;for(;s!==a;)o[c++]=n[s++];return o}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class V{static{this.b58encoder=new G(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(V.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(r.stringFormat("Parsing certificate: {0}",e));const t=new v.X509Certificate(e),{subject:i,issuer:a}=t;return this.logger.debug(r.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=j.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(a,"base64").toString("binary"),s=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await j.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new v.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,j.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new v.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:j.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=j.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),n={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},s=await this.getSubtleCrypto().deriveBits(n,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(s)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}class J extends i.InternalError{constructor(e){super(e,J.name)}}class Q extends i.InternalError{constructor(e){super(e,Q.name)}}class X extends i.InternalError{constructor(e){super(e,X.name)}}class W extends t.AuthorizationError{constructor(e){super(e,W.name)}}class Z extends i.InternalError{constructor(e){super(e,Z.name,500)}}class ee extends i.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ee.name,e,403)}}class te extends i.BaseError{constructor(e){super(te.name,e,409)}}class re extends i.InternalError{constructor(e){super(e,re.name,500)}}class ie extends i.InternalError{constructor(e){super(e,ie.name,500)}}class ae extends i.InternalError{constructor(e){super(e,ae.name,500)}}class ne extends i.InternalError{constructor(e){super(e,ne.name,500)}}class se extends i.InternalError{constructor(e){super(e,se.name,500)}}e.HFCAIdentityType=void 0,(U=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",U.ORDERER="orderer",U.CLIENT="client",U.USER="user",U.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(q=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",q.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",q.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",q.HFINTERMEDIATECA="hf.IntermediateCA",q.HFREVOKER="hf.Revoker",q.HFAFFILIATIONMGR="hf.AffiliationMgr",q.HFGENCRL="hf.GenCRL";class oe extends c.LoggedClass{constructor(e){z.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:r,url:a,hsm:n}=this.caConfig,s=this.log.for(this.User);s.debug(`Creating CA user for ${e} at ${a}`),s.debug("Retrieving CA certificate from "+t);const o=await z.getFirstDirFileNameContent(t);let c;if(n)s.debug(`Using HSM configuration for CA ${e} with library ${n.library}`);else{if(!r)throw new i.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);s.debug("Retrieving CA key from "+r),c=await z.getFirstDirFileNameContent(r)}return s.debug("Loading Admin user for ca "+e),this.user=await z.getCAUser("admin",c,o,e,{hsm:n}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:n}=r;const s=a[0];e.debug(`Retrieving CA certificate from ${s}. cwd: ${process.cwd()}`);const o=await z.getFileContent(s);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new E.default(t,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),t?n.certs.map(e=>e.PEM):n}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new W(e);const[,a,n]=r;switch(a){case"74":case"71":return new i.ConflictError(n);case"20":return new t.AuthorizationError(n);default:return new W(n)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),r=await this.User();let a;try{a=await t.newIdentityService().getOne(e,r)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n){let s;const o=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};s=await d.register(h,u),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return s}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:n}=t,s=c.Logging.for(oe,{}).for(this.identityFromEnrollment);s.debug(`Generating Identity from certificate ${i} in msp ${r}`);const o=V.fabricIdFromCertificate(i),l=V.encode(o);s.debug(`Identity ${o} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:n,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const n=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=oe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,n){const s=await this.register(e,t,r,i,a,n),{userName:o}=e;return this.enroll(o,s)}async revoke(e){const t=await this.CA(),r=await this.User(),a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},r)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}class ce extends r.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new i.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}async function le(e,t,r,i){const{stub:a}=e,n=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}async function de(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function ue(e,t,a){let n=t;if("string"!=typeof n)try{const i=r.Model.ownerOf(e)||a.get("stub").getCreator().toString();t&&"function"==typeof t&&(n=await t(e,i,a))}catch(e){throw new i.InternalError("Failed to resolve collection mirror name: "+e)}if(!n||"string"!=typeof n)throw new i.InternalError("No collection found model "+e.constructor.name);return n}async function he(e,t,i,a){const n=await ue(a,t.resolver,e),s=this.override(Object.assign({},this._overrides,{segregate:n,ignoreValidation:!0,ignoreHandlers:!0})),o=await s.create(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} created with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}async function pe(e,t,i,a){const n=await ue(a,t.resolver,e),s=this.override(Object.assign({},this._overrides,{segregate:n,ignoreValidation:!0,ignoreHandlers:!0})),o=await s.update(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} updated with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}async function ge(e,t,i,a){const n=await ue(a,t.resolver,e),s=this.override(Object.assign({},this._overrides,{segregate:n,ignoreValidation:!0,ignoreHandlers:!0})),o=await s.delete(r.Model.pk(a),e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} deleted with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}n.__decorate([r.required(),n.__metadata("design:type",String)],ce.prototype,"affiliation",void 0),n.__decorate([r.minlength(1),n.__metadata("design:type",Array)],ce.prototype,"attrs",void 0),n.__decorate([r.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentID",void 0),n.__decorate([r.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentSecret",void 0),n.__decorate([r.min(0),n.__metadata("design:type",Number)],ce.prototype,"maxEnrollments",void 0),n.__decorate([r.required(),n.__metadata("design:type",String)],ce.prototype,"role",void 0),e.ERC20Events=void 0,(Y=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",Y.APPROVAL="Approval",e.FabricBaseModel=class extends r.Model{constructor(e){super(e)}},n.__decorate([s.description("Stores the original timestamp of creation"),t.column(),t.createdAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),n.__decorate([s.description("Stores the timestamp of the last update"),t.column(),t.updatedAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),n.__decorate([s.description("Stores the version of the model"),t.column(),i.version(),n.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=n.__decorate([s.uses(k),n.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},n.__decorate([s.description("Stores the creator"),t.column(),t.createdBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),n.__decorate([s.description("Stores the user that last updated the model"),t.column(),t.updatedBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=n.__decorate([s.uses(k),n.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),r.Model.prototype.isShared=function(){return r.Model.isShared(this.constructor)},r.Model.prototype.isPrivate=function(){return r.Model.isPrivate(this.constructor)},r.Model.prototype.segregate=function(){return r.Model.segregate(this)},r.Model.segregate=(t=>{if(!r.Model.isTransient(t))return{model:t};const a=s.Metadata.validatableProperties(t.constructor),n=s.Metadata.get(t.constructor,i.DBKeys.TRANSIENT),o=s.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),c=s.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),l={model:{},transient:{},private:{},shared:{}},d=Object.keys(n),u=Object.keys(o),h=Object.keys(c);for(const e of a){const r=d.includes(e),i=u.includes(e),a=h.includes(e);r?(l.transient=l.transient||{},l.transient[e]=t[e],i&&(l.private=l.private||{},l.private[e]=t[e]),a&&(l.shared=l.shared||{},l.shared[e]=t[e])):(l.model=l.model||{},l.model[e]=t[e])}return l.model=r.Model.build(l.model,t.constructor.name),l}).bind(r.Model),r.Model.isPrivate=(t=>!!s.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(r.Model),r.Model.isShared=(t=>!!s.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(r.Model),r.Model.mirrored=(t=>s.Metadata.get("function"!=typeof t?t.constructor:t,s.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(r.Model),r.Model.ownerOf=(t=>{const r=s.Metadata.get(t.constructor,s.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(r.Model),r.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,s.Metadata.get(t,s.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(r.Model),r.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=s.Metadata.key(...r),n=s.Metadata.key(...i),o="function"==typeof t?t:t.constructor,c=s.Metadata.get(o,a),l=s.Metadata.get(o,n);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(r.Model);const fe=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0);if(!a)throw new i.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};async function ye(e,a,n,s){if(n.length!==a.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(s);if(!o)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const c=a[0].collections,l="string"==typeof c?c:c(s,o,e),d=n.reduce((r,i,n)=>{const c="string"==typeof a[n].collections?a[n].collections:a[n].collections(s,o,e);if(c!==l)throw new t.UnsupportedError(`Segregated data collection mismatch: ${c} vs ${l}`);return r[i]=s[i],r},{}),u=new this.class(d),h=await this.override({segregated:l,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(u,e);Object.assign(s,h)}async function me(e,t,a,n){if(a.length!==t.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const s=r.Model.ownerOf(n);if(!s)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const o=t[0].collections,c="string"==typeof o?o:await o(n,s,e);a.reduce((r,i,a)=>(("string"==typeof t[a].collections?t[a].collections:t[a].collections(n,s,e))!==c||(r[i]=n[i]),r),{})}async function we(e,t,r,i,a){}async function be(e,t,r,i){}function Ce(e,t,r){return(a,n)=>{const o=[];return n?o.push(s.prop(),i.transient(),(r,i)=>{const a=s.Metadata.key(t,i),n=r.constructor,o=s.Metadata.get(n,a)||{},c=new Set(o.collections||[]);c.add(e),o.collections=[...c],s.Metadata.set(n,a,o);const l=s.Metadata.get(n,t)||{};new Set(l.collections||[]).add(e),o.collections=[...c],s.Metadata.set(n,t,o)},i.onCreate(ye,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onRead(me,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onUpdate(we,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onDelete(be,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()})):s.Metadata.properties(a)?.forEach(i=>{r&&!r(i)||Ce(e,t)(a.prototype,i)}),s.apply(...o)(a,n)}}function Ee(t=fe){return s.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>Ce(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply()}class Ae extends r.JSONSerializer{constructor(){super()}preSerialize(e){const t=Object.assign({},e);let i;try{i=s.Metadata.modelName(e.constructor)}catch(e){i=void 0}t[r.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return r.Model.relations(e).forEach(e=>{t[e]=a(t[e])}),t}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}function ve(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class Se extends r.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e,t)))}preSerialize(e,t=!0){const i=Object.assign({},e);let a;try{a=s.Metadata.modelName(e.constructor)}catch(e){a=void 0}function n(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(n):this.preSerialize(e)}return t&&(i[r.ModelKeys.ANCHOR]=a||e.constructor.name),r.Model.relations(e).forEach(e=>{i[e]=n.call(this,i[e])}),i}}class _e extends t.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new i.InternalError("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(e,t){const r=t.logger.for(this.getUser),{caName:a,caCert:n,caKey:s,url:o,hsm:c}=e;r.info(`Creating CA user for ${a} at ${o}`),r.verbose("Retrieving CA certificate from "+n);const l=await z.getFirstDirFileNameContent(n);let d;if(c)r.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!s)throw new i.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+s),d=await z.getFirstDirFileNameContent(s)}return r.debug("Loading Admin user for ca "+a),this._user=await z.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:r}=await this.logCtx(e,this.initialize,!0),[a]=e;if(!a)throw new i.InternalError("Missing Fabric CA configuration");const{url:n,tls:s,caName:o}=a;t.info(`Initializing CA Client for CA ${a.caName} at ${a.url}`);const{trustedRoots:c,verify:l}=s,d=c[0];t.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const u=await z.getFileContent(d);t.debug("CA Certificate: "+u.toString());const h=new E.default(n,{trustedRoots:Buffer.from(u),verify:l},o),p=await this.getUser(a,r);return t.debug("CA user loaded: "+p.getName()),{config:a,client:h}}async getCertificates(e,r=!0,...i){e instanceof t.Context?(i=[e],r=!0,e=void 0):"boolean"==typeof e?(r=e,e=void 0):"boolean"!=typeof r&&(i=[r,...i],r=!0);const{log:a}=await this.logCtx(i,this.getCertificates,!0);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const n=(await this.certificates.getCertificates(e||{},this.user)).result;return a.verbose(`Found ${n.certs.length} certificates`),a.debug(n.certs),r?n.certs.map(e=>e.PEM):n}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new W(e);const[,a,n]=r;switch(a){case"74":case"71":return new i.ConflictError(n);case"20":return new t.AuthorizationError(n);default:return new W(n)}}async read(e,...t){const{log:r}=await this.logCtx(t,this.read,!0);let a;r.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n,...s){const{log:o}=await this.logCtx(s,this.register,!0);let c;try{const{userName:s,password:l}=e,d={enrollmentID:s,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${s} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:n,key:s,rootCertificate:o}=t;a.verbose(`Generating Identity from certificate ${n} in msp ${r}`);const c=V.fabricIdFromCertificate(n),l=V.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:n,privateKey:s.toBytes(),rootCertificate:o},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=await this.logCtx(r,this.enroll,!0);let n;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});n=_e.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${n.id}`)}catch(e){throw this.parseError(e)}return n}async registerAndEnroll(e,t=!1,r="",i,a,n,...s){const{ctx:o}=await this.logCtx(s,this.registerAndEnroll,!0),c=await this.register(e,t,r,i,a,n,o),{userName:l}=e;return this.enroll(l,c,o)}async revoke(e,...t){const{log:r}=await this.logCtx(t,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+e);const a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await this.client.revoke({enrollmentID:a.id,reason:"User Deletion"},this.user)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}const Ie=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),Me=new c.MiniLogger("fabric-fs");async function xe(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Oe(e,r){const i=await xe(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)});return{mspId:e,credentials:i}}async function Ne(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}async function Te(e){const r=await xe(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)}),i=await Fe(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}async function Fe(e){let r;if(c.isBrowser())r=globalThis.crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const a=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),n=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(a,"base64").toString("binary"));try{return await r.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new i.InternalError(e)}}class Re{static#e=null;static#t=!1;constructor(e){if(Re.#e||(Re.#e=new _.default.PKCS11,Re.#e.load(this.findHSMPKCS11Lib(e))),!Re.#t){try{Re.#e.C_Initialize()}catch(e){if(e.code!==_.default.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw e}Re.#t=!0}}findHSMPKCS11Lib(e){const t=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];e&&t.push(e);for(const e of t)if(I.default.existsSync(e))return e;throw new re("Unable to find PKCS11 library")}dispose(){Re.#e.C_Finalize()}sanitizeOptions(e){const t=Object.assign({userType:_.default.CKU_USER},e);return this.assertNotEmpty(t.label,"label"),this.assertNotEmpty(t.pin,"pin"),this.assertNotEmpty(t.identifier,"identifier"),t}assertNotEmpty(e,t){if(!e||0===e.toString().trim().length)throw Error(t+" property must be provided")}findSlotForLabel(e){const t=Re.#e.C_GetSlotList(!0);if(0===t.length)throw Error("No pkcs11 slots can be found");const r=t.find(t=>Re.#e.C_GetTokenInfo(t).label.trim()===e);if(!r)throw Error(`label ${e} cannot be found in the pkcs11 slot list`);return r}login(e,t,r){try{Re.#e.C_Login(e,t,r)}catch(e){if(e.code!==_.default.CKR_USER_ALREADY_LOGGED_IN)throw e}}findObjectInHSM(e,t,r){const i=[{type:_.default.CKA_ID,value:r},{type:_.default.CKA_CLASS,value:t},{type:_.default.CKA_KEY_TYPE,value:_.default.CKK_EC}];Re.#e.C_FindObjectsInit(e,i);const a=Re.#e.C_FindObjects(e,1)[0];if(!a)throw Re.#e.C_FindObjectsFinal(e),Error("Unable to find object in HSM with ID "+r.toString());return Re.#e.C_FindObjectsFinal(e),a}newSigner(e){const t=this.sanitizeOptions(e),r=Re.#e,i=this.findSlotForLabel(t.label),a=r.C_OpenSession(i,_.default.CKF_SERIAL_SESSION);let n;try{this.login(a,t.userType,t.pin),n=this.findObjectInHSM(a,_.default.CKO_PRIVATE_KEY,t.identifier)}catch(e){throw Re.#e.C_CloseSession(a),e}return{signer:async e=>{Re.#e.C_SignInit(a,{mechanism:_.default.CKM_ECDSA},n);const t=await Re.#e.C_SignAsync(a,Buffer.from(e),Buffer.alloc(2*w.p256.Point.Fn.BYTES));return w.p256.Signature.fromBytes(t,"compact").normalizeS().toBytes("der")},close:()=>{Re.#e.C_CloseSession(a)}}}assertDefined(e){if(void 0===e)throw Error("required value was undefined");return e}getUncompressedPointOnCurve(e){const t=e.export({format:"jwk"}),r=Buffer.from(this.assertDefined(t.x),"base64url"),i=Buffer.from(this.assertDefined(t.y),"base64url"),a=Buffer.from("04","hex");return Buffer.concat([a,r,i])}getSKIFromCertificatePath(e){const t=e.endsWith(".pem")?e:M.default.join(e,"cert.pem"),r=I.default.readFileSync(t);return this.getSKIFromCertificate(r)}getSKIFromCertificate(e){const t=new A.default.X509Certificate(e),r=this.getUncompressedPointOnCurve(t.publicKey);return A.default.createHash("sha256").update(r).digest()}}class Be extends t.Statement{constructor(e,t){super(e,t)}squash(e){const r=super.squash(e);if(!r)return r;const{method:a,params:n,args:s}=r,{direction:o,limit:c}=n;switch(a){case t.PreparedStatementKeys.FIND_BY:break;case t.PreparedStatementKeys.LIST_BY:s.push(o);break;case t.PreparedStatementKeys.PAGE_BY:s.push(o,c);break;case t.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new i.InternalError("Unsupported method "+a)}return r}async executePrepared(...e){const r=t.Repository.forModel(this.fromSelector,this.adapter.alias),{method:i,args:a}=this.prepared;return r.statement(i,...a,...e)}async prepare(e){if(e=e||await this.adapter.context(t.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const r=[],i={},a={class:this.fromSelector,args:r,params:i},n=[t.QueryClause.FIND_BY];if(this.whereCondition){const t=this.prepareCondition(this.whereCondition,e);n.push(t.method),t.args&&t.args.length&&r.push(...t.args)}return this.selectSelector&&n.push(t.QueryClause.SELECT,this.selectSelector.join(` ${t.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(t.QueryClause.ORDER_BY,this.orderBySelector[0]),r.push(this.orderBySelector[1])),a.method=c.toCamelCase(n.join(" ")),a.params=i,this.prepared=a,this}build(){throw new t.UnsupportedError("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(e,...r){throw new t.UnsupportedError("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class De extends t.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new t.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}}var Ke;class $e extends t.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new F}static{this.log=c.Logging.for($e)}constructor(e,t){super(e,k,t),this.serializer=$e.serializer}Statement(e){return new Be(this,e)}Paginator(e,t,r){return new De(this,e,t,r)}async flags(e,t,r,...i){return Object.assign(await super.flags(e,t,Object.assign({},Ie,r),...i))}decode(e){return $e.decoder.decode(e)}repository(){return x}createPrefix(e,t,i,...n){const{ctxArgs:s}=this.logCtx(n,this.createPrefix),o=r.Model.tableName(e),c={};return c[a.CouchDBKeys.TABLE]=o,Object.assign(c,i),[e,t,c,...s]}createAllPrefix(e,t,n,...s){const o=r.Model.tableName(e);if(t.length!==n.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(s,this.createAllPrefix),l=t.map((e,t)=>{const r={};return r[a.CouchDBKeys.TABLE]=o,Object.assign(r,n[t]),r});return[e,t,l,...c]}updateAllPrefix(e,t,n,...s){const o=r.Model.tableName(e);if(t.length!==n.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(s,this.updateAllPrefix),l=t.map(()=>{const e={};return e[a.CouchDBKeys.TABLE]=o,e});return[e,t,l,...c]}async createAll(e,t,a,...n){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const s=[...n],o=s.shift(),{log:c,ctx:l}=this.logCtx(s,this.createAll),d=r.Model.tableName(e);c.info(`adding ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,e.name);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async readAll(e,t,...a){const{log:n,ctx:s}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);n.info(`reading ${t.length} entries to ${o} table`),n.verbose("pks: "+t);const c=await this.evaluateTransaction(s,i.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async updateAll(e,t,a,...n){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const s=[...n],o=s.shift(),{log:c,ctx:l}=this.logCtx(s,this.updateAll),d=r.Model.tableName(e);c.info(`updating ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,e.name);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async deleteAll(e,t,...a){const{log:n,ctx:s}=this.logCtx(a,this.deleteAll),o=r.Model.tableName(e);n.info(`deleting ${t.length} entries to ${o} table`),n.verbose("pks: "+t);const c=await this.submitTransaction(s,i.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}prepare(e,...i){const{log:a}=this.logCtx(i,this.prepare),n=r.Model.segregate(e);return e[t.PersistenceKeys.METADATA]&&(a.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(n.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]})),{record:n.model,model:n.model,id:e[r.Model.pk(e.constructor)],transient:n.transient,private:n.private,shared:n.shared}}revert(e,t,r,a,...n){const{log:s}=this.logCtx(n,this.revert);return a&&(s.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([r,a])=>{if(r in e)throw new i.InternalError(`Transient property ${r} already exists on model ${"string"==typeof t?t:t.name}. should be impossible`);e[r]=a})),new t(e)}async create(e,t,a,n={},...s){const o=[...s],{log:c,ctx:l}=this.logCtx(o,this.create),d=r.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+t);const u=await this.submitTransaction(l,i.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],n,void 0,e.name);return this.serializer.deserialize(this.decode(u))}async read(e,t,...a){const{log:n,ctx:s}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);n.verbose(`reading entry from ${o} table`),n.debug("pk: "+t);const c=await this.evaluateTransaction(s,i.OperationKeys.READ,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,t,i,...n){const s=r.Model.tableName(e),{ctxArgs:o}=this.logCtx(n,this.updatePrefix),c={};return c[a.CouchDBKeys.TABLE]=s,Object.assign(c,i),[e,t,c,...o]}async update(e,t,a,n={},...s){const o=[...s],{log:c,ctx:l}=this.logCtx(o,this.updateAll);c.info("CLIENT UPDATE class : "+typeof e);const d=r.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+t);const u=await this.submitTransaction(l,i.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],n,void 0,e.name);return this.serializer.deserialize(this.decode(u))}async delete(e,t,...a){const{log:n,ctx:s}=this.logCtx(a,this.delete),o=r.Model.tableName(e);n.verbose(`deleting entry from ${o} table`),n.debug("pk: "+t);const c=await this.submitTransaction(s,i.OperationKeys.DELETE,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}async raw(e,t=!0,a,...n){const{log:s,ctx:o}=this.logCtx(n,this.raw),c=a.name;let l,d;s.info("Performing raw statement on table "+r.Model.tableName(a));try{l=await this.evaluateTransaction(o,"raw",[JSON.stringify(e),t],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new i.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return r.Model.isModel(e)?d.map(e=>r.Model.build(e)):d}return u=d,r.Model.isModel(u)?r.Model.build(u):u;var u}getClient(){return this._client||(this._client=$e.getClient(this.config)),this._client}async Gateway(e){return $e.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return $e.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a,n,s){const o=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(s));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(s)||this.config.contractName}.${t}`),o.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:a};return await l.call(c,t,d)}catch(e){if(10===e.code)throw Error(""+e.details[0].message);throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(e){return $e.parseError(e)}async submitTransaction(e,t,r,i,a,n){return this.transaction(e,t,!0,r,i,a,n)}async evaluateTransaction(e,t,r,i,a,n){return this.transaction(e,t,!1,r,i,a,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(e,t,r){const i=this.log.for(this.getContract),a=this.getNetwork(e,t.channel);let n;try{i.debug(`Retrieving chaincode ${t.chaincodeName} contract ${r||t.contractName} from network ${t.channel}`),r=r||t.contractName,n=a.getContract(t.chaincodeName,r)}catch(e){throw this.parseError(e)}return n}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let r=e.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(I.default.readFileSync(r,"utf8"))}catch(e){throw new i.InternalError(`Failed to read the tls certificate from ${r}: ${e}`)}const a=S.credentials.createSsl(r);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new g.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,t,r){const i=c.Logging.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const a=await Oe(t.mspId,t.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+t.keyCertOrDirectoryPath);let n,s=()=>{};if(t.hsm){const e=new Re(t.hsm.library),r=e.getSKIFromCertificatePath(t.certCertOrDirectoryPath),i=e.newSigner({label:t.hsm.tokenLabel,pin:t.hsm.pin+"",identifier:r});n=i.signer,s=i.close}else n=await Te(t.keyCertOrDirectoryPath);const o={client:e,identity:a,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+t.mspId);const d=l.connect(o);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r),s()}})),d}Dispatch(){return new $e._baseDispatch}static parseError(e){const r="string"==typeof e?e:e.message;return r.includes("MVCC_READ_CONFLICT")?new ae(e):r.includes("ENDORSEMENT_POLICY_FAILURE")?new se(e):r.includes("PHANTOM_READ_CONFLICT")?new ne(e):e instanceof Error&&e.code&&9===e.code?new ie(e):r.includes(i.NotFoundError.name)?new i.NotFoundError(e):r.includes(i.ConflictError.name)?new i.ConflictError(e):r.includes(i.BadRequestError.name)?new i.BadRequestError(e):r.includes(t.QueryError.name)?new t.QueryError(e):r.includes(t.PagingError.name)?new t.PagingError(e):r.includes(t.UnsupportedError.name)?new t.UnsupportedError(e):r.includes(t.MigrationError.name)?new t.MigrationError(e):r.includes(t.ObserverError.name)?new t.ObserverError(e):r.includes(t.AuthorizationError.name)?new t.AuthorizationError(e):r.includes(t.ForbiddenError.name)?new t.ForbiddenError(e):r.includes(t.ConnectionError.name)?new t.ConnectionError(e):r.includes(i.SerializationError.name)?new i.SerializationError(e):new i.InternalError(e)}}n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),n.__metadata("design:returntype",Promise)],$e.prototype,"create",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,t.Context]),n.__metadata("design:returntype",Promise)],$e.prototype,"read",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),n.__metadata("design:returntype",Promise)],$e.prototype,"update",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,t.Context]),n.__metadata("design:returntype",Promise)],$e.prototype,"delete",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,"function"==typeof(Ke="undefined"!=typeof D&&D)?Ke:Object,Object,t.Context]),n.__metadata("design:returntype",Promise)],$e.prototype,"raw",null),$e.decoration(),t.Adapter.setCurrent(k);class Pe extends t.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof $e))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,a,n,...s){const{log:o,ctxArgs:c}=t.Adapter.logCtx(this.updateObservers,a,!1,...s);if(this.adapter)try{await this.adapter.refresh(e,a,n,...c)}catch(e){throw new i.InternalError("Failed to refresh dispatch: "+e)}else o.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:r.Model.tableName(e)}:${a}`)}async handleEvents(e){if(!this.listeningStack)throw new i.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new i.InternalError("No adapter found. should be impossible");const t=e||await this.adapter.context(i.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||r.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:i,event:n,owner:s}=ve(e.eventName);if(s&&s!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(i?r.Model.get(i):r.Model.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(e,n,o.id,t)}catch(e){a.error(`Failed update observables for table ${i} event ${n} id: ${o.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close()}}async initialize(){if(!this.adapter)throw new i.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},r.Model),{ctx:t}=this.logCtx([e],this.initialize),a=(await $e.getGateway(t,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new i.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(t)}}$e&&($e._baseDispatch=Pe);const ke="##VERSION##",ze="##PACKAGE##";s.Metadata.registerLibrary(ze,ke),e.AllowanceError=X,e.BalanceError=Q,e.BaseEncoder=G,e.ClientSerializer=F,e.CoreUtils=z,e.CryptoUtils=V,e.DefaultFabricClientFlags=Ie,e.DeterministicSerializer=Ae,e.EndorsementError=ie,e.EndorsementPolicyError=se,e.FabricClientAdapter=$e,e.FabricClientDispatch=Pe,e.FabricClientRepository=x,e.FabricERC20ClientRepository=R,e.FabricEnrollmentService=oe,e.FabricFlavour=k,e.FabricIdentityService=_e,e.ImplicitPrivateCollection=fe,e.MissingContextError=Z,e.MissingPKCSS11Lib=re,e.ModelCollection=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!a)throw new i.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(n.name)}${t?c.toPascalCase(t):""}`},e.MvccReadConflictError=ae,e.NotInitializedError=te,e.OverflowError=J,e.Owner=function(){return function(e,r,a){const n=a.value;return a.value=async function(...e){const a=e[0],s=a.clientIdentity.getID(),o=await this.tokenRepository.select(),c=await o.execute(a);if(0==c.length)throw new i.NotFoundError("No tokens avaialble");if(c.length>1)throw new i.NotFoundError("To many token available : "+c.length);if(c[0].owner!=s)throw new t.AuthorizationError(`User not authorized to run ${r} on the token`);return await n.apply(this,e)},a}},e.PACKAGE_NAME=ze,e.PhantomReadConflictError=ne,e.RegistrationError=W,e.RegistrationRequestBuilder=ce,e.SimpleDeterministicSerializer=Se,e.UnauthorizedPrivateDataAccess=ee,e.VERSION=ke,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new J(`Addition overflow: ${e} + ${t}`);return r},e.contentOfLoadFile=xe,e.createMirrorHandler=he,e.deleteMirrorHandler=ge,e.evalMirrorMetadata=ue,e.extractPrivateKey=Fe,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelIndexes=(e,t)=>{const i=B([a.CouchDBKeys.TABLE]),n=t||{};n[i]={index:{fields:[a.CouchDBKeys.TABLE]},name:i,ddoc:i,type:"json"};const s={},o=r.Model.indexes(e);for(const e of Object.keys(o))for(const[,t]of Object.entries(o[e])){const r=t.directions,i=t.compositions,n=[e,a.CouchDBKeys.TABLE];K(s,n),i&&i.length&&K(s,n,void 0,i),r&&r.length&&r.forEach(e=>{K(s,n,e),i&&i.length&&K(s,n,e,i)})}return Object.entries(s).forEach(([e,t])=>{n[e]=t}),Object.values(s)},e.getCAUser=async(e,t,r,i)=>{Me.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),n=d.User.newCryptoSuite();a.setCryptoSuite(n);const s=n.createKeyFromRaw(t);return await a.setEnrollment(s,r,i),a},e.getFirstDirFileName=Ne,e.getFirstDirFileNameContent=async e=>{const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()},e.getIdentity=Oe,e.getSigner=Te,e.mirror=(t,r)=>s.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(r,a)=>{const n={condition:a,resolver:r};return s.apply(s.metadata(s.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),n),Ee(t),i.afterCreate(he,n,{priority:95}),i.afterUpdate(pe,n,{priority:95}),i.afterDelete(ge,n,{priority:95}))},args:[t,r]}).apply(),e.ownedBy=()=>s.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(t,a)=>s.apply(r.required(),i.readonly(),i.onCreate(le),s.propMetadata(s.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(t,a),args:[]}).apply(),e.ownedByOnCreate=le,e.parseEventName=ve,e.privateData=Ee,e.readFile=async e=>"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e),e.readModelFile=$,e.readModelFolders=async(...e)=>{const t=require("fs"),r=[];for(const i of e){const e=t.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const t of e)r.push(...$(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string contains digits"));const t=parseInt(e);if(isNaN(t))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return t},e.segregatedDataOnCreate=ye,e.segregatedDataOnDelete=be,e.segregatedDataOnRead=me,e.segregatedDataOnUpdate=we,e.sharedData=t=>s.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>Ce(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new J(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>s.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(t,a)=>s.apply(r.required(),i.readonly(),i.onCreate(de),i.onUpdate(de),s.propMetadata(s.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(t,a),args:[]}).apply(),e.transactionIdOnCreate=de,e.updateMirrorHandler=pe,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");function n(e){const t=a.dirname(e);if(i.existsSync(t))return!0;n(t),i.mkdirSync(t)}e.forEach(e=>{const s=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));n(s),i.writeFileSync(s,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/core"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("pkcs11js"),require("fs"),require("path"),require("@noble/curves/nist")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/core","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","pkcs11js","fs","path","@noble/curves/nist"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsCore,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.pkcs11js,e.fs,e.path,e.nist);
1
+ var e,t;e=this,t=function(e,t,r,i,a,s,n,o,c,l,d,u,h,p,g,f,y,m,w){"use strict";function b(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function C(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var E=b(o),A=b(u),v=C(h),S=C(g),_=b(f),I=b(y),M=b(m);class x extends t.Repository{constructor(e,t){super(e,t),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}async paginateBy(e,i,a={offset:1,limit:10},...s){const{log:n,ctxArgs:o}=(await this.logCtx(s,t.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${r.Model.tableName(this.class)} with page size ${a.limit}`),this.statement(this.paginateBy.name,e,i,{limit:a.limit,offset:a.offset,bookmark:a.bookmark},...o)}async listBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${r.Model.tableName(this.class)} by ${e} ${i}`),await this.statement(this.listBy.name,e,i,...n)}async findBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findBy.name,e,i,...n)}async findOneBy(e,i,...a){const{log:s,ctxArgs:n}=(await this.logCtx(a,t.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${r.Model.tableName(this.class)} with ${e} ${i}`),await this.statement(this.findOneBy.name,e,i,...n)}async statement(e,...i){const{log:s,ctx:n,ctxArgs:o}=(await this.logCtx(i,t.PersistenceKeys.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+e);const c=o.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,t.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[a.CouchDBKeys.TABLE]&&e[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(e):e):l[a.CouchDBKeys.TABLE]&&l[a.CouchDBKeys.TABLE]===r.Model.tableName(this.class)?new this.class(l):t.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async create(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${r.Model.tableName(this.class)}`);let{record:n,id:o,transient:c}=this.adapter.prepare(e,i);return n=await this.adapter.create(this.class,o,n,c,...s),this.adapter.revert(n,this.class,o,c,i)}async update(e,...t){const{ctxArgs:i,log:a,ctx:s}=this.logCtx(t,this.update);let{record:n,id:o,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${r.Model.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,c,...i),this.adapter.revert(n,this.class,o,c,s)}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:a}=(await this.logCtx(t,i.OperationKeys.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),s||await i.enforceDBDecorators(this,r,e,i.OperationKeys.CREATE,i.OperationKeys.ON),e))),!n){const t=r.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),s=i.reduceErrorsToPrint(a);if(s)throw new i.ValidationError(s)}return[e,...a]}async createAll(e,...t){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,i)),o=n.map(e=>e.id);let c=n.map(e=>e.record);const l=n.map(e=>e.transient);return c=await this.adapter.createAll(this.class,o,c,l,...s),c.map((e,t)=>this.adapter.revert(e,this.class,o[t],i.get("rebuildWithTransient")?n[t].transient:void 0,i))}async updateAll(e,...t){const{ctx:i,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${r.Model.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,i));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),n.map(e=>e.transient),...s)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,i.get("rebuildWithTransient")?n[t].transient:void 0,i))}}let O=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],O.prototype,"name",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],O.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],O.prototype,"symbol",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],O.prototype,"decimals",void 0),O=s.__decorate([t.table("erc20_tokens"),r.model(),s.__metadata("design:paramtypes",[Object])],O);let N=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),s.__metadata("design:type",String)],N.prototype,"id",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],N.prototype,"token",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],N.prototype,"balance",void 0),s.__decorate([t.column(),s.__metadata("design:type",String)],N.prototype,"captive",void 0),N=s.__decorate([t.table("erc20_wallets"),r.model(),s.__metadata("design:paramtypes",[Object])],N);let T=class extends t.BaseModel{constructor(e){super(e)}};s.__decorate([t.pk({type:String}),t.column(),r.required(),s.__metadata("design:type",String)],T.prototype,"owner",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],T.prototype,"spender",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",Number)],T.prototype,"value",void 0),T=s.__decorate([t.table("erc20_allowances"),r.model(),s.__metadata("design:paramtypes",[Object])],T);class F extends r.JSONSerializer{constructor(){super()}preSerialize(e,t){const a=Object.assign({},e);let s=n.Metadata.modelName(e.constructor);if(!s||"Object"===s){if(!t)throw new i.SerializationError("Could not find metadata for "+e.constructor.name);s=t}return a[r.ModelKeys.ANCHOR]=s,a}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class R extends x{static{this.serializer=new F}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,a,s,...n){if(!this.observerHandler)throw new i.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:c}=this.logCtx(n,this.updateObservers);let l;o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?r.Model.get(e):e,l=void 0===s?void 0:Array.isArray(s)?s.map(i=>t.Sequence.parseValue(r.Model.sequenceFor(e).type,i)):t.Sequence.parseValue(r.Model.sequenceFor(e).type,s),await this.observerHandler.updateObservers(e,a,l,...c)}decode(e){return R.decoder.decode(e)}constructor(e){super(e,N),this.serializer=R.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,r,i){const a=await t.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(a.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[e,r,i.toString()]);return"true"===this.decode(n)}async approve(e,r){const i=await t.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.approve),s=await this.adapter.submitTransaction(a,"Approve",[e,r.toString()]);return"true"===this.decode(s)}async allowance(e,r){const i=await t.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.allowance),s=await this.adapter.submitTransaction(a,"Allowance",[e,r]);return Number(this.decode(s))}async initialize(e){const r=await t.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.initialize),a=await this.adapter.submitTransaction(i,"Initialize",[R.serializer.serialize(e)]);return"true"===this.decode(a)}async checkInitialized(){const e=await t.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(r,"CheckInitialized")}async mint(e){const r=await t.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.mint);await this.adapter.submitTransaction(i,"Mint",[e.toString()])}async burn(e){const r=await t.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burn);await this.adapter.submitTransaction(i,"Burn",[e.toString()])}async burnFrom(e,r){const i=await t.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(i.args,this.burnFrom);await this.adapter.submitTransaction(a,"BurnFrom",[e,r.toString()])}async clientAccountBalance(){const e=await t.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountBalance),i=await this.adapter.evaluateTransaction(r,"ClientAccountBalance");return Number(this.decode(i))}async clientAccountID(){const e=await t.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.clientAccountID),i=await this.adapter.evaluateTransaction(r,"ClientAccountID");return this.decode(i)}}function B(e,t,r){return[...e.map(e=>e===a.CouchDBKeys.TABLE?"table":e),...r||[],...t?[t]:[],"index"].join(n.Metadata.splitter)}function K(e,t,r,i){const s=t.pop();s&&s!==a.CouchDBKeys.TABLE?t.push(s):s===a.CouchDBKeys.TABLE&&t.unshift(s);const n=B(t,r,i);let o=[...t,...i||[]];r&&(o=o.reduce((e,t)=>{const i={};return i[t]=r,e.push(i),e},[]));const c={index:{fields:o},name:n,ddoc:n,type:"json"};e[n]=c}function $(e){const t=require("path"),i=require(t.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof r.Model}catch(e){return!1}})}var P;e.IdentityCredentials=class extends t.BaseModel{constructor(e){super(e)}},s.__decorate([n.description("Unique identifier of the credentials record"),t.column(),t.pk(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),s.__decorate([n.description("PEM-encoded X.509 certificate for the identity"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),s.__decorate([n.description("PEM-encoded root or intermediate certificate"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),s.__decorate([n.description("PEM-encoded private key"),t.column(),r.required(),s.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(P=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",P.SHARED="shared",P.FABRIC="fabric",P.OWNED_BY="owned-by",P.TRANSACTION_ID="transaction-id",P.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const k="hlf-fabric";e.Identity=class extends t.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},s.__decorate([n.description("Unique identifier of the identity"),t.pk(),s.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),s.__decorate([t.oneToOne(e.IdentityCredentials,{update:t.Cascade.CASCADE,delete:t.Cascade.CASCADE}),s.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),s.__decorate([t.column(),r.required(),t.index(),s.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),s.__decorate([t.column(),r.required(),s.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=s.__decorate([r.model(),s.__metadata("design:paramtypes",[Object])],e.Identity);class z{static{this.logger=new c.MiniLogger(z.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e)}static async getCAUser(e,t,i,a,s){this.logger.debug(r.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const n=new d.User(e),o=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,c=this.getCryptoSuite(o);n.setCryptoSuite(c);const l=s?.hsm?await this.getHSMEnrollmentKey(c,i,s.hsm):this.getSoftwareEnrollmentKey(c,t);return await n.setEnrollment(l,i,a),n}static getCryptoSuite(e){return e?(z.cryptoSuite||(z.cryptoSuite=d.User.newCryptoSuite(e)),z.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return A.default.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,r){const i=await this.contentOfLoadFile(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)});return{mspId:e,credentials:i}}static async getFirstDirFileName(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()}static async getFileContent(e){const{promises:r}=await t.normalizeImport(import("fs"));return(await r.readFile(e)).toString()}static async getSigner(e){const r=await this.contentOfLoadFile(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await this.getFirstDirFileName(e);return await r.readFile(i)}),i=await this.extractPrivateKey(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}static async extractPrivateKey(e){let r;if(globalThis.window&&globalThis.window.Crypto)r=globalThis.Crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),a=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));return await r.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const j=new p.Crypto;var L,H,U,q,Y;v.cryptoProvider.set(j),e.BASE_ALPHABET=void 0,(L=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",L.BASE8="01234567",L.BASE11="0123456789a",L.BASE16="0123456789abcdef",L.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",L.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",L.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",L.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",L.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",L.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(H=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",H[H.ITERATIONS=1e3]="ITERATIONS",H[H.KEYLENGTH=48]="KEYLENGTH",H[H.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",H[H.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",H.ALGORYTHM="AES-GCM",H.KEY_ALGORYTHM="PBKDF2";class G{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const s=(a-i)*this.iFactor+1>>>0,n=new Uint8Array(s);for(;i!==a;){let t=e[i],a=0;for(let e=s-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*n[e]>>>0,n[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let o=s-r;for(;o!==s&&0===n[o];)o++;let c=this.leader.repeat(t);for(;s>o;++o)c+=this.alphabet.charAt(n[o]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,s=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let n=0;for(let e=a-1;(0!==r||i>n)&&-1!==e;e--,n++)r+=this.base*s[e]>>>0,s[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=n,t++}let n=a-i;for(;n!==a&&0===s[n];)n++;const o=new Uint8Array(r+(a-n));let c=r;for(;n!==a;)o[c++]=s[n++];return o}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class V{static{this.b58encoder=new G(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(V.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(r.stringFormat("Parsing certificate: {0}",e));const t=new v.X509Certificate(e),{subject:i,issuer:a}=t;return this.logger.debug(r.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=j.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),s=Buffer.from(a,"base64").toString("binary"),n=this.stringToArrayBuffer(s);return await i.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await j.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new v.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,j.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new v.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:j.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=j.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),s={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(n)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}class J extends i.InternalError{constructor(e){super(e,J.name)}}class Q extends i.InternalError{constructor(e){super(e,Q.name)}}class X extends i.InternalError{constructor(e){super(e,X.name)}}class W extends t.AuthorizationError{constructor(e){super(e,W.name)}}class Z extends i.InternalError{constructor(e){super(e,Z.name,500)}}class ee extends i.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ee.name,e,403)}}class te extends i.BaseError{constructor(e){super(te.name,e,409)}}class re extends i.InternalError{constructor(e){super(e,re.name,500)}}class ie extends i.InternalError{constructor(e){super(e,ie.name,500)}}class ae extends i.InternalError{constructor(e){super(e,ae.name,500)}}class se extends i.InternalError{constructor(e){super(e,se.name,500)}}class ne extends i.InternalError{constructor(e){super(e,ne.name,500)}}e.HFCAIdentityType=void 0,(U=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",U.ORDERER="orderer",U.CLIENT="client",U.USER="user",U.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(q=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",q.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",q.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",q.HFINTERMEDIATECA="hf.IntermediateCA",q.HFREVOKER="hf.Revoker",q.HFAFFILIATIONMGR="hf.AffiliationMgr",q.HFGENCRL="hf.GenCRL";class oe extends c.LoggedClass{constructor(e){z.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:r,url:a,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${e} at ${a}`),n.debug("Retrieving CA certificate from "+t);const o=await z.getFirstDirFileNameContent(t);let c;if(s)n.debug(`Using HSM configuration for CA ${e} with library ${s.library}`);else{if(!r)throw new i.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),c=await z.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+e),this.user=await z.getCAUser("admin",c,o,e,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:s}=r;const n=a[0];e.debug(`Retrieving CA certificate from ${n}. cwd: ${process.cwd()}`);const o=await z.getFileContent(n);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new E.default(t,{trustedRoots:Buffer.from(o),verify:s},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const s=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${s.certs.length} certificates: ${JSON.stringify(s)}`),t?s.certs.map(e=>e.PEM):s}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new W(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new W(s)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),r=await this.User();let a;try{a=await t.newIdentityService().getOne(e,r)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s){let n;const o=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};n=await d.register(h,u),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return n}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:s}=t,n=c.Logging.for(oe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${i} in msp ${r}`);const o=V.fabricIdFromCertificate(i),l=V.encode(o);n.debug(`Identity ${o} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:s,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const s=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=oe.identityFromEnrollment(s,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,s){const n=await this.register(e,t,r,i,a,s),{userName:o}=e;return this.enroll(o,n)}async revoke(e){const t=await this.CA(),r=await this.User(),a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let s;try{s=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},r)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!s.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${s.errors.join("\n")}`);return s}}class ce extends r.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new i.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}async function le(e,t,r,i){const{stub:a}=e,s=(await a.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:s})}async function de(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function ue(e,t,a){let s=t;if("string"!=typeof s)try{const i=r.Model.ownerOf(e)||a.get("stub").getCreator().toString();t&&"function"==typeof t&&(s=await t(e,i,a))}catch(e){throw new i.InternalError("Failed to resolve collection mirror name: "+e)}if(!s||"string"!=typeof s)throw new i.InternalError("No collection found model "+e.constructor.name);return s}async function he(e,t,i,a){const s=await ue(a,t.resolver,e),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),o=await n.create(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} created with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}async function pe(e,t,i,a){const s=await ue(a,t.resolver,e),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),o=await n.update(a,e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} updated with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}async function ge(e,t,i,a){const s=await ue(a,t.resolver,e),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),o=await n.delete(r.Model.pk(a),e);e.logger.info(`Mirror for ${r.Model.tableName(this.class)} deleted with ${r.Model.pk(a)}: ${o[r.Model.pk(a)]}`)}s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"affiliation",void 0),s.__decorate([r.minlength(1),s.__metadata("design:type",Array)],ce.prototype,"attrs",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"enrollmentID",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"enrollmentSecret",void 0),s.__decorate([r.min(0),s.__metadata("design:type",Number)],ce.prototype,"maxEnrollments",void 0),s.__decorate([r.required(),s.__metadata("design:type",String)],ce.prototype,"role",void 0),e.ERC20Events=void 0,(Y=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",Y.APPROVAL="Approval",e.FabricBaseModel=class extends r.Model{constructor(e){super(e)}},s.__decorate([n.description("Stores the original timestamp of creation"),t.column(),t.createdAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),s.__decorate([n.description("Stores the timestamp of the last update"),t.column(),t.updatedAt(),s.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),s.__decorate([n.description("Stores the version of the model"),t.column(),i.version(),s.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=s.__decorate([n.uses(k),s.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},s.__decorate([n.description("Stores the creator"),t.column(),t.createdBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),s.__decorate([n.description("Stores the user that last updated the model"),t.column(),t.updatedBy(),s.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=s.__decorate([n.uses(k),s.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),r.Model.prototype.isShared=function(){return r.Model.isShared(this.constructor)},r.Model.prototype.isPrivate=function(){return r.Model.isPrivate(this.constructor)},r.Model.prototype.segregate=function(){return r.Model.segregate(this)},r.Model.segregate=(t=>{if(!r.Model.isTransient(t))return{model:t};const a=n.Metadata.validatableProperties(t.constructor),s=n.Metadata.get(t.constructor,i.DBKeys.TRANSIENT),o=n.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),c=n.Metadata.get(t.constructor,e.FabricModelKeys.PRIVATE),l={model:{},transient:{},private:{},shared:{}},d=Object.keys(s),u=Object.keys(o),h=Object.keys(c);for(const e of a){const r=d.includes(e),i=u.includes(e),a=h.includes(e);r?(l.transient=l.transient||{},l.transient[e]=t[e],i&&(l.private=l.private||{},l.private[e]=t[e]),a&&(l.shared=l.shared||{},l.shared[e]=t[e])):(l.model=l.model||{},l.model[e]=t[e])}return l.model=r.Model.build(l.model,t.constructor.name),l}).bind(r.Model),r.Model.isPrivate=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(r.Model),r.Model.isShared=(t=>!!n.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(r.Model),r.Model.mirrored=(t=>n.Metadata.get("function"!=typeof t?t.constructor:t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(r.Model),r.Model.ownerOf=(t=>{const r=n.Metadata.get(t.constructor,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(r.Model),r.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,n.Metadata.get(t,n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(r.Model),r.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=n.Metadata.key(...r),s=n.Metadata.key(...i),o="function"==typeof t?t:t.constructor,c=n.Metadata.get(o,a),l=n.Metadata.get(o,s);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(r.Model);const fe=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0);if(!a)throw new i.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};async function ye(e,a,s,n){if(s.length!==a.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const o=r.Model.ownerOf(n);if(!o)throw new i.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=a[0].collections,l="string"==typeof c?c:c(n,o,e),d=s.reduce((r,i,s)=>{const c="string"==typeof a[s].collections?a[s].collections:a[s].collections(n,o,e);if(c!==l)throw new t.UnsupportedError(`Segregated data collection mismatch: ${c} vs ${l}`);return r[i]=n[i],r},{}),u=new this.class(d),h=await this.override({segregated:l,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(u,e);Object.assign(n,h)}async function me(e,t,a,s){if(a.length!==t.length)throw new i.InternalError("Segregated data keys and metadata length mismatch");const n=r.Model.ownerOf(s);if(!n)throw new i.ValidationError("There's no assigned organization for model "+s.constructor.name);const o=t[0].collections,c="string"==typeof o?o:await o(s,n,e);a.reduce((r,i,a)=>(("string"==typeof t[a].collections?t[a].collections:t[a].collections(s,n,e))!==c||(r[i]=s[i]),r),{})}async function we(e,t,r,i,a){}async function be(e,t,r,i){}function Ce(e,t,r){return(a,s)=>{const o=[];return s?o.push(n.prop(),i.transient(),(r,i)=>{const a=n.Metadata.key(t,i),s=r.constructor,o=n.Metadata.get(s,a)||{},c=new Set(o.collections||[]);c.add(e),o.collections=[...c],n.Metadata.set(s,a,o);const l=n.Metadata.get(s,t)||{};new Set(l.collections||[]).add(e),o.collections=[...c],n.Metadata.set(s,t,o)},i.onCreate(ye,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onRead(me,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onUpdate(we,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()}),i.onDelete(be,{collections:e},{priority:95,group:"string"==typeof e?e:e.toString()})):n.Metadata.properties(a)?.forEach(i=>{r&&!r(i)||Ce(e,t)(a.prototype,i)}),n.apply(...o)(a,s)}}function Ee(t=fe){return n.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>Ce(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply()}class Ae extends r.JSONSerializer{constructor(){super()}preSerialize(e){const t=Object.assign({},e);let i;try{i=n.Metadata.modelName(e.constructor)}catch(e){i=void 0}t[r.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return r.Model.relations(e).forEach(e=>{t[e]=a(t[e])}),t}deserialize(e){const t=JSON.parse(e),i=t[r.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return r.Model.build(t,i)}serialize(e){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e)))}}function ve(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class Se extends r.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(e,t)))}preSerialize(e,t=!0){const i=Object.assign({},e);let a;try{a=n.Metadata.modelName(e.constructor)}catch(e){a=void 0}function s(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(s):this.preSerialize(e)}return t&&(i[r.ModelKeys.ANCHOR]=a||e.constructor.name),r.Model.relations(e).forEach(e=>{i[e]=s.call(this,i[e])}),i}}class _e extends t.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new i.InternalError("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(e,t){const r=t.logger.for(this.getUser),{caName:a,caCert:s,caKey:n,url:o,hsm:c}=e;r.info(`Creating CA user for ${a} at ${o}`),r.verbose("Retrieving CA certificate from "+s);const l=await z.getFirstDirFileNameContent(s);let d;if(c)r.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!n)throw new i.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),d=await z.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+a),this._user=await z.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:r,ctx:a}=(await this.logCtx(e,t.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[s]=e;if(!s)throw new i.InternalError("Missing Fabric CA configuration");const{url:n,tls:o,caName:c}=s;r.info(`Initializing CA Client for CA ${s.caName} at ${s.url}`);const{trustedRoots:l,verify:d}=o,u=l[0];r.debug(`Retrieving CA certificate from ${u}. cwd: ${process.cwd()}`);const h=await z.getFileContent(u);r.debug("CA Certificate: "+h.toString());const p=new E.default(n,{trustedRoots:Buffer.from(h),verify:d},c),g=await this.getUser(s,a);return r.debug("CA user loaded: "+g.getName()),{config:s,client:p}}async getCertificates(e,r=!0,...a){e instanceof t.Context?(a=[e],r=!0,e=void 0):"boolean"==typeof e?(r=e,e=void 0):"boolean"!=typeof r&&(a=[r,...a],r=!0);const{log:s}=(await this.logCtx(a,i.OperationKeys.READ,!0)).for(this.getCertificates);s.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const n=(await this.certificates.getCertificates(e||{},this.user)).result;return s.verbose(`Found ${n.certs.length} certificates`),s.debug(n.certs),r?n.certs.map(e=>e.PEM):n}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const r=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!r)return new W(e);const[,a,s]=r;switch(a){case"74":case"71":return new i.ConflictError(s);case"20":return new t.AuthorizationError(s);default:return new W(s)}}async read(e,...t){const{log:r}=(await this.logCtx(t,i.OperationKeys.READ,!0)).for(this.read);let a;r.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new i.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,s,...n){const{log:o}=(await this.logCtx(n,"register",!0)).for(this.register);let c;try{const{userName:n,password:l}=e,d={enrollmentID:n,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:s};c=await this.client.register(d,this.user),o.info(`Registration for ${n} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:o}=t;a.verbose(`Generating Identity from certificate ${s} in msp ${r}`);const c=V.fabricIdFromCertificate(s),l=V.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:s,privateKey:n.toBytes(),rootCertificate:o},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let s;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});s=_e.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${s.id}`)}catch(e){throw this.parseError(e)}return s}async registerAndEnroll(e,t=!1,r="",i,a,s,...n){const{ctx:o}=(await this.logCtx(n,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,s,o),{userName:l}=e;return this.enroll(l,c,o)}async revoke(e,...t){const{log:r}=(await this.logCtx(t,"revoke",!0)).for(this.revoke);r.verbose("Revoking identity with enrollment ID "+e);const a=await this.read(e);if(!a)throw new i.NotFoundError("Could not find enrollment with id "+e);let s;try{s=await this.client.revoke({enrollmentID:a.id,reason:"User Deletion"},this.user)}catch(t){throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!s.success)throw new i.InternalError(`Could not revoke enrollment with id ${e}: ${s.errors.join("\n")}`);return s}}const Ie=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),Me=new c.MiniLogger("fabric-fs");async function xe(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Oe(e,r){const i=await xe(r,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)});return{mspId:e,credentials:i}}async function Ne(e){const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path"));return i(e,(await r.readdir(e))[0])}async function Te(e){const r=await xe(e,async e=>{const{promises:r}=await t.normalizeImport(import("fs")),i=await Ne(e);return await r.readFile(i)}),i=await Fe(r),a=i[Object.getOwnPropertySymbols(i)[0]];return l.signers.newPrivateKeySigner(a)}async function Fe(e){let r;if(c.isBrowser())r=globalThis.crypto.subtle;else{const e=await t.normalizeImport(import("crypto"));r=e.subtle||e.webcrypto.subtle}if(!r)throw Error("Could not load SubtleCrypto module");const a=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),s=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(a,"base64").toString("binary"));try{return await r.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new i.InternalError(e)}}class Re{static#e=null;static#t=!1;constructor(e){if(Re.#e||(Re.#e=new _.default.PKCS11,Re.#e.load(this.findHSMPKCS11Lib(e))),!Re.#t){try{Re.#e.C_Initialize()}catch(e){if(e.code!==_.default.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw e}Re.#t=!0}}findHSMPKCS11Lib(e){const t=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];e&&t.push(e);for(const e of t)if(I.default.existsSync(e))return e;throw new re("Unable to find PKCS11 library")}dispose(){Re.#e.C_Finalize()}sanitizeOptions(e){const t=Object.assign({userType:_.default.CKU_USER},e);return this.assertNotEmpty(t.label,"label"),this.assertNotEmpty(t.pin,"pin"),this.assertNotEmpty(t.identifier,"identifier"),t}assertNotEmpty(e,t){if(!e||0===e.toString().trim().length)throw Error(t+" property must be provided")}findSlotForLabel(e){const t=Re.#e.C_GetSlotList(!0);if(0===t.length)throw Error("No pkcs11 slots can be found");const r=t.find(t=>Re.#e.C_GetTokenInfo(t).label.trim()===e);if(!r)throw Error(`label ${e} cannot be found in the pkcs11 slot list`);return r}login(e,t,r){try{Re.#e.C_Login(e,t,r)}catch(e){if(e.code!==_.default.CKR_USER_ALREADY_LOGGED_IN)throw e}}findObjectInHSM(e,t,r){const i=[{type:_.default.CKA_ID,value:r},{type:_.default.CKA_CLASS,value:t},{type:_.default.CKA_KEY_TYPE,value:_.default.CKK_EC}];Re.#e.C_FindObjectsInit(e,i);const a=Re.#e.C_FindObjects(e,1)[0];if(!a)throw Re.#e.C_FindObjectsFinal(e),Error("Unable to find object in HSM with ID "+r.toString());return Re.#e.C_FindObjectsFinal(e),a}newSigner(e){const t=this.sanitizeOptions(e),r=Re.#e,i=this.findSlotForLabel(t.label),a=r.C_OpenSession(i,_.default.CKF_SERIAL_SESSION);let s;try{this.login(a,t.userType,t.pin),s=this.findObjectInHSM(a,_.default.CKO_PRIVATE_KEY,t.identifier)}catch(e){throw Re.#e.C_CloseSession(a),e}return{signer:async e=>{Re.#e.C_SignInit(a,{mechanism:_.default.CKM_ECDSA},s);const t=await Re.#e.C_SignAsync(a,Buffer.from(e),Buffer.alloc(2*w.p256.Point.Fn.BYTES));return w.p256.Signature.fromBytes(t,"compact").normalizeS().toBytes("der")},close:()=>{Re.#e.C_CloseSession(a)}}}assertDefined(e){if(void 0===e)throw Error("required value was undefined");return e}getUncompressedPointOnCurve(e){const t=e.export({format:"jwk"}),r=Buffer.from(this.assertDefined(t.x),"base64url"),i=Buffer.from(this.assertDefined(t.y),"base64url"),a=Buffer.from("04","hex");return Buffer.concat([a,r,i])}getSKIFromCertificatePath(e){const t=e.endsWith(".pem")?e:M.default.join(e,"cert.pem"),r=I.default.readFileSync(t);return this.getSKIFromCertificate(r)}getSKIFromCertificate(e){const t=new A.default.X509Certificate(e),r=this.getUncompressedPointOnCurve(t.publicKey);return A.default.createHash("sha256").update(r).digest()}}class Be extends t.Statement{constructor(e,t){super(e,t)}squash(e){const r=super.squash(e);if(!r)return r;const{method:a,params:s,args:n}=r,{direction:o,limit:c}=s;switch(a){case t.PreparedStatementKeys.FIND_BY:break;case t.PreparedStatementKeys.LIST_BY:n.push(o);break;case t.PreparedStatementKeys.PAGE_BY:n.push(o,c);break;case t.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new i.InternalError("Unsupported method "+a)}return r}async executePrepared(...e){const r=t.Repository.forModel(this.fromSelector,this.adapter.alias),{method:i,args:a}=this.prepared;return r.statement(i,...a,...e)}async prepare(e){if(e=e||await this.adapter.context(t.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const r=[],i={},a={class:this.fromSelector,args:r,params:i},s=[t.QueryClause.FIND_BY];if(this.whereCondition){const t=this.prepareCondition(this.whereCondition,e);s.push(t.method),t.args&&t.args.length&&r.push(...t.args)}return this.selectSelector&&s.push(t.QueryClause.SELECT,this.selectSelector.join(` ${t.QueryClause.AND.toLowerCase()} `)),this.orderBySelector&&(s.push(t.QueryClause.ORDER_BY,this.orderBySelector[0]),r.push(this.orderBySelector[1])),a.method=c.toCamelCase(s.join(" ")),a.params=i,this.prepared=a,this}build(){throw new t.UnsupportedError("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(e,...r){throw new t.UnsupportedError("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class De extends t.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new t.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}}var Ke;class $e extends t.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new F}static{this.log=c.Logging.for($e)}constructor(e,t){super(e,k,t),this.serializer=$e.serializer}Statement(e){return new Be(this,e)}Paginator(e,t,r){return new De(this,e,t,r)}async flags(e,t,r,...i){return Object.assign(await super.flags(e,t,Object.assign({},this.config,r),...i))}decode(e){return $e.decoder.decode(e)}repository(){return x}createPrefix(e,t,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),o=r.Model.tableName(e),c={};return c[a.CouchDBKeys.TABLE]=o,Object.assign(c,i),[e,t,c,...n]}createAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.createAllPrefix),l=t.map((e,t)=>{const r={};return r[a.CouchDBKeys.TABLE]=o,Object.assign(r,s[t]),r});return[e,t,l,...c]}updateAllPrefix(e,t,s,...n){const o=r.Model.tableName(e);if(t.length!==s.length)throw new i.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(n,this.updateAllPrefix),l=t.map(()=>{const e={};return e[a.CouchDBKeys.TABLE]=o,e});return[e,t,l,...c]}async createAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s],o=n.shift(),{log:c,ctx:l}=this.logCtx(n,this.createAll),d=r.Model.tableName(e);c.info(`adding ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,e.name);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async readAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);s.info(`reading ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.evaluateTransaction(n,i.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async updateAll(e,t,a,...s){if(t.length!==a.length)throw new i.InternalError("Ids and models must have the same length");const n=[...s],o=n.shift(),{log:c,ctx:l}=this.logCtx(n,this.updateAll),d=r.Model.tableName(e);c.info(`updating ${t.length} entries to ${d} table`),c.verbose("pks: "+t);const u=await this.submitTransaction(l,i.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],o,void 0,e.name);try{return JSON.parse(this.decode(u)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}async deleteAll(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.deleteAll),o=r.Model.tableName(e);s.info(`deleting ${t.length} entries to ${o} table`),s.verbose("pks: "+t);const c=await this.submitTransaction(n,i.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(t)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new i.SerializationError(e)}}prepare(e,...i){const{log:a}=this.logCtx(i,this.prepare),s=r.Model.segregate(e);return e[t.PersistenceKeys.METADATA]&&(a.silly("Passing along persistence metadata for "+e[t.PersistenceKeys.METADATA]),Object.defineProperty(s.model,t.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[t.PersistenceKeys.METADATA]})),{record:s.model,model:s.model,id:e[r.Model.pk(e.constructor)],transient:s.transient,private:s.private,shared:s.shared}}revert(e,t,r,a,...s){const{log:n}=this.logCtx(s,this.revert);return a&&(n.verbose("re-adding transient properties: "+Object.keys(a).join(", ")),Object.entries(a).forEach(([r,a])=>{if(r in e)throw new i.InternalError(`Transient property ${r} already exists on model ${"string"==typeof t?t:t.name}. should be impossible`);e[r]=a})),new t(e)}async create(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.create),d=r.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+t);const u=await this.submitTransaction(l,i.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],s,void 0,e.name);return this.serializer.deserialize(this.decode(u))}async read(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.readAll),o=r.Model.tableName(e);s.verbose(`reading entry from ${o} table`),s.debug("pk: "+t);const c=await this.evaluateTransaction(n,i.OperationKeys.READ,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,t,i,...s){const n=r.Model.tableName(e),{ctxArgs:o}=this.logCtx(s,this.updatePrefix),c={};return c[a.CouchDBKeys.TABLE]=n,Object.assign(c,i),[e,t,c,...o]}async update(e,t,a,s={},...n){const o=[...n],{log:c,ctx:l}=this.logCtx(o,this.updateAll);c.info("CLIENT UPDATE class : "+typeof e);const d=r.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+t);const u=await this.submitTransaction(l,i.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],s,void 0,e.name);return this.serializer.deserialize(this.decode(u))}async delete(e,t,...a){const{log:s,ctx:n}=this.logCtx(a,this.delete),o=r.Model.tableName(e);s.verbose(`deleting entry from ${o} table`),s.debug("pk: "+t);const c=await this.submitTransaction(n,i.OperationKeys.DELETE,[t.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}async raw(e,t=!0,a,...s){const{log:n,ctx:o}=this.logCtx(s,this.raw),c=a.name;let l,d;n.info("Performing raw statement on table "+r.Model.tableName(a));try{l=await this.evaluateTransaction(o,"raw",[JSON.stringify(e),t],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new i.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return r.Model.isModel(e)?d.map(e=>r.Model.build(e)):d}return u=d,r.Model.isModel(u)?r.Model.build(u):u;var u}getClient(){return this._client||(this._client=$e.getClient(this.config)),this._client}async Gateway(e){return $e.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return $e.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a,s,n){const o=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(n));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(n)||this.config.contractName}.${t}`),o.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;s=s?.length?s:void 0;const d={arguments:i||[],transientData:a};return await l.call(c,t,d)}catch(e){if(10===e.code)throw Error(""+e.details[0].message);throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(e){return $e.parseError(e)}async submitTransaction(e,t,r,i,a,s){return this.transaction(e,t,!0,r,i,a,s)}async evaluateTransaction(e,t,r,i,a,s){return this.transaction(e,t,!1,r,i,a,s)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(e,t,r){const i=this.log.for(this.getContract),a=this.getNetwork(e,t.channel);let s;try{i.debug(`Retrieving chaincode ${t.chaincodeName} contract ${r||t.contractName} from network ${t.channel}`),r=r||t.contractName,s=a.getContract(t.chaincodeName,r)}catch(e){throw this.parseError(e)}return s}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let r=e.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(I.default.readFileSync(r,"utf8"))}catch(e){throw new i.InternalError(`Failed to read the tls certificate from ${r}: ${e}`)}const a=S.credentials.createSsl(r);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new g.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,t,r){const i=c.Logging.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const a=await Oe(t.mspId,t.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+t.keyCertOrDirectoryPath);let s,n=()=>{};if(t.hsm){const e=new Re(t.hsm.library),r=e.getSKIFromCertificatePath(t.certCertOrDirectoryPath),i=e.newSigner({label:t.hsm.tokenLabel,pin:t.hsm.pin+"",identifier:r});s=i.signer,n=i.close}else s=await Te(t.keyCertOrDirectoryPath);const o={client:e,identity:a,signer:s,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+t.mspId);const d=l.connect(o);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r),n()}})),d}Dispatch(){return new $e._baseDispatch}static parseError(e){const r="string"==typeof e?e:e.message;return r.includes("MVCC_READ_CONFLICT")?new ae(e):r.includes("ENDORSEMENT_POLICY_FAILURE")?new ne(e):r.includes("PHANTOM_READ_CONFLICT")?new se(e):e instanceof Error&&e.code&&9===e.code?new ie(e):r.includes(i.NotFoundError.name)?new i.NotFoundError(e):r.includes(i.ConflictError.name)?new i.ConflictError(e):r.includes(i.BadRequestError.name)?new i.BadRequestError(e):r.includes(t.QueryError.name)?new t.QueryError(e):r.includes(t.PagingError.name)?new t.PagingError(e):r.includes(t.UnsupportedError.name)?new t.UnsupportedError(e):r.includes(t.MigrationError.name)?new t.MigrationError(e):r.includes(t.ObserverError.name)?new t.ObserverError(e):r.includes(t.AuthorizationError.name)?new t.AuthorizationError(e):r.includes(t.ForbiddenError.name)?new t.ForbiddenError(e):r.includes(t.ConnectionError.name)?new t.ConnectionError(e):r.includes(i.SerializationError.name)?new i.SerializationError(e):new i.InternalError(e)}}s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],$e.prototype,"create",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],$e.prototype,"read",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],$e.prototype,"update",null),s.__decorate([c.debug(),c.final(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],$e.prototype,"delete",null),s.__decorate([c.debug(),s.__metadata("design:type",Function),s.__metadata("design:paramtypes",[Object,"function"==typeof(Ke="undefined"!=typeof D&&D)?Ke:Object,Object,t.Context]),s.__metadata("design:returntype",Promise)],$e.prototype,"raw",null),$e.decoration(),t.Adapter.setCurrent(k);class Pe extends t.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof $e))throw new t.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,a,s,...n){const{log:o,ctxArgs:c}=t.Adapter.logCtx(this.updateObservers,a,!1,...n);if(this.adapter)try{await this.adapter.refresh(e,a,s,...c)}catch(e){throw new i.InternalError("Failed to refresh dispatch: "+e)}else o.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:r.Model.tableName(e)}:${a}`)}async handleEvents(e){if(!this.listeningStack)throw new i.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new i.InternalError("No adapter found. should be impossible");const t=e||await this.adapter.context(i.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||r.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:i,event:s,owner:n}=ve(e.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(i?r.Model.get(i):r.Model.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(e,s,o.id,t)}catch(e){a.error(`Failed update observables for table ${i} event ${s} id: ${o.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close()}}async initialize(){if(!this.adapter)throw new i.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},r.Model),{ctx:t}=this.logCtx([e],this.initialize),a=(await $e.getGateway(t,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new i.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(t)}}$e&&($e._baseDispatch=Pe);const ke="##VERSION##",ze="##PACKAGE##";n.Metadata.registerLibrary(ze,ke),e.AllowanceError=X,e.BalanceError=Q,e.BaseEncoder=G,e.ClientSerializer=F,e.CoreUtils=z,e.CryptoUtils=V,e.DefaultFabricClientFlags=Ie,e.DeterministicSerializer=Ae,e.EndorsementError=ie,e.EndorsementPolicyError=ne,e.FabricClientAdapter=$e,e.FabricClientDispatch=Pe,e.FabricClientRepository=x,e.FabricERC20ClientRepository=R,e.FabricEnrollmentService=oe,e.FabricFlavour=k,e.FabricIdentityService=_e,e.ImplicitPrivateCollection=fe,e.MissingContextError=Z,e.MissingPKCSS11Lib=re,e.ModelCollection=(e,t)=>{const a=t||("function"!=typeof e?r.Model.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!a)throw new i.InternalError(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(s.name)}${t?c.toPascalCase(t):""}`},e.MvccReadConflictError=ae,e.NotInitializedError=te,e.OverflowError=J,e.Owner=function(){return function(e,r,a){const s=a.value;return a.value=async function(...e){const a=e[0],n=a.clientIdentity.getID(),o=await this.tokenRepository.select(),c=await o.execute(a);if(0==c.length)throw new i.NotFoundError("No tokens avaialble");if(c.length>1)throw new i.NotFoundError("To many token available : "+c.length);if(c[0].owner!=n)throw new t.AuthorizationError(`User not authorized to run ${r} on the token`);return await s.apply(this,e)},a}},e.PACKAGE_NAME=ze,e.PhantomReadConflictError=se,e.RegistrationError=W,e.RegistrationRequestBuilder=ce,e.SimpleDeterministicSerializer=Se,e.UnauthorizedPrivateDataAccess=ee,e.VERSION=ke,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new J(`Addition overflow: ${e} + ${t}`);return r},e.contentOfLoadFile=xe,e.createMirrorHandler=he,e.deleteMirrorHandler=ge,e.evalMirrorMetadata=ue,e.extractPrivateKey=Fe,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelIndexes=(e,t)=>{const i=B([a.CouchDBKeys.TABLE]),s=t||{};s[i]={index:{fields:[a.CouchDBKeys.TABLE]},name:i,ddoc:i,type:"json"};const n={},o=r.Model.indexes(e);for(const e of Object.keys(o))for(const[,t]of Object.entries(o[e])){const r=t.directions,i=t.compositions,s=[e,a.CouchDBKeys.TABLE];K(n,s),i&&i.length&&K(n,s,void 0,i),r&&r.length&&r.forEach(e=>{K(n,s,e),i&&i.length&&K(n,s,e,i)})}return Object.entries(n).forEach(([e,t])=>{s[e]=t}),Object.values(n)},e.getCAUser=async(e,t,r,i)=>{Me.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),s=d.User.newCryptoSuite();a.setCryptoSuite(s);const n=s.createKeyFromRaw(t);return await a.setEnrollment(n,r,i),a},e.getFirstDirFileName=Ne,e.getFirstDirFileNameContent=async e=>{const{promises:r}=await t.normalizeImport(import("fs")),{join:i}=await t.normalizeImport(import("path")),a=await r.readdir(e);return(await r.readFile(i(e,a[0]))).toString()},e.getIdentity=Oe,e.getSigner=Te,e.mirror=(t,r)=>n.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(r,a)=>{const s={condition:a,resolver:r};return n.apply(n.metadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),s),Ee(t),i.afterCreate(he,s,{priority:95}),i.afterUpdate(pe,s,{priority:95}),i.afterDelete(ge,s,{priority:95}))},args:[t,r]}).apply(),e.ownedBy=()=>n.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(t,a)=>n.apply(r.required(),i.readonly(),i.onCreate(le),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(t,a),args:[]}).apply(),e.ownedByOnCreate=le,e.parseEventName=ve,e.privateData=Ee,e.readFile=async e=>"string"!=typeof e?e:await(async e=>{const{promises:r}=await t.normalizeImport(import("fs"));return await r.readFile(e)})(e),e.readModelFile=$,e.readModelFolders=async(...e)=>{const t=require("fs"),r=[];for(const i of e){const e=t.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const t of e)r.push(...$(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string contains digits"));const t=parseInt(e);if(isNaN(t))throw new i.ValidationError(r.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return t},e.segregatedDataOnCreate=ye,e.segregatedDataOnDelete=be,e.segregatedDataOnRead=me,e.segregatedDataOnUpdate=we,e.sharedData=t=>n.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>Ce(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new J(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>n.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(t,a)=>n.apply(r.required(),i.readonly(),i.onCreate(de),i.onUpdate(de),n.propMetadata(n.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(t,a),args:[]}).apply(),e.transactionIdOnCreate=de,e.updateMirrorHandler=pe,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");function s(e){const t=a.dirname(e);if(i.existsSync(t))return!0;s(t),i.mkdirSync(t)}e.forEach(e=>{const n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));s(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/core"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("pkcs11js"),require("fs"),require("path"),require("@noble/curves/nist")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/core","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","pkcs11js","fs","path","@noble/curves/nist"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsCore,e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.pkcs11js,e.fs,e.path,e.nist);
2
2
  //# sourceMappingURL=for-fabric.cjs.map