@decaf-ts/for-fabric 0.3.21 → 0.3.22

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,o,s,c,l,d,u,h,g,p,f,m){"use strict";function y(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 w=y(h),b=y(p);function C(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;C(r),t.mkdirSync(r)}function E(e){const r=require("path"),i=require(r.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof t.Model}catch(e){return!1}})}function A(e,t=process.cwd(),r){if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const n=e._id.replace(/^_design\//,""),o=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));C(o);const s={...e};delete s._rev,i.writeFileSync(o,JSON.stringify(s,void 0,2))})}function v(e,t,r,i,a,n,o){return{name:e,policy:t,requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}}function S(e,t=e+"Private",r=0,i=0,a=0,n=!0,o=!0){const s=v(t,`OR('${e}.member')`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`OR('${e}'.peer)`},s}function O(e,t,r=1,i=2,a=0,n=!0,o=!0){const s=v(t,`OR(${e.map(e=>`'${e}.member'`).join(",")})`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`AND(${e.map(e=>`'${e}.peer'`).join(",")})`},s}class I extends a.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,rebuildWithTransient:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return o.verbose(`paginating ${t.Model.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...s)}async listBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return n.verbose(`listing ${t.Model.tableName(this.class)} by ${e} ${r}`),await this.statement(this.listBy.name,e,r,...o)}async findBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...o)}async findOneBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...o)}async find(e,r=a.OrderDirection.ASC,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...o)}async page(e,r=a.OrderDirection.ASC,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE,!0)).for(this.page);return o.verbose(`paging ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...s)}async statement(e,...r){const{log:n,ctx:o,ctxArgs:s}=(await this.logCtx(r,a.PersistenceKeys.STATEMENT,!0)).for(this.statement);n.verbose("Executing prepared statement "+e);const c=s.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(o,a.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[i.CouchDBKeys.TABLE]&&e[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(e):e):l[i.CouchDBKeys.TABLE]&&l[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(l):a.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async countOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.Model.tableName(this.class)}${e?" by "+e:""}`);const o=e?[e,...n]:n;return this.statement(a.PreparedStatementKeys.COUNT_OF,...o)}async maxOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MAX_OF,e,...n)}async minOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MIN_OF,e,...n)}async avgOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.AVG_OF,e,...n)}async sumOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.SUM_OF,e,...n)}async distinctOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.DISTINCT_OF,e,...n)}async groupOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.Model.tableName(this.class)} by ${e}`),this.statement(a.PreparedStatementKeys.GROUP_OF,e,...n)}async healthcheck(...e){const{ctxArgs:t}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...t)}async create(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.create);a.debug(`Creating new ${this.class.name} in table ${t.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const o=this.adapter.prepare(e,i),{record:s,id:c,transient:l}=o,d=await this.adapter.create(this.class,c,s,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:a,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const o=this.adapter.prepare(e,n),{id:s,transient:c}=o;let l=o.record;return a.debug(`updating ${this.class.name} in table ${t.Model.tableName(this.class)} with id ${s}`),l=await this.adapter.update(this.class,s,l,c,...i),this.adapter.revert(l,this.class,s,c,n)}async createAllPrefix(e,...t){const{ctx:i,ctxArgs:a}=(await this.logCtx(t,r.OperationKeys.CREATE,!0)).for(this.createAllPrefix),n=i.get("ignoreHandlers"),o=i.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),n||await r.enforceDBDecorators(this,i,e,r.OperationKeys.CREATE,r.OperationKeys.ON),e))),!o){const t=i.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=r.reduceErrorsToPrint(a);if(n)throw new r.ValidationError(n)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=o.map(e=>e.record),l=o.map(e=>e.transient),d=await this.adapter.createAll(this.class,s,c,l,...n);return Promise.all(d.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,l[t],i)}))}async updateAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=await this.adapter.updateAll(this.class,s,o.map(e=>e.record),o.map(e=>e.transient),...n);return Promise.all(c.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,o[t].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.Model.mirroredAt(r)&&e.accumulate({legacy:!0})}}let M=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],M.prototype,"name",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],M.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],M.prototype,"symbol",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],M.prototype,"decimals",void 0),M=n.__decorate([a.table("erc20_tokens"),t.model(),n.__metadata("design:paramtypes",[Object])],M);let _=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],_.prototype,"id",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],_.prototype,"token",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],_.prototype,"balance",void 0),n.__decorate([a.column(),n.__metadata("design:type",String)],_.prototype,"captive",void 0),_=n.__decorate([a.table("erc20_wallets"),t.model(),n.__metadata("design:paramtypes",[Object])],_);let x=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),a.column(),t.required(),n.__metadata("design:type",String)],x.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],x.prototype,"spender",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],x.prototype,"value",void 0),x=n.__decorate([a.table("erc20_allowances"),t.model(),n.__metadata("design:paramtypes",[Object])],x);class N extends t.JSONSerializer{constructor(){super()}preSerialize(e,i){const a=Object.assign({},e);let n=o.Metadata.modelName(e.constructor);if(!n||"Object"===n){if(!i)throw new r.SerializationError("Could not find metadata for "+e.constructor.name);n=i}return a[t.ModelKeys.ANCHOR]=n,a}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class T extends I{static{this.serializer=new N}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,i,n,...o){if(!this.observerHandler)throw new r.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:c}=this.logCtx(o,this.updateObservers);let l;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.Model.get(e):e,l=void 0===n?void 0:Array.isArray(n)?n.map(r=>a.Sequence.parseValue(t.Model.sequenceFor(e).type,r)):a.Sequence.parseValue(t.Model.sequenceFor(e).type,n),await this.observerHandler.updateObservers(e,i,l,...c)}decode(e){return T.decoder.decode(e)}constructor(e){super(e,_),this.serializer=T.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,t,r){const i=await a.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(i.args,this.transferFrom),o=await this.adapter.submitTransaction(n,"TransferFrom",[e,t,r.toString()]);return"true"===this.decode(o)}async approve(e,t){const r=await a.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),n=await this.adapter.submitTransaction(i,"Approve",[e,t.toString()]);return"true"===this.decode(n)}async allowance(e,t){const r=await a.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),n=await this.adapter.submitTransaction(i,"Allowance",[e,t]);return Number(this.decode(n))}async initialize(e){const t=await a.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[T.serializer.serialize(e)]);return"true"===this.decode(i)}async checkInitialized(){const e=await a.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(t,"CheckInitialized")}async mint(e){const t=await a.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[e.toString()])}async burn(e){const t=await a.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[e.toString()])}async burnFrom(e,t){const r=await a.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[e,t.toString()])}async clientAccountBalance(){const e=await a.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(t,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const e=await a.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(t,"ClientAccountID");return this.decode(r)}}function F(e,i,a){let n,o,s;function c(i,a){if(n=n||t.Model.pk(e),s=s||t.Model.sequenceFor(e),o=o||t.Model.composed(e,n),o)return r.composeAttributeValue(i,o);const c=i[n]||a;if(void 0===c)throw new r.InternalError("could not rebuild id for "+i.constructor.name);return c}if(Array.isArray(i)){if(!Array.isArray(a)||a.length!==i.length)throw new r.InternalError("inconsistent parameters. both must be arrays of equal length");return i.map((e,t)=>c(e,a[t]))}return c(i,a)}var R;e.IdentityCredentials=class extends a.BaseModel{constructor(e){super(e)}},n.__decorate([o.description("Unique identifier of the credentials record"),a.column(),a.pk(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),n.__decorate([o.description("PEM-encoded X.509 certificate for the identity"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),n.__decorate([o.description("PEM-encoded root or intermediate certificate"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),n.__decorate([o.description("PEM-encoded private key"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(R=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",R.SHARED="shared",R.FABRIC="fabric",R.OWNED_BY="owned-by",R.TRANSACTION_ID="transaction-id",R.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const P="hlf-fabric";e.Identity=class extends a.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},n.__decorate([o.description("Unique identifier of the identity"),a.pk(),n.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),n.__decorate([a.oneToOne(e.IdentityCredentials,{update:a.Cascade.CASCADE,delete:a.Cascade.CASCADE}),n.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),n.__decorate([a.column(),t.required(),a.index(),n.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.Identity);class ${static{this.logger=new c.MiniLogger($.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:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}static async getCAUser(e,r,i,a,n){this.logger.debug(t.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const o=new d.User(e),s=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(s);o.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,i,n.hsm):this.getSoftwareEnrollmentKey(c,r);return await o.setEnrollment(l,i,a),o}static getCryptoSuite(e){return e?($.cryptoSuite||($.cryptoSuite=d.User.newCryptoSuite(e)),$.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 u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,t){return{mspId:e,credentials:await this.contentOfLoadFile(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)})}}static async getFirstDirFileName(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}static async getFileContent(e){const{promises:t}=await a.normalizeImport(import("fs"));return(await t.readFile(e)).toString()}static async getSigner(e){const t=await this.contentOfLoadFile(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)}),r=await this.extractPrivateKey(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}static async extractPrivateKey(e){let t;if(globalThis.window&&globalThis.window.Crypto)t=globalThis.Crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(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(r,"base64").toString("binary"));return await t.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function B(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const k=new g.Crypto;var K,L,z,j,U;w.cryptoProvider.set(k),e.BASE_ALPHABET=void 0,(K=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",K.BASE8="01234567",K.BASE11="0123456789a",K.BASE16="0123456789abcdef",K.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",K.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",K.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",K.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",K.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",K.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",K.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(L=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",L[L.ITERATIONS=1e3]="ITERATIONS",L[L.KEYLENGTH=48]="KEYLENGTH",L[L.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",L[L.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",L.ALGORYTHM="AES-GCM",L.KEY_ALGORYTHM="PBKDF2";class H{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,o=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*o[e]>>>0,o[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let s=n-r;for(;s!==n&&0===o[s];)s++;let c=this.leader.repeat(t);for(;n>s;++s)c+=this.alphabet.charAt(o[s]);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 o=0;for(let e=a-1;(0!==r||i>o)&&-1!==e;e--,o++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=o,t++}let o=a-i;for(;o!==a&&0===n[o];)o++;const s=new Uint8Array(r+(a-o));let c=r;for(;o!==a;)s[c++]=n[o++];return s}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class G{static{this.b58encoder=new H(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(G.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(t.stringFormat("Parsing certificate: {0}",e));const r=new w.X509Certificate(e),{subject:i,issuer:a}=r;return this.logger.debug(t.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=k.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"),o=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",o,{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 k.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 w.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,k.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new w.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:k.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=k.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},o=await this.getSubtleCrypto().deriveBits(n,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(o)}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 q extends r.InternalError{constructor(e){super(e,q.name)}}class V extends r.InternalError{constructor(e){super(e,V.name)}}class Y extends r.InternalError{constructor(e){super(e,Y.name)}}class J extends a.AuthorizationError{constructor(e){super(e,J.name)}}class W extends r.InternalError{constructor(e){super(e,W.name,500)}}class Q extends r.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(Q.name,e,403)}}class X extends r.BaseError{constructor(e){super(X.name,e,409)}}class Z extends r.InternalError{constructor(e){super(e,Z.name,500)}}class ee extends r.InternalError{constructor(e){super(e,ee.name,500)}}class te extends r.InternalError{constructor(e){super(e,te.name,500)}}class re extends r.InternalError{constructor(e){super(e,re.name,500)}}class ie extends r.InternalError{constructor(e){super(e,ie.name,500)}}class ae extends r.InternalError{constructor(e,t=ae.name,r=590){super(e,t,r)}}class ne extends r.InternalError{constructor(e){super(e,ne.name,591)}}class oe extends r.InternalError{constructor(e){super(e,oe.name,592)}}e.HFCAIdentityType=void 0,(z=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",z.ORDERER="orderer",z.CLIENT="client",z.USER="user",z.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(j=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",j.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",j.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",j.HFINTERMEDIATECA="hf.IntermediateCA",j.HFREVOKER="hf.Revoker",j.HFAFFILIATIONMGR="hf.AffiliationMgr",j.HFGENCRL="hf.GenCRL";class se extends c.LoggedClass{constructor(e){$.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:i,url:a,hsm:n}=this.caConfig,o=this.log.for(this.User);o.debug(`Creating CA user for ${e} at ${a}`),o.debug("Retrieving CA certificate from "+t);const s=await $.getFirstDirFileNameContent(t);let c;if(n)o.debug(`Using HSM configuration for CA ${e} with library ${n.library}`);else{if(!i)throw new r.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);o.debug("Retrieving CA key from "+i),c=await $.getFirstDirFileNameContent(i)}return o.debug("Loading Admin user for ca "+e),this.user=await $.getCAUser("admin",c,s,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 o=a[0];e.debug(`Retrieving CA certificate from ${o}. cwd: ${process.cwd()}`);const c=await $.getFileContent(o);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new s(t,{trustedRoots:Buffer.from(c),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 t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new J(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new J(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(),i=await this.User();let a;try{a=await t.newIdentityService().getOne(e,i)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.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 o;const s=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};o=await d.register(h,u),s.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return o}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:n}=t,o=c.Logging.for(se,{}).for(this.identityFromEnrollment);o.debug(`Generating Identity from certificate ${i} in msp ${r}`);const s=G.fabricIdFromCertificate(i),l=G.encode(s);o.debug(`Identity ${s} 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=se.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 o=await this.register(e,t,r,i,a,n),{userName:s}=e;return this.enroll(s,o)}async revoke(e){const t=await this.CA(),i=await this.User(),a=await this.read(e);if(!a)throw new r.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},i)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}class ce extends t.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new r.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}}function le(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function de(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 ue(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function he(e,i,a){let n=i;if("string"!=typeof n)try{const r=t.Model.ownerOf(e)||a.get("stub").getCreator().toString();i&&"function"==typeof i&&(n=await i(e,r,a))}catch(e){throw new r.InternalError("Failed to resolve collection mirror name: "+e)}if(!n||"string"!=typeof n)throw new r.InternalError("No collection found model "+e.constructor.name);return n}async function ge(e,r,i,a){const n=await he(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(s,e);e.logger.info(`Mirror for ${t.Model.tableName(this.class)} created with ${t.Model.pk(a)}: ${i[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function pe(e,r,i,a){const n=await he(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(s,e),e.logger.info(`Mirror for ${t.Model.tableName(this.class)} updated: ${a[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function fe(e,r,i,a){const n=await he(a,r.resolver,e),o=e;o.put("mirror",!0),o.put("mirrorCollection",n),o.put("segregated",n);try{const r=a[t.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.Model.tableName(this.class)} deleted: ${r+""}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0),o.put("segregated",void 0)}}async function me(e,t,r,i){const n=le(e.get("identity"));if(n&&(n===t.mspId||t.condition&&t.condition(n)))throw new a.AuthorizationError(`Organization ${n} is not authorized to modify mirrored data`)}async function ye(e,t,r,i){const a=le(e.get("identity"));if(!a)return;const n=await he(i,t.resolver,e),o=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${n}`),o.put("mirror",!0),o.put("mirrorCollection",n),o.put("fullySegregated",!0),o.readFrom(n))}n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"affiliation",void 0),n.__decorate([t.minlength(1),n.__metadata("design:type",Array)],ce.prototype,"attrs",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentID",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentSecret",void 0),n.__decorate([t.min(0),n.__metadata("design:type",Number)],ce.prototype,"maxEnrollments",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"role",void 0),e.ERC20Events=void 0,(U=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",U.APPROVAL="Approval",e.FabricBaseModel=class extends t.Model{constructor(e){super(e)}},n.__decorate([o.description("Stores the original timestamp of creation"),a.column(),a.createdAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),n.__decorate([o.description("Stores the timestamp of the last update"),a.column(),a.updatedAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),n.__decorate([o.description("Stores the version of the model"),a.column(),r.version(),n.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=n.__decorate([o.uses(P),n.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},n.__decorate([o.description("Stores the creator"),a.column(),a.createdBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),n.__decorate([o.description("Stores the user that last updated the model"),a.column(),a.updatedBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=n.__decorate([o.uses(P),n.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),t.Model.prototype.isShared=function(){return t.Model.isShared(this.constructor)},t.Model.prototype.isPrivate=function(){return t.Model.isPrivate(this.constructor)},t.Model.prototype.segregate=function(){return t.Model.segregate(this)},t.Model.segregate=(i=>{if(!t.Model.isTransient(i))return{model:i};const a=o.Metadata.getAttributes(i.constructor)||[],n=o.Metadata.get(i.constructor,r.DBKeys.TRANSIENT),s=o.Metadata.get(i.constructor,e.FabricModelKeys.PRIVATE),c=o.Metadata.get(i.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(n||{}),u=Object.keys(s||{}),h=Object.keys(c||{});for(const e of a){const t=i[e],r=d.includes(e),a=!r,n=u.includes(e),o=h.includes(e);(r||n||o)&&(l.transient=l.transient||{},l.transient[e]=t),n&&(l.privates=l.privates||{},l.privates[e]=t),o&&(l.shared=l.shared||{},l.shared[e]=t),a&&(l.public=l.public||{},l.public[e]=t)}return l.model=t.Model.build(l.public,i.constructor.name),l}).bind(t.Model),t.Model.isPrivate=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(t.Model),t.Model.isShared=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(t.Model),t.Model.mirrored=(t=>o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(t.Model),t.Model.ownerOf=(t=>{const r=o.Metadata.get(t.constructor,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(t.Model),t.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,o.Metadata.get(t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(t.Model),t.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=o.Metadata.key(...r),n=o.Metadata.key(...i),s="function"==typeof t?t:t.constructor,c=o.Metadata.get(s,a),l=o.Metadata.get(s,n);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(t.Model);const we=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0);if(!a)throw new r.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function be(i,a,n){a.length>0&&n.readFrom(a),!n.isFullySegregated&&a.length&&((i=>{const a=o.Metadata.getAttributes(i)||[],n=t.Model.pk(i),s=o.Metadata.get(i,r.DBKeys.TRANSIENT)||{},c=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.PRIVATE))||{},l=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.SHARED))||{};return a.some(e=>e!==n&&!(e in s)&&!(e in c)&&!(e in l))})(i.constructor)||n.markFullySegregated())}async function Ce(e,r,i,a){const n=Array.isArray(r)?r:[r],o=t.Model.ownerOf(a)||le(e.get("identity"));if(!o)return;const s=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(a,o,e);i&&!s.includes(i)&&s.push(i)}be(a,s,e);const c=t.Model.sequenceName(a,"pk");e.setSequenceSegregation(c,e.isFullySegregated,s)}async function Ee(e,i,n,o){const s=Array.isArray(i)?i:[i],c=Array.isArray(n)?n:[n];if(c.length!==s.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const l=t.Model.ownerOf(o)||le(e.get("identity"));if(!l)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const d=s[0].collections,u="string"==typeof d?d:d(o,l,e);c.forEach((t,r)=>{const i="string"==typeof s[r].collections?s[r].collections:s[r].collections(o,l,e);if(i!==u)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function Ae(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=t.Model.ownerOf(n)||le(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:await c(n,s,e);e.readFrom(l)}async function ve(e,i,n,o,s){const c=Array.isArray(i)?i:[i],l=Array.isArray(n)?n:[n];if(l.length!==c.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const d=t.Model.ownerOf(o)||le(e.get("identity"));if(!d)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(o,d,e);l.forEach((t,r)=>{const i="string"==typeof c[r].collections?c[r].collections:c[r].collections(o,d,e);if(i!==h)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function Se(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=t.Model.ownerOf(n)||le(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:c(n,s,e);e.readFrom(l)}function Oe(e,t,i){return(i,a)=>{const n=[];if(!a){const r=o.Metadata.getAttributes(i);return r?.forEach(r=>{Oe(e,t)(i.prototype,r)}),i}{const i="string"==typeof e?e:e.toString(),a=i+":data",s={collections:e},c={priority:35,group:i+":extract"};n.push(o.prop(),r.transient(),(i,a)=>{const n=o.Metadata.key(t,a),s=i.constructor,c=o.Metadata.get(s,n)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],o.Metadata.set(s,n,c);const d=o.Metadata.get(s,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],o.Metadata.set(s,t,d);const h={...o.Metadata.get(s,r.DBKeys.TRANSIENT)||{},[a]:{}};o.Metadata.set(s,r.DBKeys.TRANSIENT,h)},r.on(r.DBOperations.ALL,Ce,s,c),r.onCreate(Ee,{collections:e},{priority:95,group:a}),r.onRead(Ae,{collections:e},{priority:95,group:a}),r.onUpdate(ve,{collections:e},{priority:95,group:a}),r.onDelete(Se,{collections:e},{priority:95,group:a}))}return o.apply(...n)(i,a)}}function Ie(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(Ie):e.constructor!==Object?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Ie(e[r]),t),{})}class Me extends t.JSONSerializer{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=o.Metadata.modelName(e.constructor)}catch(e){i=void 0}r[t.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 t.Model.relations(e).forEach(e=>{r[e]=a(r[e])}),r}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e){return require("json-stringify-deterministic")(Ie(this.preSerialize(e)))}}function _e(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 xe extends t.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(Ie(this.preSerialize(e,t)))}preSerialize(e,r=!0){const i=Object.assign({},e);let a;try{a=o.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 r&&(i[t.ModelKeys.ANCHOR]=a||e.constructor.name),t.Model.relations(e).forEach(e=>{i[e]=n.call(this,i[e])}),i}}class Ne extends a.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new r.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 i=t.logger.for(this.getUser),{caName:a,caCert:n,caKey:o,url:s,hsm:c}=e;i.info(`Creating CA user for ${a} at ${s}`),i.verbose("Retrieving CA certificate from "+n);const l=await $.getFirstDirFileNameContent(n);let d;if(c)i.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!o)throw new r.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);i.debug("Retrieving CA key from "+o),d=await $.getFirstDirFileNameContent(o)}return i.debug("Loading Admin user for ca "+a),this._user=await $.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:i}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[n]=e;if(!n)throw new r.InternalError("Missing Fabric CA configuration");const{url:o,tls:c,caName:l}=n;t.info(`Initializing CA Client for CA ${n.caName} at ${n.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];t.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await $.getFileContent(h);t.debug("CA Certificate: "+g.toString());const p=new s(o,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(n,i);return t.debug("CA user loaded: "+f.getName()),{config:n,client:p}}async getCertificates(e,t=!0,...i){e instanceof a.Context?(i=[e],t=!0,e=void 0):"boolean"==typeof e?(t=e,e=void 0):"boolean"!=typeof t&&(i=[t,...i],t=!0);const{log:n}=(await this.logCtx(i,r.OperationKeys.READ,!0)).for(this.getCertificates);n.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const o=(await this.certificates.getCertificates(e||{},this.user)).result;return n.verbose(`Found ${o.certs.length} certificates`),n.debug(o.certs),t?o.certs.map(e=>e.PEM):o}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 t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new J(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new J(n)}}async read(e,...t){const{log:i}=(await this.logCtx(t,r.OperationKeys.READ,!0)).for(this.read);let a;i.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n,...o){const{log:s}=(await this.logCtx(o,"register",!0)).for(this.register);let c;try{const{userName:o,password:l}=e,d={enrollmentID:o,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};c=await this.client.register(d,this.user),s.info(`Registration for ${o} 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:o,rootCertificate:s}=t;a.verbose(`Generating Identity from certificate ${n} in msp ${r}`);const c=G.fabricIdFromCertificate(n),l=G.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:n,privateKey:o.toBytes(),rootCertificate:s},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});n=Ne.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,...o){const{ctx:s}=(await this.logCtx(o,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,n,s),{userName:l}=e;return this.enroll(l,c,s)}async updateIdentity(e,t,r,...i){const{log:a,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const o=this.client.newIdentityService(),s=await o.getOne(e,this.user);await o.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(s.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=Ne.identityFromEnrollment(u,this.config.caName,n);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=B(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...i){const{log:a}=(await this.logCtx(i,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const n=await this.read(e);if(!n)throw new r.NotFoundError("Could not find enrollment with id "+e);let o;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:n.id};o=await this.client.revoke(e,this.user)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!o.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${o.errors.join("\n")}`);return o}}var Te;e.CA_ROLE=void 0,(Te=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",Te.USER="user",Te.CLIENT="client";const Fe=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Re=new c.MiniLogger("fabric-fs");async function De(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Pe(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}async function $e(e,t){return{mspId:e,credentials:await De(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Be(e);return await t.readFile(r)})}}async function Be(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}async function ke(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}async function Ke(e){const t=await De(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Be(e);return await t.readFile(r)}),r=await Le(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}async function Le(e){let t;if(c.isBrowser())t=globalThis.crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const i=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(i,"base64").toString("binary"));try{return await t.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new r.InternalError(e)}}function ze(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class je extends a.Statement{constructor(e,t){super(e,t)}squash(e){const t=super.squash(e);if(!t)return t;const{method:i,params:n,args:o}=t,{direction:s,limit:c}=n;switch(i){case a.PreparedStatementKeys.FIND:break;case a.PreparedStatementKeys.PAGE:o.push(s,c);break;case a.PreparedStatementKeys.FIND_BY:break;case a.PreparedStatementKeys.LIST_BY:o.push(s);break;case a.PreparedStatementKeys.PAGE_BY:o.push(s,c);break;case a.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new r.InternalError("Unsupported method "+i)}return t}async executePrepared(...e){const t=a.Repository.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return t.statement(r,...i,...e)}async prepare(e){if(e=e||await this.adapter.context(a.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},i={class:this.fromSelector,args:t,params:r},n=[a.QueryClause.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);n.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&n.push(a.QueryClause.SELECT,this.selectSelector.join(` ${a.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(a.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),t.push(this.orderBySelectors[0][1])),i.method=c.toCamelCase(n.join(" ")),i.params=r,this.prepared=i,this}processRecord(e,t,r,n){if(e[i.CouchDBKeys.ID]){const[,...t]=e[i.CouchDBKeys.ID].split(i.CouchDBKeys.SEPARATOR),o=t.join("_");return this.adapter.revert(e,this.fromSelector,a.Sequence.parseValue(r,o),void 0,n)}return e}async raw(e,...i){const{ctx:a}=this.logCtx(i,this.raw),n=e?.aggregateInfo;if(e?.aggregate&&n)return this.executeAggregate(n,a);const s=await this.adapter.raw(e,!0,this.fromSelector,a),c=t.Model.pk(this.fromSelector),l=o.Metadata.get(this.fromSelector,o.Metadata.key(r.DBKeys.ID,c))?.type;return this.selectSelector?s:s.map(e=>this.processRecord(e,c,l,a))}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const n={};n[i.CouchDBKeys.TABLE]={},n[i.CouchDBKeys.TABLE]=t.Model.tableName(this.fromSelector);const o={selector:n};if(this.selectSelector&&(o.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(a.Condition.and(this.whereCondition,a.Condition.attribute(i.CouchDBKeys.TABLE).eq(o.selector[i.CouchDBKeys.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(i.CouchDBGroupOperator).indexOf(r[0]))switch(r[0]){case i.CouchDBGroupOperator.AND:t[i.CouchDBGroupOperator.AND]=[...Object.values(t[i.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const a=r[0];return a===i.CouchDBGroupOperator.AND?e.push(...t[a]):e.push(t),e},[])],o.selector=t;break;case i.CouchDBGroupOperator.OR:{const e={};e[i.CouchDBGroupOperator.AND]=[t,...Object.entries(o.selector).map(([e,t])=>{const r={};return r[e]=t,r})],o.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{o.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${o.selector[t]} by ${r}`),o.selector[t]=r})}if(this.orderBySelectors?.length){o.sort=o.sort||[],o.selector=o.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,a={};a[r]=t,o.sort.push(a),o.selector[r]||(o.selector[r]={},o.selector[r][i.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?o.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+i.CouchDBQueryLimit),o.limit=i.CouchDBQueryLimit),this.offsetSelector&&(o.skip=this.offsetSelector),o}parseCondition(e){const{attr1:t,operator:r,comparison:n}=e;if(r===a.Operator.STARTS_WITH){if("string"!=typeof t)throw new a.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("STARTS_WITH requires a string comparison");const e={start:o=n,end:ze(o)},r={};return r[t]={},r[t][i.CouchDBOperator.BIGGER_EQ]=e.start,r[t][i.CouchDBOperator.SMALLER]=e.end,{selector:r}}var o,s;if(r===a.Operator.ENDS_WITH){if("string"!=typeof t)throw new a.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("ENDS_WITH requires a string comparison");const e={};return e[t]={[i.CouchDBOperator.REGEXP]:(s=n,s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(r===a.Operator.BETWEEN){const e=t;if(!Array.isArray(n)||2!==n.length)throw new a.QueryError("BETWEEN operator requires [min, max] comparison");const[r,o]=n,s={};return s[e]={},s[e][i.translateOperators(a.Operator.BIGGER_EQ)]=r,s[e][i.translateOperators(a.Operator.SMALLER_EQ)]=o,{selector:s}}let c={};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(r))c[t]={},c[t][i.translateOperators(r)]=n;else if(r===a.Operator.NOT)c=this.parseCondition(t).selector,c[i.translateOperators(a.Operator.NOT)]={},c[i.translateOperators(a.Operator.NOT)][t.attr1]=n;else{const e=this.parseCondition(t).selector,a=this.parseCondition(n).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(i.translateOperators(r),e,a).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",t=this.createAggregateDescriptor("sum",e),r=this.createAggregateDescriptor("count",e);if(!t||!r)throw new a.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:t.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of r){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new a.QueryError(`No CouchDB view metadata found for table ${t.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const a=i.findViewMetadata(this.fromSelector,e,r);if(!a.length)return;const n=a[0],o=t.Model.tableName(this.fromSelector),s=i.generateViewName(o,n.attribute,e,n),c=n.ddoc||i.generateDesignDocName(o,s),l={reduce:void 0!==n.reduce||!n.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:n,descriptor:{ddoc:c,view:s,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,t){if("avg"!==e.kind)throw new a.QueryError("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,n]=[e.sumDescriptor,e.countDescriptor],[o,s]=await Promise.all([r.view(i.ddoc,i.view,i.options,t),r.view(n.ddoc,n.view,n.options,t)]),c=o.rows?.[0]?.value??0,l=s.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,t){if("avg"===e.kind)throw new a.QueryError("Average results should be handled before processing rows");const r=t.rows||[],i=e,n=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(e=>e.key??e.value):n.returnDocs?r.map(e=>e.value??e.doc??e):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}class Ue extends a.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new a.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 He;class Ge extends a.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new N}static{this.log=c.Logging.for(Ge)}constructor(e,t){super(Object.assign({},Fe,e),P,t),this.serializer=Ge.serializer}Statement(e){return new je(this,e)}Paginator(e,t,r){return new Ue(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,r,i,...n){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.Model.tableName(e)):t.Model.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let o=n.pop();void 0===o||o instanceof a.Context||(n.push(o),o=void 0),r=o?Object.assign({},o.toOverrides(),r):r;const s=await this.flags("string"==typeof e?e:e.name,i,r,...[...n,o].filter(Boolean));if(o){if(!(o instanceof this.Context)){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}const t=o.getOrUndefined("operation"),r=o.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}return o.accumulate(s)}return(new this.Context).accumulate({...s})}decode(e){return Ge.decoder.decode(e)}repository(){return I}createPrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.createPrefix),s=t.Model.tableName(e),c={};return c[i.CouchDBKeys.TABLE]=s,Object.assign(c,a),[e,r,c,...o]}createAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.createAllPrefix),l=a.map((e,t)=>{const r={};return r[i.CouchDBKeys.TABLE]=s,Object.assign(r,n[t]),r});return[e,a,l,...c]}updateAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.updateAllPrefix),l=a.map(()=>{const e={};return e[i.CouchDBKeys.TABLE]=s,e});return[e,a,l,...c]}async createAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.createAll),d=t.Model.tableName(e);c.info(`adding ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:s}:{},p=await this.submitTransaction(l,r.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],g,this.getEndorsingOrganizations(l),e.name);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,f[0][t.Model.pk(e)]||i[0])?this.readAll(e,F(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s[r]||{}),f[r])),i),l):f}async readAll(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.readAll),s=t.Model.tableName(e);n.info(`reading ${i.length} entries to ${s} table`),n.verbose("pks: "+i);const c=await this.evaluateTransaction(o,r.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(i)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}async updateAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.updateAll),d=t.Model.tableName(e);c.info(`updating ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:s}:{},p=await this.submitTransaction(l,r.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],g,this.getEndorsingOrganizations(l),e.name);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,i[0])?this.readAll(e,F(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s[r]||{}),f[r])),i),l):f}async deleteAll(e,i,...a){const{log:n,ctx:o,ctxArgs:s}=this.logCtx(a,this.deleteAll),c=t.Model.tableName(e),l=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let d;const u=this.shouldRefreshAfterWrite(e,o,l,i[0]);u&&(d=await this.readAll(e,i,...s)),n.info(`deleting ${i.length} entries to ${c} table`),n.verbose("pks: "+i);const h=await this.submitTransaction(o,r.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(i)],void 0,this.getEndorsingOrganizations(o),e.name);try{return u?d:JSON.parse(this.decode(h)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}prepare(e,...i){const{log:n,ctx:o}=this.logCtx(i,this.prepare),s=t.Model.segregate(e);e[a.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+e[a.PersistenceKeys.METADATA]),Object.defineProperty(s.model,a.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[a.PersistenceKeys.METADATA]}));const c=t.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new r.InternalError("No mirror MSP could be found");const t=this.getEndorsingOrganizations(o)||[],i=[...new Set([...t,e])];o.accumulate({endorsingOrgs:i,endorsingOrganizations:i,legacy:!0})}return{record:s.model,model:s.model,id:e[t.Model.pk(e.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(e,t,r,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(o,o.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&n.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,a){if(!i)return!1;const n=t.Model.pk(e),o=t.Model.composed(e,n),s=t.Model.generated(e,n),c=null!=a;return!(c||!o)||(!c&&s?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(e){return!!this.config.allowGatewayOverride}async create(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.create),d=t.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:n}:{},p=await this.submitTransaction(l,r.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],g,this.getEndorsingOrganizations(l),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,F(e,t.Model.merge(Object.assign({},a,n||{}),f,e),i),l):f}async healthcheck(e,...r){const{log:i,ctx:a}=this.logCtx(r,this.healthcheck),n=t.Model.tableName(e);i.verbose(`reading entry from ${n} table`);const o=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(o))}async read(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.read),s=t.Model.tableName(e);n.verbose(`reading entry from ${s} table`),n.debug("pk: "+i);const c=await this.evaluateTransaction(o,r.OperationKeys.READ,[i.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,r,a,...n){const o=t.Model.tableName(e),{ctxArgs:s}=this.logCtx(n,this.updatePrefix),c={};return c[i.CouchDBKeys.TABLE]=o,Object.assign(c,a),[e,r,c,...s]}async update(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=t.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:n}:{},p=await this.submitTransaction(l,r.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],g,this.getEndorsingOrganizations(l),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,F(e,t.Model.merge(Object.assign({},a,n||{}),f,e),i),l):f}async delete(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.delete),s=t.Model.tableName(e),c=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let l;const d=this.shouldRefreshAfterWrite(e,o,c,i);d&&(l=await this.read(e,i,o)),n.verbose(`deleting entry from ${s} table`),n.debug("pk: "+i);const u=await this.submitTransaction(o,r.OperationKeys.DELETE,[i.toString()],void 0,this.getEndorsingOrganizations(o),e.name);return d?l:this.serializer.deserialize(this.decode(u))}async raw(e,i=!0,a,...n){const{log:o,ctx:s}=this.logCtx(n,this.raw),c=a.name;let l,d;o.info("Performing raw statement on table "+t.Model.tableName(a));try{l=await this.evaluateTransaction(s,"raw",[JSON.stringify(e),i],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new r.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return t.Model.isModel(e)?d.map(e=>t.Model.build(e)):d}return u=d,t.Model.isModel(u)?t.Model.build(u):u;var u}async view(e,t,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.view);let s,c;n.info(`Querying view ${e}/${t}`);try{s=await this.evaluateTransaction(o,"view",[e,t,JSON.stringify(i)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(s))}catch(e){throw new r.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Ge.getClient(this.config)),this._client}async Gateway(e){return Ge.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return Ge.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a={},n,o){const s=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(o));s.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(o)||this.config.contractName}.${t}`),s.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:Object.entries(a).reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}),endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,t,d)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(e){const t=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}],r=(this.getEndorsingOrganizations(e)?.filter(e=>!!e)||[]).filter(e=>e!==this.config.mspId);if(!r.length)return t;const i=this.config.mspMap;for(const e of r){const r=i?.[e];if(!r?.length)throw new a.UnsupportedError(`No peer mapping available for MSP ${e}. Provide it via config.mspMap`);const n=r[Math.floor(Math.random()*r.length)];if(!n.endpoint)throw new a.UnsupportedError(`Invalid peer mapping for MSP ${e}: missing endpoint`);t.push({mspId:e,peerEndpoint:n.endpoint,peerHostAlias:n.alias,tlsCert:n.tlsCert||this.config.tlsCert})}return t}async submitLegacyWithExplicitEndorsers(e,t,r,i,a,n){const o=this.log.for(this.submitLegacyWithExplicitEndorsers),s=this.normalizeLegacyPeers(a),c=await this.resolveLegacyIdentityMaterial(),l=await f.Wallets.newInMemoryWallet(),d=this.config.mspId+"-legacy";await l.put(d,{credentials:{certificate:c.certificate,privateKey:c.privateKey},mspId:this.config.mspId,type:"X.509"});const u=await this.buildLegacyConnectionProfile(s),h=new f.Gateway;try{await h.connect(u,{identity:d,wallet:l,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(s)},tlsInfo:{certificate:c.certificate,key:c.privateKey}});const e=await h.getNetwork(this.config.channel),a=e.getContract(this.config.chaincodeName,this.getContractName(n)).createTransaction(t);i&&a.setTransient(i);const g=s.map(t=>e.getChannel().getEndorser(t.name)).filter(e=>!!e);g.length&&a.setEndorsingPeers(g),o.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${t} via peers ${s.map(e=>e.peerEndpoint).join(", ")}`);const p=await a.submit(...r);return Uint8Array.from(p)}catch(e){throw this.parseError(e)}finally{h.disconnect()}}normalizeLegacyPeers(e){const t=new Map,r=e=>{const r=`${e.peerEndpoint}|${e.peerHostAlias||""}`;if(t.has(r))return;const i=`peer-${e.mspId}-${t.size}`;t.set(r,{...e,name:i})};return e.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(t.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(e){const t={},r={},i={};for(const a of e){const e=await this.readPemInput(a.tlsCert||this.config.tlsCert),n=a.peerHostAlias||this.extractHost(a.peerEndpoint);t[a.name]={url:this.ensureGrpcUrl(a.peerEndpoint),tlsCACerts:{pem:e},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[a.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[a.mspId]=i[a.mspId]||{mspid:a.mspId,peers:[]},i[a.mspId].peers.push(a.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:t,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(e){return e.every(e=>this.isLocalEndpoint(e.peerEndpoint))}isLocalEndpoint(e){const t=this.extractHost(e).toLowerCase();return"localhost"===t||"127.0.0.1"===t}extractHost(e){return e.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(e){return/^grpcs?:\/\//i.test(e)?e:"grpcs://"+e}async readPemInput(e){if(!e)throw new r.InternalError("Missing certificate or key material");if(Buffer.isBuffer(e))return e.toString("utf8");const t=e.trim();if(/-----BEGIN [A-Z ]+-----/.test(t))return t;const i=await m.promises.stat(e).catch(()=>{});return i?.isDirectory()?await ke(e):(await Pe(e)).toString()}parseError(e){return Ge.parseError(e)}async submitTransaction(e,t,r,i,a,n){if(this.shouldUseLegacyGateway(e)){const a=this.prepareLegacyArgs(r),o=this.buildLegacyTransient(i),s=this.buildLegacyPeerConfigs(e);return this.submitLegacyWithExplicitEndorsers(e,t,a,o,s,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 i=e.tlsCert;if("string"==typeof i)if(i.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))i=Buffer.from(i,"utf8");else try{i=Buffer.from(m.readFileSync(i,"utf8"))}catch(e){throw new r.InternalError(`Failed to read the tls certificate from ${i}: ${e}`)}const a=b.credentials.createSsl(i);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.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 n=await $e(t.mspId,t.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+G.fabricIdFromCertificate(n.credentials.toString()))}catch(e){i.error("Failed to extract Fabric ID from certificate",e)}let o;if(t.hsm)throw new a.UnsupportedError("HSM NOT IMPLEMENTED");o=await Ke(t.keyCertOrDirectoryPath);const s={client:e,identity:n,signer:o,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(s);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Ge._baseDispatch}static parseError(e){let t="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(t=""+e.details[0].message),t.includes("MVCC_READ_CONFLICT")?new te(e):t.includes("DEADLINE_EXCEEDED")?new ne(e):t.includes("ENDORSEMENT_POLICY_FAILURE")?new ie(e):t.includes("PHANTOM_READ_CONFLICT")?new re(e):e instanceof Error&&e.code&&9===e.code?new ee(e):t.includes(r.ValidationError.name)?new r.ValidationError(e):t.includes(r.NotFoundError.name)?new r.NotFoundError(e):t.includes(r.ConflictError.name)?new r.ConflictError(e):t.includes(r.BadRequestError.name)?new r.BadRequestError(e):t.includes(a.QueryError.name)?new a.QueryError(e):t.includes(a.PagingError.name)?new a.PagingError(e):t.includes(a.UnsupportedError.name)?new a.UnsupportedError(e):t.includes(a.MigrationError.name)?new a.MigrationError(e):t.includes(a.ObserverError.name)?new a.ObserverError(e):t.includes(a.AuthorizationError.name)?new a.AuthorizationError(e):t.includes(a.ForbiddenError.name)?new a.ForbiddenError(e):t.includes(a.ConnectionError.name)?new a.ConnectionError(e):t.includes(r.SerializationError.name)?new r.SerializationError(e):new r.InternalError(e)}}n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"create",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"healthcheck",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"read",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"update",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"delete",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,"function"==typeof(He="undefined"!=typeof D&&D)?He:Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"raw",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String,String,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"view",null),Ge.decoration(),a.Adapter.setCurrent(P);class qe extends a.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 Ge))throw new a.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,i,n,...o){const{log:s,ctxArgs:c}=a.Adapter.logCtx(this.updateObservers,i,!1,...o);if(this.adapter)try{await this.adapter.refresh(e,i,n,...c)}catch(e){throw new r.InternalError("Failed to refresh dispatch: "+e)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.Model.tableName(e)}:${i}`)}async handleEvents(e){if(!this.listeningStack)throw new r.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new r.InternalError("No adapter found. should be impossible");const i=e||await this.adapter.context(r.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t.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:r,event:n,owner:o}=_e(e.eventName);if(o&&o!==this.adapter.config?.mspId)continue;const s=this.parsePayload(e.payload);try{const e=(r?t.Model.get(r):t.Model.get(this.models[0].name))??(r||this.models[0]?.name);await this.updateObservers(e,n,s.id,i)}catch(e){a.error(`Failed update observables for table ${r} event ${n} id: ${s.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 r.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t.Model),{ctx:i}=this.logCtx([e],this.initialize),a=(await Ge.getGateway(i,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new r.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(i)}}Ge&&(Ge._baseDispatch=qe);const Ve="##VERSION##",Ye="##PACKAGE##";o.Metadata.registerLibrary(Ye,Ve),e.AllowanceError=Y,e.BalanceError=V,e.BaseEncoder=H,e.ClientSerializer=N,e.CoreUtils=$,e.CryptoUtils=G,e.DefaultFabricClientFlags=Fe,e.DeterministicSerializer=Me,e.EndorsementError=ee,e.EndorsementPolicyError=ie,e.FabricClientAdapter=Ge,e.FabricClientDispatch=qe,e.FabricClientRepository=I,e.FabricERC20ClientRepository=T,e.FabricEnrollmentService=se,e.FabricFlavour=P,e.FabricIdentityService=Ne,e.ImplicitPrivateCollection=we,e.MissingContextError=W,e.MissingPKCSS11Lib=Z,e.ModelCollection=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!a)throw new r.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(n.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=te,e.NamespaceCollection=e=>(i,a)=>{const n=a||("function"!=typeof i?t.Model.ownerOf(i):void 0),o="function"==typeof i?i:i.constructor;if(!n)throw new r.InternalError(`Model ${o.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${n?c.toPascalCase(n):""}`},e.NotInitializedError=X,e.OverflowError=q,e.Owner=function(){return function(e,t,i){const n=i.value;return i.value=async function(...e){const i=e[0],o=i.clientIdentity.getID(),s=await this.tokenRepository.select(),c=await s.execute(i);if(0==c.length)throw new r.NotFoundError("No tokens avaialble");if(c.length>1)throw new r.NotFoundError("To many token available : "+c.length);if(c[0].owner!=o)throw new a.AuthorizationError(`User not authorized to run ${t} on the token`);return await n.apply(this,e)},i}},e.PACKAGE_NAME=Ye,e.PhantomReadConflictError=re,e.RegistrationError=J,e.RegistrationRequestBuilder=ce,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=xe,e.TransactionBufferSizeError=oe,e.TransactionLimitsError=ae,e.TransactionTimeoutError=ne,e.UnauthorizedPrivateDataAccess=Q,e.VERSION=Ve,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new q(`Addition overflow: ${e} + ${t}`);return r},e.applyMirrorFlags=async(e,r,i)=>{if(!r)return;const a=t.Model.mirroredAt(e);if(!a)return;if(!(r===a.mspId||a.condition&&a.condition(r)))return;const n=await he(new e,a.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)},e.applySegregationFlags=be,e.collectionFor=v,e.contentOfLoadFile=De,e.createMirrorHandler=ge,e.deleteMirrorHandler=fe,e.evalMirrorMetadata=he,e.extractCollections=async(e,i,a={},n=!1)=>{let{privateCols:o,sharedCols:s}=t.Model.collectionsFor(e);function c(t){try{return"string"==typeof t?t:t(e,i[0])}catch(e){throw new r.InternalError(e)}}o=o.map(c),s=s.map(c);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.sharedCols||{}),u=n?t.Model.mirroredAt(e):void 0,h=i.map(e=>o.map(t=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n}=l;return S(e,t,r,i,a,n,!1)})).flat();if(u&&u.mspId){const t="string"==typeof u.resolver?u.resolver:u.resolver(e,u.mspId);if(t&&!h.some(e=>e.name===t&&e.policy.includes(u.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:a}=l;h.push(S(u.mspId,t,e,r,i,a,!1))}}return{privates:h,shared:s.map(e=>{const{requiredPeerCount:t,maxPeerCount:r,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}=d;return O(i,e,t,r,a,n,o)})}},e.extractIds=F,e.extractMspId=le,e.extractPrivateKey=Le,e.extractSegregatedCollections=Ce,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=i.generateViews([e]),a=t||{};return r.forEach(e=>{a[e._id]=e}),r},e.generateModelIndexes=e=>i.generateIndexes([e]),e.getAkiAndSerialFromCert=B,e.getCAUser=async(e,t,r,i)=>{Re.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),n=d.User.newCryptoSuite();a.setCryptoSuite(n);const o=n.createKeyFromRaw(t);return await a.setEnrollment(o,r,i),a},e.getFirstDirFileName=Be,e.getFirstDirFileNameContent=ke,e.getIdentity=$e,e.getSigner=Ke,e.mirror=(t,i,a)=>{const n="string"!=typeof i&&!!i,s=n?void 0:i,c=n?i:a;return o.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,i,a)=>{const n={condition:a,mspId:i,resolver:t};return o.apply(o.metadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),n),r.onRead(ye,n,{priority:30}),r.onCreate(me,n,{priority:20}),r.onUpdate(me,n,{priority:20}),r.onDelete(me,n,{priority:20}),r.onCreate(ge,n,{priority:100}),r.onUpdate(pe,n,{priority:100}),r.onDelete(fe,n,{priority:100}))},args:[t,s,c]}).apply()},e.mirrorWriteGuard=me,e.ownedBy=()=>o.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(i,a)=>o.apply(t.required(),r.generated(),r.readonly(),r.onCreate(de),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(i,a),args:[]}).apply(),e.ownedByOnCreate=de,e.parseEventName=_e,e.privateCollectionFor=S,e.privateData=(t=we)=>o.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>Oe(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=Pe,e.readMirrorHandler=ye,e.readModelFile=E,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(...E(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string contains digits"));const i=parseInt(e);if(isNaN(i))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return i},e.segregatedDataOnCreate=Ee,e.segregatedDataOnDelete=Se,e.segregatedDataOnRead=Ae,e.segregatedDataOnUpdate=ve,e.sharedCollectionFor=O,e.sharedData=t=>o.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>Oe(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sortKeysOnlyRecursive=Ie,e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new q(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>o.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(i,a)=>o.apply(t.required(),r.readonly(),r.onCreate(ue),r.onUpdate(ue),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(i,a),args:[]}).apply(),e.transactionIdOnCreate=ue,e.updateMirrorHandler=pe,e.writeCollectionDesignDocs=(e,t=process.cwd(),r)=>{e?.length&&A(e,t,r)},e.writeCollections=(e,t=process.cwd(),r="collections_config")=>{const i=require("fs"),a=require("path"),n=a.resolve(a.join(t,`./META-INF/${r}.json`));!function e(t){const r=a.dirname(t);if(i.existsSync(r))return!0;e(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))},e.writeDesignDocs=A,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));C(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("@decaf-ts/core"),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("fabric-network"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","@decaf-ts/core","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fabric-network","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.decafTsCore,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fabricNetwork,e.fs);
1
+ var e,t;e=this,t=function(e,t,r,i,a,n,o,s,c,l,d,u,h,g,p,f,m){"use strict";function y(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 w=y(h),b=y(p);function C(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;C(r),t.mkdirSync(r)}function E(e){const r=require("path"),i=require(r.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof t.Model}catch(e){return!1}})}function A(e,t=process.cwd(),r){if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const n=e._id.replace(/^_design\//,""),o=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));C(o);const s={...e};delete s._rev,i.writeFileSync(o,JSON.stringify(s,void 0,2))})}function v(e,t,r,i,a,n,o){return{name:e,policy:t,requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}}function S(e,t=e+"Private",r=0,i=0,a=0,n=!0,o=!0){const s=v(t,`OR('${e}.member')`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`OR('${e}.peer')`},s}function O(e,t,r=1,i=2,a=0,n=!0,o=!0){const s=v(t,`OR(${e.map(e=>`'${e}.member'`).join(",")})`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`AND(${e.map(e=>`'${e}.peer'`).join(",")})`},s}class I extends a.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,rebuildWithTransient:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return o.verbose(`paginating ${t.Model.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...s)}async listBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return n.verbose(`listing ${t.Model.tableName(this.class)} by ${e} ${r}`),await this.statement(this.listBy.name,e,r,...o)}async findBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...o)}async findOneBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...o)}async find(e,r=a.OrderDirection.ASC,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...o)}async page(e,r=a.OrderDirection.ASC,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE,!0)).for(this.page);return o.verbose(`paging ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...s)}async statement(e,...r){const{log:n,ctx:o,ctxArgs:s}=(await this.logCtx(r,a.PersistenceKeys.STATEMENT,!0)).for(this.statement);n.verbose("Executing prepared statement "+e);const c=s.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(o,a.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class.name)));return Array.isArray(l)?l.map(e=>e[i.CouchDBKeys.TABLE]&&e[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(e):e):l[i.CouchDBKeys.TABLE]&&l[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(l):a.Paginator.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l}async countOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.Model.tableName(this.class)}${e?" by "+e:""}`);const o=e?[e,...n]:n;return this.statement(a.PreparedStatementKeys.COUNT_OF,...o)}async maxOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MAX_OF,e,...n)}async minOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MIN_OF,e,...n)}async avgOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.AVG_OF,e,...n)}async sumOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.SUM_OF,e,...n)}async distinctOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.DISTINCT_OF,e,...n)}async groupOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.Model.tableName(this.class)} by ${e}`),this.statement(a.PreparedStatementKeys.GROUP_OF,e,...n)}async healthcheck(...e){const{ctxArgs:t}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...t)}async create(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.create);a.debug(`Creating new ${this.class.name} in table ${t.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const o=this.adapter.prepare(e,i),{record:s,id:c,transient:l}=o,d=await this.adapter.create(this.class,c,s,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:a,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const o=this.adapter.prepare(e,n),{id:s,transient:c}=o;let l=o.record;return a.debug(`updating ${this.class.name} in table ${t.Model.tableName(this.class)} with id ${s}`),l=await this.adapter.update(this.class,s,l,c,...i),this.adapter.revert(l,this.class,s,c,n)}async createAllPrefix(e,...t){const{ctx:i,ctxArgs:a}=(await this.logCtx(t,r.OperationKeys.CREATE,!0)).for(this.createAllPrefix),n=i.get("ignoreHandlers"),o=i.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),n||await r.enforceDBDecorators(this,i,e,r.OperationKeys.CREATE,r.OperationKeys.ON),e))),!o){const t=i.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=r.reduceErrorsToPrint(a);if(n)throw new r.ValidationError(n)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=o.map(e=>e.record),l=o.map(e=>e.transient),d=await this.adapter.createAll(this.class,s,c,l,...n);return Promise.all(d.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,l[t],i)}))}async updateAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=await this.adapter.updateAll(this.class,s,o.map(e=>e.record),o.map(e=>e.transient),...n);return Promise.all(c.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,o[t].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.Model.mirroredAt(r)&&e.accumulate({legacy:!0})}}let M=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],M.prototype,"name",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],M.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],M.prototype,"symbol",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],M.prototype,"decimals",void 0),M=n.__decorate([a.table("erc20_tokens"),t.model(),n.__metadata("design:paramtypes",[Object])],M);let _=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],_.prototype,"id",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],_.prototype,"token",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],_.prototype,"balance",void 0),n.__decorate([a.column(),n.__metadata("design:type",String)],_.prototype,"captive",void 0),_=n.__decorate([a.table("erc20_wallets"),t.model(),n.__metadata("design:paramtypes",[Object])],_);let x=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),a.column(),t.required(),n.__metadata("design:type",String)],x.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],x.prototype,"spender",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],x.prototype,"value",void 0),x=n.__decorate([a.table("erc20_allowances"),t.model(),n.__metadata("design:paramtypes",[Object])],x);class N extends t.JSONSerializer{constructor(){super()}preSerialize(e,i){const a=Object.assign({},e);let n=o.Metadata.modelName(e.constructor);if(!n||"Object"===n){if(!i)throw new r.SerializationError("Could not find metadata for "+e.constructor.name);n=i}return a[t.ModelKeys.ANCHOR]=n,a}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class T extends I{static{this.serializer=new N}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,i,n,...o){if(!this.observerHandler)throw new r.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:c}=this.logCtx(o,this.updateObservers);let l;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.Model.get(e):e,l=void 0===n?void 0:Array.isArray(n)?n.map(r=>a.Sequence.parseValue(t.Model.sequenceFor(e).type,r)):a.Sequence.parseValue(t.Model.sequenceFor(e).type,n),await this.observerHandler.updateObservers(e,i,l,...c)}decode(e){return T.decoder.decode(e)}constructor(e){super(e,_),this.serializer=T.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,t,r){const i=await a.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(i.args,this.transferFrom),o=await this.adapter.submitTransaction(n,"TransferFrom",[e,t,r.toString()]);return"true"===this.decode(o)}async approve(e,t){const r=await a.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),n=await this.adapter.submitTransaction(i,"Approve",[e,t.toString()]);return"true"===this.decode(n)}async allowance(e,t){const r=await a.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),n=await this.adapter.submitTransaction(i,"Allowance",[e,t]);return Number(this.decode(n))}async initialize(e){const t=await a.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[T.serializer.serialize(e)]);return"true"===this.decode(i)}async checkInitialized(){const e=await a.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(t,"CheckInitialized")}async mint(e){const t=await a.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[e.toString()])}async burn(e){const t=await a.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[e.toString()])}async burnFrom(e,t){const r=await a.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[e,t.toString()])}async clientAccountBalance(){const e=await a.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(t,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const e=await a.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(t,"ClientAccountID");return this.decode(r)}}function F(e,i,a){let n,o,s;function c(i,a){if(n=n||t.Model.pk(e),s=s||t.Model.sequenceFor(e),o=o||t.Model.composed(e,n),o)return r.composeAttributeValue(i,o);const c=i[n]||a;if(void 0===c)throw new r.InternalError("could not rebuild id for "+i.constructor.name);return c}if(Array.isArray(i)){if(!Array.isArray(a)||a.length!==i.length)throw new r.InternalError("inconsistent parameters. both must be arrays of equal length");return i.map((e,t)=>c(e,a[t]))}return c(i,a)}var R;e.IdentityCredentials=class extends a.BaseModel{constructor(e){super(e)}},n.__decorate([o.description("Unique identifier of the credentials record"),a.column(),a.pk(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),n.__decorate([o.description("PEM-encoded X.509 certificate for the identity"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),n.__decorate([o.description("PEM-encoded root or intermediate certificate"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),n.__decorate([o.description("PEM-encoded private key"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(R=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",R.SHARED="shared",R.FABRIC="fabric",R.OWNED_BY="owned-by",R.TRANSACTION_ID="transaction-id",R.MIRROR="mirror",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const P="hlf-fabric";e.Identity=class extends a.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},n.__decorate([o.description("Unique identifier of the identity"),a.pk(),n.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),n.__decorate([a.oneToOne(e.IdentityCredentials,{update:a.Cascade.CASCADE,delete:a.Cascade.CASCADE}),n.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),n.__decorate([a.column(),t.required(),a.index(),n.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.Identity);class ${static{this.logger=new c.MiniLogger($.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:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}static async getCAUser(e,r,i,a,n){this.logger.debug(t.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const o=new d.User(e),s=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(s);o.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,i,n.hsm):this.getSoftwareEnrollmentKey(c,r);return await o.setEnrollment(l,i,a),o}static getCryptoSuite(e){return e?($.cryptoSuite||($.cryptoSuite=d.User.newCryptoSuite(e)),$.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 u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,t){return{mspId:e,credentials:await this.contentOfLoadFile(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)})}}static async getFirstDirFileName(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}static async getFileContent(e){const{promises:t}=await a.normalizeImport(import("fs"));return(await t.readFile(e)).toString()}static async getSigner(e){const t=await this.contentOfLoadFile(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)}),r=await this.extractPrivateKey(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}static async extractPrivateKey(e){let t;if(globalThis.window&&globalThis.window.Crypto)t=globalThis.Crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(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(r,"base64").toString("binary"));return await t.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function B(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const k=new g.Crypto;var K,L,z,j,U;w.cryptoProvider.set(k),e.BASE_ALPHABET=void 0,(K=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",K.BASE8="01234567",K.BASE11="0123456789a",K.BASE16="0123456789abcdef",K.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",K.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",K.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",K.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",K.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",K.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",K.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(L=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",L[L.ITERATIONS=1e3]="ITERATIONS",L[L.KEYLENGTH=48]="KEYLENGTH",L[L.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",L[L.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",L.ALGORYTHM="AES-GCM",L.KEY_ALGORYTHM="PBKDF2";class H{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,o=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*o[e]>>>0,o[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let s=n-r;for(;s!==n&&0===o[s];)s++;let c=this.leader.repeat(t);for(;n>s;++s)c+=this.alphabet.charAt(o[s]);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 o=0;for(let e=a-1;(0!==r||i>o)&&-1!==e;e--,o++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=o,t++}let o=a-i;for(;o!==a&&0===n[o];)o++;const s=new Uint8Array(r+(a-o));let c=r;for(;o!==a;)s[c++]=n[o++];return s}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class G{static{this.b58encoder=new H(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(G.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(t.stringFormat("Parsing certificate: {0}",e));const r=new w.X509Certificate(e),{subject:i,issuer:a}=r;return this.logger.debug(t.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=k.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"),o=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",o,{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 k.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 w.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,k.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new w.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:k.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=k.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},o=await this.getSubtleCrypto().deriveBits(n,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(o)}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 q extends r.InternalError{constructor(e){super(e,q.name)}}class V extends r.InternalError{constructor(e){super(e,V.name)}}class Y extends r.InternalError{constructor(e){super(e,Y.name)}}class J extends a.AuthorizationError{constructor(e){super(e,J.name)}}class W extends r.InternalError{constructor(e){super(e,W.name,500)}}class Q extends r.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(Q.name,e,403)}}class X extends r.BaseError{constructor(e){super(X.name,e,409)}}class Z extends r.InternalError{constructor(e){super(e,Z.name,500)}}class ee extends r.InternalError{constructor(e){super(e,ee.name,500)}}class te extends r.InternalError{constructor(e){super(e,te.name,500)}}class re extends r.InternalError{constructor(e){super(e,re.name,500)}}class ie extends r.InternalError{constructor(e){super(e,ie.name,500)}}class ae extends r.InternalError{constructor(e,t=ae.name,r=590){super(e,t,r)}}class ne extends r.InternalError{constructor(e){super(e,ne.name,591)}}class oe extends r.InternalError{constructor(e){super(e,oe.name,592)}}e.HFCAIdentityType=void 0,(z=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",z.ORDERER="orderer",z.CLIENT="client",z.USER="user",z.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(j=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",j.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",j.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",j.HFINTERMEDIATECA="hf.IntermediateCA",j.HFREVOKER="hf.Revoker",j.HFAFFILIATIONMGR="hf.AffiliationMgr",j.HFGENCRL="hf.GenCRL";class se extends c.LoggedClass{constructor(e){$.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:i,url:a,hsm:n}=this.caConfig,o=this.log.for(this.User);o.debug(`Creating CA user for ${e} at ${a}`),o.debug("Retrieving CA certificate from "+t);const s=await $.getFirstDirFileNameContent(t);let c;if(n)o.debug(`Using HSM configuration for CA ${e} with library ${n.library}`);else{if(!i)throw new r.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);o.debug("Retrieving CA key from "+i),c=await $.getFirstDirFileNameContent(i)}return o.debug("Loading Admin user for ca "+e),this.user=await $.getCAUser("admin",c,s,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 o=a[0];e.debug(`Retrieving CA certificate from ${o}. cwd: ${process.cwd()}`);const c=await $.getFileContent(o);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new s(t,{trustedRoots:Buffer.from(c),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 t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new J(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new J(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(),i=await this.User();let a;try{a=await t.newIdentityService().getOne(e,i)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.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 o;const s=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};o=await d.register(h,u),s.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return o}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:n}=t,o=c.Logging.for(se,{}).for(this.identityFromEnrollment);o.debug(`Generating Identity from certificate ${i} in msp ${r}`);const s=G.fabricIdFromCertificate(i),l=G.encode(s);o.debug(`Identity ${s} 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=se.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 o=await this.register(e,t,r,i,a,n),{userName:s}=e;return this.enroll(s,o)}async revoke(e){const t=await this.CA(),i=await this.User(),a=await this.read(e);if(!a)throw new r.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},i)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}class ce extends t.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new r.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}}function le(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function de(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 ue(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function he(e,i,a){let n=i;if("string"!=typeof n)try{const r=t.Model.ownerOf(e)||a.get("stub").getCreator().toString();i&&"function"==typeof i&&(n=await i(e,r,a))}catch(e){throw new r.InternalError("Failed to resolve collection mirror name: "+e)}if(!n||"string"!=typeof n)throw new r.InternalError("No collection found model "+e.constructor.name);return n}async function ge(e,r,i,a){const n=await he(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(s,e);e.logger.info(`Mirror for ${t.Model.tableName(this.class)} created with ${t.Model.pk(a)}: ${i[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function pe(e,r,i,a){const n=await he(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(s,e),e.logger.info(`Mirror for ${t.Model.tableName(this.class)} updated: ${a[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function fe(e,r,i,a){const n=await he(a,r.resolver,e),o=e;o.put("mirror",!0),o.put("mirrorCollection",n),o.put("segregated",n);try{const r=a[t.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.Model.tableName(this.class)} deleted: ${r+""}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0),o.put("segregated",void 0)}}async function me(e,t,r,i){const n=le(e.get("identity"));if(n&&(n===t.mspId||t.condition&&t.condition(n)))throw new a.AuthorizationError(`Organization ${n} is not authorized to modify mirrored data`)}async function ye(e,t,r,i){const a=le(e.get("identity"));if(!a)return;const n=await he(i,t.resolver,e),o=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${n}`),o.put("mirror",!0),o.put("mirrorCollection",n),o.put("fullySegregated",!0),o.readFrom(n))}n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"affiliation",void 0),n.__decorate([t.minlength(1),n.__metadata("design:type",Array)],ce.prototype,"attrs",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentID",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"enrollmentSecret",void 0),n.__decorate([t.min(0),n.__metadata("design:type",Number)],ce.prototype,"maxEnrollments",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],ce.prototype,"role",void 0),e.ERC20Events=void 0,(U=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",U.APPROVAL="Approval",e.FabricBaseModel=class extends t.Model{constructor(e){super(e)}},n.__decorate([o.description("Stores the original timestamp of creation"),a.column(),a.createdAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),n.__decorate([o.description("Stores the timestamp of the last update"),a.column(),a.updatedAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),n.__decorate([o.description("Stores the version of the model"),a.column(),r.version(),n.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=n.__decorate([o.uses(P),n.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},n.__decorate([o.description("Stores the creator"),a.column(),a.createdBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),n.__decorate([o.description("Stores the user that last updated the model"),a.column(),a.updatedBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=n.__decorate([o.uses(P),n.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel),t.Model.prototype.isShared=function(){return t.Model.isShared(this.constructor)},t.Model.prototype.isPrivate=function(){return t.Model.isPrivate(this.constructor)},t.Model.prototype.segregate=function(){return t.Model.segregate(this)},t.Model.segregate=(i=>{if(!t.Model.isTransient(i))return{model:i};const a=o.Metadata.getAttributes(i.constructor)||[],n=o.Metadata.get(i.constructor,r.DBKeys.TRANSIENT),s=o.Metadata.get(i.constructor,e.FabricModelKeys.PRIVATE),c=o.Metadata.get(i.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(n||{}),u=Object.keys(s||{}),h=Object.keys(c||{});for(const e of a){const t=i[e],r=d.includes(e),a=!r,n=u.includes(e),o=h.includes(e);(r||n||o)&&(l.transient=l.transient||{},l.transient[e]=t),n&&(l.privates=l.privates||{},l.privates[e]=t),o&&(l.shared=l.shared||{},l.shared[e]=t),a&&(l.public=l.public||{},l.public[e]=t)}return l.model=t.Model.build(l.public,i.constructor.name),l}).bind(t.Model),t.Model.isPrivate=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(t.Model),t.Model.isShared=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(t.Model),t.Model.mirrored=(t=>o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(t.Model),t.Model.ownerOf=(t=>{const r=o.Metadata.get(t.constructor,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(t.Model),t.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,o.Metadata.get(t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(t.Model),t.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=o.Metadata.key(...r),n=o.Metadata.key(...i),s="function"==typeof t?t:t.constructor,c=o.Metadata.get(s,a),l=o.Metadata.get(s,n);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(t.Model);const we=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0);if(!a)throw new r.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function be(i,a,n){a.length>0&&n.readFrom(a),!n.isFullySegregated&&a.length&&((i=>{const a=o.Metadata.getAttributes(i)||[],n=t.Model.pk(i),s=o.Metadata.get(i,r.DBKeys.TRANSIENT)||{},c=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.PRIVATE))||{},l=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.SHARED))||{};return a.some(e=>e!==n&&!(e in s)&&!(e in c)&&!(e in l))})(i.constructor)||n.markFullySegregated())}async function Ce(e,r,i,a){const n=Array.isArray(r)?r:[r],o=t.Model.ownerOf(a)||le(e.get("identity"));if(!o)return;const s=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(a,o,e);i&&!s.includes(i)&&s.push(i)}be(a,s,e);const c=t.Model.sequenceName(a,"pk");e.setSequenceSegregation(c,e.isFullySegregated,s)}async function Ee(e,i,n,o){const s=Array.isArray(i)?i:[i],c=Array.isArray(n)?n:[n];if(c.length!==s.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const l=t.Model.ownerOf(o)||le(e.get("identity"));if(!l)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const d=s[0].collections,u="string"==typeof d?d:d(o,l,e);c.forEach((t,r)=>{const i="string"==typeof s[r].collections?s[r].collections:s[r].collections(o,l,e);if(i!==u)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function Ae(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=t.Model.ownerOf(n)||le(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:await c(n,s,e);e.readFrom(l)}async function ve(e,i,n,o,s){const c=Array.isArray(i)?i:[i],l=Array.isArray(n)?n:[n];if(l.length!==c.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const d=t.Model.ownerOf(o)||le(e.get("identity"));if(!d)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(o,d,e);l.forEach((t,r)=>{const i="string"==typeof c[r].collections?c[r].collections:c[r].collections(o,d,e);if(i!==h)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function Se(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=t.Model.ownerOf(n)||le(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:c(n,s,e);e.readFrom(l)}function Oe(e,t,i){return(i,a)=>{const n=[];if(!a){const r=o.Metadata.getAttributes(i);return r?.forEach(r=>{Oe(e,t)(i.prototype,r)}),i}{const i="string"==typeof e?e:e.toString(),a=i+":data",s={collections:e},c={priority:35,group:i+":extract"};n.push(o.prop(),r.transient(),(i,a)=>{const n=o.Metadata.key(t,a),s=i.constructor,c=o.Metadata.get(s,n)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],o.Metadata.set(s,n,c);const d=o.Metadata.get(s,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],o.Metadata.set(s,t,d);const h={...o.Metadata.get(s,r.DBKeys.TRANSIENT)||{},[a]:{}};o.Metadata.set(s,r.DBKeys.TRANSIENT,h)},r.on(r.DBOperations.ALL,Ce,s,c),r.onCreate(Ee,{collections:e},{priority:95,group:a}),r.onRead(Ae,{collections:e},{priority:95,group:a}),r.onUpdate(ve,{collections:e},{priority:95,group:a}),r.onDelete(Se,{collections:e},{priority:95,group:a}))}return o.apply(...n)(i,a)}}function Ie(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(Ie):e.constructor!==Object?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=Ie(e[r]),t),{})}class Me extends t.JSONSerializer{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=o.Metadata.modelName(e.constructor)}catch(e){i=void 0}r[t.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 t.Model.relations(e).forEach(e=>{r[e]=a(r[e])}),r}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e){return require("json-stringify-deterministic")(Ie(this.preSerialize(e)))}}function _e(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 xe extends t.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(Ie(this.preSerialize(e,t)))}preSerialize(e,r=!0){const i=Object.assign({},e);let a;try{a=o.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 r&&(i[t.ModelKeys.ANCHOR]=a||e.constructor.name),t.Model.relations(e).forEach(e=>{i[e]=n.call(this,i[e])}),i}}class Ne extends a.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new r.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 i=t.logger.for(this.getUser),{caName:a,caCert:n,caKey:o,url:s,hsm:c}=e;i.info(`Creating CA user for ${a} at ${s}`),i.verbose("Retrieving CA certificate from "+n);const l=await $.getFirstDirFileNameContent(n);let d;if(c)i.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!o)throw new r.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);i.debug("Retrieving CA key from "+o),d=await $.getFirstDirFileNameContent(o)}return i.debug("Loading Admin user for ca "+a),this._user=await $.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:i}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[n]=e;if(!n)throw new r.InternalError("Missing Fabric CA configuration");const{url:o,tls:c,caName:l}=n;t.info(`Initializing CA Client for CA ${n.caName} at ${n.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];t.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await $.getFileContent(h);t.debug("CA Certificate: "+g.toString());const p=new s(o,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(n,i);return t.debug("CA user loaded: "+f.getName()),{config:n,client:p}}async getCertificates(e,t=!0,...i){e instanceof a.Context?(i=[e],t=!0,e=void 0):"boolean"==typeof e?(t=e,e=void 0):"boolean"!=typeof t&&(i=[t,...i],t=!0);const{log:n}=(await this.logCtx(i,r.OperationKeys.READ,!0)).for(this.getCertificates);n.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const o=(await this.certificates.getCertificates(e||{},this.user)).result;return n.verbose(`Found ${o.certs.length} certificates`),n.debug(o.certs),t?o.certs.map(e=>e.PEM):o}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 t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new J(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new J(n)}}async read(e,...t){const{log:i}=(await this.logCtx(t,r.OperationKeys.READ,!0)).for(this.read);let a;i.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n,...o){const{log:s}=(await this.logCtx(o,"register",!0)).for(this.register);let c;try{const{userName:o,password:l}=e,d={enrollmentID:o,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};c=await this.client.register(d,this.user),s.info(`Registration for ${o} 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:o,rootCertificate:s}=t;a.verbose(`Generating Identity from certificate ${n} in msp ${r}`);const c=G.fabricIdFromCertificate(n),l=G.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:n,privateKey:o.toBytes(),rootCertificate:s},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});n=Ne.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,...o){const{ctx:s}=(await this.logCtx(o,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,n,s),{userName:l}=e;return this.enroll(l,c,s)}async updateIdentity(e,t,r,...i){const{log:a,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const o=this.client.newIdentityService(),s=await o.getOne(e,this.user);await o.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(s.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=Ne.identityFromEnrollment(u,this.config.caName,n);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=B(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...i){const{log:a}=(await this.logCtx(i,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const n=await this.read(e);if(!n)throw new r.NotFoundError("Could not find enrollment with id "+e);let o;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:n.id};o=await this.client.revoke(e,this.user)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!o.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${o.errors.join("\n")}`);return o}}var Te;e.CA_ROLE=void 0,(Te=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",Te.USER="user",Te.CLIENT="client";const Fe=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Re=new c.MiniLogger("fabric-fs");async function De(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Pe(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}async function $e(e,t){return{mspId:e,credentials:await De(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Be(e);return await t.readFile(r)})}}async function Be(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}async function ke(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}async function Ke(e){const t=await De(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Be(e);return await t.readFile(r)}),r=await Le(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}async function Le(e){let t;if(c.isBrowser())t=globalThis.crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const i=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(i,"base64").toString("binary"));try{return await t.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new r.InternalError(e)}}function ze(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class je extends a.Statement{constructor(e,t){super(e,t)}squash(e){const t=super.squash(e);if(!t)return t;const{method:i,params:n,args:o}=t,{direction:s,limit:c}=n;switch(i){case a.PreparedStatementKeys.FIND:break;case a.PreparedStatementKeys.PAGE:o.push(s,c);break;case a.PreparedStatementKeys.FIND_BY:break;case a.PreparedStatementKeys.LIST_BY:o.push(s);break;case a.PreparedStatementKeys.PAGE_BY:o.push(s,c);break;case a.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new r.InternalError("Unsupported method "+i)}return t}async executePrepared(...e){const t=a.Repository.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return t.statement(r,...i,...e)}async prepare(e){if(e=e||await this.adapter.context(a.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},i={class:this.fromSelector,args:t,params:r},n=[a.QueryClause.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);n.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&n.push(a.QueryClause.SELECT,this.selectSelector.join(` ${a.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(a.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),t.push(this.orderBySelectors[0][1])),i.method=c.toCamelCase(n.join(" ")),i.params=r,this.prepared=i,this}processRecord(e,t,r,n){if(e[i.CouchDBKeys.ID]){const[,...t]=e[i.CouchDBKeys.ID].split(i.CouchDBKeys.SEPARATOR),o=t.join("_");return this.adapter.revert(e,this.fromSelector,a.Sequence.parseValue(r,o),void 0,n)}return e}async raw(e,...i){const{ctx:a}=this.logCtx(i,this.raw),n=e?.aggregateInfo;if(e?.aggregate&&n)return this.executeAggregate(n,a);const s=await this.adapter.raw(e,!0,this.fromSelector,a),c=t.Model.pk(this.fromSelector),l=o.Metadata.get(this.fromSelector,o.Metadata.key(r.DBKeys.ID,c))?.type;return this.selectSelector?s:s.map(e=>this.processRecord(e,c,l,a))}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const n={};n[i.CouchDBKeys.TABLE]={},n[i.CouchDBKeys.TABLE]=t.Model.tableName(this.fromSelector);const o={selector:n};if(this.selectSelector&&(o.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(a.Condition.and(this.whereCondition,a.Condition.attribute(i.CouchDBKeys.TABLE).eq(o.selector[i.CouchDBKeys.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(i.CouchDBGroupOperator).indexOf(r[0]))switch(r[0]){case i.CouchDBGroupOperator.AND:t[i.CouchDBGroupOperator.AND]=[...Object.values(t[i.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const a=r[0];return a===i.CouchDBGroupOperator.AND?e.push(...t[a]):e.push(t),e},[])],o.selector=t;break;case i.CouchDBGroupOperator.OR:{const e={};e[i.CouchDBGroupOperator.AND]=[t,...Object.entries(o.selector).map(([e,t])=>{const r={};return r[e]=t,r})],o.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{o.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${o.selector[t]} by ${r}`),o.selector[t]=r})}if(this.orderBySelectors?.length){o.sort=o.sort||[],o.selector=o.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,a={};a[r]=t,o.sort.push(a),o.selector[r]||(o.selector[r]={},o.selector[r][i.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?o.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+i.CouchDBQueryLimit),o.limit=i.CouchDBQueryLimit),this.offsetSelector&&(o.skip=this.offsetSelector),o}parseCondition(e){const{attr1:t,operator:r,comparison:n}=e;if(r===a.Operator.STARTS_WITH){if("string"!=typeof t)throw new a.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("STARTS_WITH requires a string comparison");const e={start:o=n,end:ze(o)},r={};return r[t]={},r[t][i.CouchDBOperator.BIGGER_EQ]=e.start,r[t][i.CouchDBOperator.SMALLER]=e.end,{selector:r}}var o,s;if(r===a.Operator.ENDS_WITH){if("string"!=typeof t)throw new a.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("ENDS_WITH requires a string comparison");const e={};return e[t]={[i.CouchDBOperator.REGEXP]:(s=n,s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(r===a.Operator.BETWEEN){const e=t;if(!Array.isArray(n)||2!==n.length)throw new a.QueryError("BETWEEN operator requires [min, max] comparison");const[r,o]=n,s={};return s[e]={},s[e][i.translateOperators(a.Operator.BIGGER_EQ)]=r,s[e][i.translateOperators(a.Operator.SMALLER_EQ)]=o,{selector:s}}let c={};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(r))c[t]={},c[t][i.translateOperators(r)]=n;else if(r===a.Operator.NOT)c=this.parseCondition(t).selector,c[i.translateOperators(a.Operator.NOT)]={},c[i.translateOperators(a.Operator.NOT)][t.attr1]=n;else{const e=this.parseCondition(t).selector,a=this.parseCondition(n).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(i.translateOperators(r),e,a).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",t=this.createAggregateDescriptor("sum",e),r=this.createAggregateDescriptor("count",e);if(!t||!r)throw new a.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:t.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of r){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new a.QueryError(`No CouchDB view metadata found for table ${t.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const a=i.findViewMetadata(this.fromSelector,e,r);if(!a.length)return;const n=a[0],o=t.Model.tableName(this.fromSelector),s=i.generateViewName(o,n.attribute,e,n),c=n.ddoc||i.generateDesignDocName(o,s),l={reduce:void 0!==n.reduce||!n.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:n,descriptor:{ddoc:c,view:s,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,t){if("avg"!==e.kind)throw new a.QueryError("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,n]=[e.sumDescriptor,e.countDescriptor],[o,s]=await Promise.all([r.view(i.ddoc,i.view,i.options,t),r.view(n.ddoc,n.view,n.options,t)]),c=o.rows?.[0]?.value??0,l=s.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,t){if("avg"===e.kind)throw new a.QueryError("Average results should be handled before processing rows");const r=t.rows||[],i=e,n=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(e=>e.key??e.value):n.returnDocs?r.map(e=>e.value??e.doc??e):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}class Ue extends a.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new a.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 He;class Ge extends a.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new N}static{this.log=c.Logging.for(Ge)}constructor(e,t){super(Object.assign({},Fe,e),P,t),this.serializer=Ge.serializer}Statement(e){return new je(this,e)}Paginator(e,t,r){return new Ue(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,r,i,...n){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.Model.tableName(e)):t.Model.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let o=n.pop();void 0===o||o instanceof a.Context||(n.push(o),o=void 0),r=o?Object.assign({},o.toOverrides(),r):r;const s=await this.flags("string"==typeof e?e:e.name,i,r,...[...n,o].filter(Boolean));if(o){if(!(o instanceof this.Context)){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}const t=o.getOrUndefined("operation"),r=o.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}return o.accumulate(s)}return(new this.Context).accumulate({...s})}decode(e){return Ge.decoder.decode(e)}repository(){return I}createPrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.createPrefix),s=t.Model.tableName(e),c={};return c[i.CouchDBKeys.TABLE]=s,Object.assign(c,a),[e,r,c,...o]}createAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.createAllPrefix),l=a.map((e,t)=>{const r={};return r[i.CouchDBKeys.TABLE]=s,Object.assign(r,n[t]),r});return[e,a,l,...c]}updateAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.updateAllPrefix),l=a.map(()=>{const e={};return e[i.CouchDBKeys.TABLE]=s,e});return[e,a,l,...c]}async createAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.createAll),d=t.Model.tableName(e);c.info(`adding ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:s}:{},p=await this.submitTransaction(l,r.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],g,this.getEndorsingOrganizations(l),e.name);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,f[0][t.Model.pk(e)]||i[0])?this.readAll(e,F(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s[r]||{}),f[r])),i),l):f}async readAll(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.readAll),s=t.Model.tableName(e);n.info(`reading ${i.length} entries to ${s} table`),n.verbose("pks: "+i);const c=await this.evaluateTransaction(o,r.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(i)],void 0,void 0,e.name);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}async updateAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.updateAll),d=t.Model.tableName(e);c.info(`updating ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:s}:{},p=await this.submitTransaction(l,r.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(a.map(t=>this.serializer.serialize(t,e.name)))],g,this.getEndorsingOrganizations(l),e.name);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,i[0])?this.readAll(e,F(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s[r]||{}),f[r])),i),l):f}async deleteAll(e,i,...a){const{log:n,ctx:o,ctxArgs:s}=this.logCtx(a,this.deleteAll),c=t.Model.tableName(e),l=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let d;const u=this.shouldRefreshAfterWrite(e,o,l,i[0]);u&&(d=await this.readAll(e,i,...s)),n.info(`deleting ${i.length} entries to ${c} table`),n.verbose("pks: "+i);const h=await this.submitTransaction(o,r.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(i)],void 0,this.getEndorsingOrganizations(o),e.name);try{return u?d:JSON.parse(this.decode(h)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}prepare(e,...i){const{log:n,ctx:o}=this.logCtx(i,this.prepare),s=t.Model.segregate(e);e[a.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+e[a.PersistenceKeys.METADATA]),Object.defineProperty(s.model,a.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[a.PersistenceKeys.METADATA]}));const c=t.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new r.InternalError("No mirror MSP could be found");const t=this.getEndorsingOrganizations(o)||[],i=[...new Set([...t,e])];o.accumulate({endorsingOrgs:i,endorsingOrganizations:i,legacy:!0})}return{record:s.model,model:s.model,id:e[t.Model.pk(e.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(e,t,r,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(o,o.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&n.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,a){if(!i)return!1;const n=t.Model.pk(e),o=t.Model.composed(e,n),s=t.Model.generated(e,n),c=null!=a;return!(c||!o)||(!c&&s?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(e){return!!this.config.allowGatewayOverride}async create(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.create),d=t.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:n}:{},p=await this.submitTransaction(l,r.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],g,this.getEndorsingOrganizations(l),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,F(e,t.Model.merge(Object.assign({},a,n||{}),f,e),i),l):f}async healthcheck(e,...r){const{log:i,ctx:a}=this.logCtx(r,this.healthcheck),n=t.Model.tableName(e);i.verbose(`reading entry from ${n} table`);const o=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(o))}async read(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.read),s=t.Model.tableName(e);n.verbose(`reading entry from ${s} table`),n.debug("pk: "+i);const c=await this.evaluateTransaction(o,r.OperationKeys.READ,[i.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,r,a,...n){const o=t.Model.tableName(e),{ctxArgs:s}=this.logCtx(n,this.updatePrefix),c={};return c[i.CouchDBKeys.TABLE]=o,Object.assign(c,a),[e,r,c,...s]}async update(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=t.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=u?{[d]:n}:{},p=await this.submitTransaction(l,r.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name||e)],g,this.getEndorsingOrganizations(l),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,F(e,t.Model.merge(Object.assign({},a,n||{}),f,e),i),l):f}async delete(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.delete),s=t.Model.tableName(e),c=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let l;const d=this.shouldRefreshAfterWrite(e,o,c,i);d&&(l=await this.read(e,i,o)),n.verbose(`deleting entry from ${s} table`),n.debug("pk: "+i);const u=await this.submitTransaction(o,r.OperationKeys.DELETE,[i.toString()],void 0,this.getEndorsingOrganizations(o),e.name);return d?l:this.serializer.deserialize(this.decode(u))}async raw(e,i=!0,a,...n){const{log:o,ctx:s}=this.logCtx(n,this.raw),c=a.name;let l,d;o.info("Performing raw statement on table "+t.Model.tableName(a));try{l=await this.evaluateTransaction(s,"raw",[JSON.stringify(e),i],void 0,void 0,c)}catch(e){throw this.parseError(e)}try{d=JSON.parse(this.decode(l))}catch(e){throw new r.SerializationError("Failed to process result: "+e)}if(Array.isArray(d)){if(!d.length)return d;const e=d[0];return t.Model.isModel(e)?d.map(e=>t.Model.build(e)):d}return u=d,t.Model.isModel(u)?t.Model.build(u):u;var u}async view(e,t,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.view);let s,c;n.info(`Querying view ${e}/${t}`);try{s=await this.evaluateTransaction(o,"view",[e,t,JSON.stringify(i)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(s))}catch(e){throw new r.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Ge.getClient(this.config)),this._client}async Gateway(e){return Ge.getGateway(e,this.config,this.client)}getContractName(e){if(e)return e+"Contract"}async Contract(e,t){return Ge.getContract(await this.Gateway(e),this.config,t)}async transaction(e,t,r=!0,i,a={},n,o){const s=this.log.for(this.transaction),c=await this.Gateway(e);try{const c=await this.Contract(e,this.getContractName(o));s.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(o)||this.config.contractName}.${t}`),s.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:Object.entries(a).reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}),endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,t,d)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(e){const t=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}],r=(this.getEndorsingOrganizations(e)?.filter(e=>!!e)||[]).filter(e=>e!==this.config.mspId);if(!r.length)return t;const i=this.config.mspMap;for(const e of r){const r=i?.[e];if(!r?.length)throw new a.UnsupportedError(`No peer mapping available for MSP ${e}. Provide it via config.mspMap`);const n=r[Math.floor(Math.random()*r.length)];if(!n.endpoint)throw new a.UnsupportedError(`Invalid peer mapping for MSP ${e}: missing endpoint`);t.push({mspId:e,peerEndpoint:n.endpoint,peerHostAlias:n.alias,tlsCert:n.tlsCert||this.config.tlsCert})}return t}async submitLegacyWithExplicitEndorsers(e,t,r,i,a,n){const o=this.log.for(this.submitLegacyWithExplicitEndorsers),s=this.normalizeLegacyPeers(a),c=await this.resolveLegacyIdentityMaterial(),l=await f.Wallets.newInMemoryWallet(),d=this.config.mspId+"-legacy";await l.put(d,{credentials:{certificate:c.certificate,privateKey:c.privateKey},mspId:this.config.mspId,type:"X.509"});const u=await this.buildLegacyConnectionProfile(s),h=new f.Gateway;try{await h.connect(u,{identity:d,wallet:l,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(s)},tlsInfo:{certificate:c.certificate,key:c.privateKey}});const e=await h.getNetwork(this.config.channel),a=e.getContract(this.config.chaincodeName,this.getContractName(n)).createTransaction(t);i&&a.setTransient(i);const g=s.map(t=>e.getChannel().getEndorser(t.name)).filter(e=>!!e);g.length&&a.setEndorsingPeers(g),o.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${t} via peers ${s.map(e=>e.peerEndpoint).join(", ")}`);const p=await a.submit(...r);return Uint8Array.from(p)}catch(e){throw this.parseError(e)}finally{h.disconnect()}}normalizeLegacyPeers(e){const t=new Map,r=e=>{const r=`${e.peerEndpoint}|${e.peerHostAlias||""}`;if(t.has(r))return;const i=`peer-${e.mspId}-${t.size}`;t.set(r,{...e,name:i})};return e.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(t.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(e){const t={},r={},i={};for(const a of e){const e=await this.readPemInput(a.tlsCert||this.config.tlsCert),n=a.peerHostAlias||this.extractHost(a.peerEndpoint);t[a.name]={url:this.ensureGrpcUrl(a.peerEndpoint),tlsCACerts:{pem:e},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[a.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[a.mspId]=i[a.mspId]||{mspid:a.mspId,peers:[]},i[a.mspId].peers.push(a.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:t,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(e){return e.every(e=>this.isLocalEndpoint(e.peerEndpoint))}isLocalEndpoint(e){const t=this.extractHost(e).toLowerCase();return"localhost"===t||"127.0.0.1"===t}extractHost(e){return e.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(e){return/^grpcs?:\/\//i.test(e)?e:"grpcs://"+e}async readPemInput(e){if(!e)throw new r.InternalError("Missing certificate or key material");if(Buffer.isBuffer(e))return e.toString("utf8");const t=e.trim();if(/-----BEGIN [A-Z ]+-----/.test(t))return t;const i=await m.promises.stat(e).catch(()=>{});return i?.isDirectory()?await ke(e):(await Pe(e)).toString()}parseError(e){return Ge.parseError(e)}async submitTransaction(e,t,r,i,a,n){if(this.shouldUseLegacyGateway(e)){const a=this.prepareLegacyArgs(r),o=this.buildLegacyTransient(i),s=this.buildLegacyPeerConfigs(e);return this.submitLegacyWithExplicitEndorsers(e,t,a,o,s,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 i=e.tlsCert;if("string"==typeof i)if(i.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))i=Buffer.from(i,"utf8");else try{i=Buffer.from(m.readFileSync(i,"utf8"))}catch(e){throw new r.InternalError(`Failed to read the tls certificate from ${i}: ${e}`)}const a=b.credentials.createSsl(i);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.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 n=await $e(t.mspId,t.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+G.fabricIdFromCertificate(n.credentials.toString()))}catch(e){i.error("Failed to extract Fabric ID from certificate",e)}let o;if(t.hsm)throw new a.UnsupportedError("HSM NOT IMPLEMENTED");o=await Ke(t.keyCertOrDirectoryPath);const s={client:e,identity:n,signer:o,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(s);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Ge._baseDispatch}static parseError(e){let t="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(t=""+e.details[0].message),t.includes("MVCC_READ_CONFLICT")?new te(e):t.includes("DEADLINE_EXCEEDED")?new ne(e):t.includes("ENDORSEMENT_POLICY_FAILURE")?new ie(e):t.includes("PHANTOM_READ_CONFLICT")?new re(e):e instanceof Error&&e.code&&9===e.code?new ee(e):t.includes(r.ValidationError.name)?new r.ValidationError(e):t.includes(r.NotFoundError.name)?new r.NotFoundError(e):t.includes(r.ConflictError.name)?new r.ConflictError(e):t.includes(r.BadRequestError.name)?new r.BadRequestError(e):t.includes(a.QueryError.name)?new a.QueryError(e):t.includes(a.PagingError.name)?new a.PagingError(e):t.includes(a.UnsupportedError.name)?new a.UnsupportedError(e):t.includes(a.MigrationError.name)?new a.MigrationError(e):t.includes(a.ObserverError.name)?new a.ObserverError(e):t.includes(a.AuthorizationError.name)?new a.AuthorizationError(e):t.includes(a.ForbiddenError.name)?new a.ForbiddenError(e):t.includes(a.ConnectionError.name)?new a.ConnectionError(e):t.includes(r.SerializationError.name)?new r.SerializationError(e):new r.InternalError(e)}}n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"create",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"healthcheck",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"read",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"update",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"delete",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,"function"==typeof(He="undefined"!=typeof D&&D)?He:Object,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"raw",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String,String,Object,a.Context]),n.__metadata("design:returntype",Promise)],Ge.prototype,"view",null),Ge.decoration(),a.Adapter.setCurrent(P);class qe extends a.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 Ge))throw new a.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,i,n,...o){const{log:s,ctxArgs:c}=a.Adapter.logCtx(this.updateObservers,i,!1,...o);if(this.adapter)try{await this.adapter.refresh(e,i,n,...c)}catch(e){throw new r.InternalError("Failed to refresh dispatch: "+e)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.Model.tableName(e)}:${i}`)}async handleEvents(e){if(!this.listeningStack)throw new r.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new r.InternalError("No adapter found. should be impossible");const i=e||await this.adapter.context(r.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t.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:r,event:n,owner:o}=_e(e.eventName);if(o&&o!==this.adapter.config?.mspId)continue;const s=this.parsePayload(e.payload);try{const e=(r?t.Model.get(r):t.Model.get(this.models[0].name))??(r||this.models[0]?.name);await this.updateObservers(e,n,s.id,i)}catch(e){a.error(`Failed update observables for table ${r} event ${n} id: ${s.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 r.InternalError("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t.Model),{ctx:i}=this.logCtx([e],this.initialize),a=(await Ge.getGateway(i,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new r.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(i)}}Ge&&(Ge._baseDispatch=qe);const Ve="##VERSION##",Ye="##PACKAGE##";o.Metadata.registerLibrary(Ye,Ve),e.AllowanceError=Y,e.BalanceError=V,e.BaseEncoder=H,e.ClientSerializer=N,e.CoreUtils=$,e.CryptoUtils=G,e.DefaultFabricClientFlags=Fe,e.DeterministicSerializer=Me,e.EndorsementError=ee,e.EndorsementPolicyError=ie,e.FabricClientAdapter=Ge,e.FabricClientDispatch=qe,e.FabricClientRepository=I,e.FabricERC20ClientRepository=T,e.FabricEnrollmentService=se,e.FabricFlavour=P,e.FabricIdentityService=Ne,e.ImplicitPrivateCollection=we,e.MissingContextError=W,e.MissingPKCSS11Lib=Z,e.ModelCollection=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!a)throw new r.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(n.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=te,e.NamespaceCollection=e=>(i,a)=>{const n=a||("function"!=typeof i?t.Model.ownerOf(i):void 0),o="function"==typeof i?i:i.constructor;if(!n)throw new r.InternalError(`Model ${o.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${n?c.toPascalCase(n):""}`},e.NotInitializedError=X,e.OverflowError=q,e.Owner=function(){return function(e,t,i){const n=i.value;return i.value=async function(...e){const i=e[0],o=i.clientIdentity.getID(),s=await this.tokenRepository.select(),c=await s.execute(i);if(0==c.length)throw new r.NotFoundError("No tokens avaialble");if(c.length>1)throw new r.NotFoundError("To many token available : "+c.length);if(c[0].owner!=o)throw new a.AuthorizationError(`User not authorized to run ${t} on the token`);return await n.apply(this,e)},i}},e.PACKAGE_NAME=Ye,e.PhantomReadConflictError=re,e.RegistrationError=J,e.RegistrationRequestBuilder=ce,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=xe,e.TransactionBufferSizeError=oe,e.TransactionLimitsError=ae,e.TransactionTimeoutError=ne,e.UnauthorizedPrivateDataAccess=Q,e.VERSION=Ve,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new q(`Addition overflow: ${e} + ${t}`);return r},e.applyMirrorFlags=async(e,r,i)=>{if(!r)return;const a=t.Model.mirroredAt(e);if(!a)return;if(!(r===a.mspId||a.condition&&a.condition(r)))return;const n=await he(new e,a.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)},e.applySegregationFlags=be,e.collectionFor=v,e.contentOfLoadFile=De,e.createMirrorHandler=ge,e.deleteMirrorHandler=fe,e.evalMirrorMetadata=he,e.extractCollections=async(e,i,a={},n=!1)=>{let{privateCols:o,sharedCols:s}=t.Model.collectionsFor(e);function c(t){try{return"string"==typeof t?t:t(e,i[0])}catch(e){throw new r.InternalError(e)}}o=o.map(c),s=s.map(c);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.sharedCols||{}),u=n?t.Model.mirroredAt(e):void 0,h=i.map(e=>o.map(t=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n}=l;return S(e,t,r,i,a,n,!1)})).flat();if(u&&u.mspId){const t="string"==typeof u.resolver?u.resolver:u.resolver(e,u.mspId);if(t&&!h.some(e=>e.name===t&&e.policy.includes(u.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:a}=l;h.push(S(u.mspId,t,e,r,i,a,!1))}}return{privates:h,shared:s.map(e=>{const{requiredPeerCount:t,maxPeerCount:r,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}=d;return O(i,e,t,r,a,n,o)})}},e.extractIds=F,e.extractMspId=le,e.extractPrivateKey=Le,e.extractSegregatedCollections=Ce,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=i.generateViews([e]),a=t||{};return r.forEach(e=>{a[e._id]=e}),r},e.generateModelIndexes=e=>i.generateIndexes([e]),e.getAkiAndSerialFromCert=B,e.getCAUser=async(e,t,r,i)=>{Re.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),n=d.User.newCryptoSuite();a.setCryptoSuite(n);const o=n.createKeyFromRaw(t);return await a.setEnrollment(o,r,i),a},e.getFirstDirFileName=Be,e.getFirstDirFileNameContent=ke,e.getIdentity=$e,e.getSigner=Ke,e.mirror=(t,i,a)=>{const n="string"!=typeof i&&!!i,s=n?void 0:i,c=n?i:a;return o.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,i,a)=>{const n={condition:a,mspId:i,resolver:t};return o.apply(o.metadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),n),r.onRead(ye,n,{priority:30}),r.onCreate(me,n,{priority:20}),r.onUpdate(me,n,{priority:20}),r.onDelete(me,n,{priority:20}),r.onCreate(ge,n,{priority:100}),r.onUpdate(pe,n,{priority:100}),r.onDelete(fe,n,{priority:100}))},args:[t,s,c]}).apply()},e.mirrorWriteGuard=me,e.ownedBy=()=>o.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(i,a)=>o.apply(t.required(),r.generated(),r.readonly(),r.onCreate(de),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(i,a),args:[]}).apply(),e.ownedByOnCreate=de,e.parseEventName=_e,e.privateCollectionFor=S,e.privateData=(t=we)=>o.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>Oe(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=Pe,e.readMirrorHandler=ye,e.readModelFile=E,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(...E(t))}return r},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string contains digits"));const i=parseInt(e);if(isNaN(i))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return i},e.segregatedDataOnCreate=Ee,e.segregatedDataOnDelete=Se,e.segregatedDataOnRead=Ae,e.segregatedDataOnUpdate=ve,e.sharedCollectionFor=O,e.sharedData=t=>o.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>Oe(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sortKeysOnlyRecursive=Ie,e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new q(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>o.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(i,a)=>o.apply(t.required(),r.readonly(),r.onCreate(ue),r.onUpdate(ue),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(i,a),args:[]}).apply(),e.transactionIdOnCreate=ue,e.updateMirrorHandler=pe,e.writeCollectionDesignDocs=(e,t=process.cwd(),r)=>{e?.length&&A(e,t,r)},e.writeCollections=(e,t=process.cwd(),r="collections_config")=>{const i=require("fs"),a=require("path"),n=a.resolve(a.join(t,`./META-INF/${r}.json`));!function e(t){const r=a.dirname(t);if(i.existsSync(r))return!0;e(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))},e.writeDesignDocs=A,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));C(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("@decaf-ts/core"),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("fabric-network"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","@decaf-ts/core","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fabric-network","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.decafTsCore,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fabricNetwork,e.fs);
2
2
  //# sourceMappingURL=for-fabric.cjs.map
@@ -1,2 +1,2 @@
1
- import{Model as t,required as e,model as r,JSONSerializer as i,ModelKeys as s,stringFormat as n,minlength as a,min as o}from"@decaf-ts/decorator-validation";import{InternalError as c,OperationKeys as l,enforceDBDecorators as d,reduceErrorsToPrint as h,ValidationError as u,SerializationError as g,composeAttributeValue as p,BaseError as f,ConflictError as m,NotFoundError as y,version as w,DBKeys as b,generated as A,readonly as v,onCreate as C,onUpdate as S,onRead as E,onDelete as O,transient as x,on as N,DBOperations as I,BulkCrudOperationKeys as T,BadRequestError as $}from"@decaf-ts/db-decorators";import{generateIndexes as R,generateViews as F,CouchDBKeys as k,CouchDBGroupOperator as P,CouchDBOperator as B,CouchDBQueryLimit as j,translateOperators as L,findViewMetadata as _,generateViewName as M,generateDesignDocName as H}from"@decaf-ts/for-couchdb";import{Repository as z,PreparedStatementKeys as U,OrderDirection as G,PersistenceKeys as K,Paginator as q,pk as Y,column as V,table as W,BaseModel as J,Sequence as Q,Context as X,oneToOne as Z,Cascade as tt,index as et,normalizeImport as rt,AuthorizationError as it,createdAt as st,updatedAt as nt,createdBy as at,updatedBy as ot,UnsupportedError as ct,ClientBasedService as lt,Statement as dt,QueryClause as ht,Condition as ut,Operator as gt,QueryError as pt,GroupOperator as ft,Adapter as mt,PagingError as yt,MigrationError as wt,ObserverError as bt,ForbiddenError as At,ConnectionError as vt,Dispatch as Ct}from"@decaf-ts/core";import{__decorate as St,__metadata as Et}from"tslib";import{Metadata as Ot,description as xt,uses as Nt,Decoration as It,apply as Tt,propMetadata as $t,metadata as Rt,prop as Ft}from"@decaf-ts/decoration";import Dt from"fabric-ca-client";import{MiniLogger as kt,isBrowser as Pt,LoggedClass as Bt,Logging as jt,toPascalCase as Lt,toCamelCase as _t,debug as Mt,final as Ht}from"@decaf-ts/logging";import{signers as zt,connect as Ut,GatewayError as Gt}from"@hyperledger/fabric-gateway";import{User as Kt}from"fabric-common";import qt,{X509Certificate as Yt}from"crypto";import*as Vt from"@peculiar/x509";import{X509Certificate as Wt}from"@peculiar/x509";import{Crypto as Jt}from"@peculiar/webcrypto";import*as Qt from"@grpc/grpc-js";import{Client as Xt}from"@grpc/grpc-js";import{Wallets as Zt,Gateway as te}from"fabric-network";import ee from"fs";function re(t){const e=require("fs"),r=require("path").dirname(t);if(e.existsSync(r))return!0;re(r),e.mkdirSync(r)}function ie(t){return R([t])}function se(t,e){const r=F([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function ne(e){const r=require("path"),i=require(r.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof t}catch(e){return!1}})}async function ae(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...ne(e))}return r}function oe(t,e=process.cwd(),r){const i=require("fs"),s=require("path");t.forEach(t=>{const n=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));re(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))})}function ce(t,e=process.cwd(),r){if(!t.length)return;const i=require("fs"),s=require("path");t.forEach(t=>{const n=t._id.replace(/^_design\//,""),a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));re(a);const o={...t};delete o._rev,i.writeFileSync(a,JSON.stringify(o,void 0,2))})}function le(t,e,r,i,s,n,a){return{name:t,policy:e,requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n,memberOnlyWrite:a}}function de(t,e=t+"Private",r=0,i=0,s=0,n=!0,a=!0){const o=le(e,`OR('${t}.member')`,r,i,s,n,a);return o.endorsementPolicy={signaturePolicy:`OR('${t}'.peer)`},o}function he(t,e,r=1,i=2,s=0,n=!0,a=!0){const o=le(e,`OR(${t.map(t=>`'${t}.member'`).join(",")})`,r,i,s,n,a);return o.endorsementPolicy={signaturePolicy:`AND(${t.map(t=>`'${t}.peer'`).join(",")})`},o}async function ue(e,r,i={},s=!1){let{privateCols:n,sharedCols:a}=t.collectionsFor(e);function o(t){try{return"string"==typeof t?t:t(e,r[0])}catch(t){throw new c(t)}}n=n.map(o),a=a.map(o);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},i?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},i?.sharedCols||{}),h=s?t.mirroredAt(e):void 0,u=r.map(t=>n.map(e=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n}=l;return de(t,e,r,i,s,n,!1)})).flat();if(h&&h.mspId){const t="string"==typeof h.resolver?h.resolver:h.resolver(e,h.mspId);if(t&&!u.some(e=>e.name===t&&e.policy.includes(h.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:s}=l;u.push(de(h.mspId,t,e,r,i,s,!1))}}return{privates:u,shared:a.map(t=>{const{requiredPeerCount:e,maxPeerCount:i,blockToLive:s,memberOnlyRead:n,memberOnlyWrite:a}=d;return he(r,t,e,i,s,n,a)})}}function ge(t,e=process.cwd(),r="collections_config"){const i=require("fs"),s=require("path"),n=s.resolve(s.join(e,`./META-INF/${r}.json`));!function t(e){const r=s.dirname(e);if(i.existsSync(r))return!0;t(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))}function pe(t,e=process.cwd(),r){t?.length&&ce(t,e,r)}class fe extends z{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(t){return super.override(Object.assign({},t,this._overrides)).for(t)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,U.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${t.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${t.tableName(this.class)} by ${e} ${r}`),await this.statement(this.listBy.name,e,r,...n)}async findBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...n)}async findOneBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...n)}async find(e,r=G.ASC,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND,!0)).for(this.find);return s.verbose(`finding ${t.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...n)}async page(e,r=G.ASC,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,U.PAGE,!0)).for(this.page);return n.verbose(`paging ${t.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...a)}async statement(e,...r){const{log:i,ctx:s,ctxArgs:n}=(await this.logCtx(r,K.STATEMENT,!0)).for(this.statement);i.verbose("Executing prepared statement "+e);const a=n.slice(0,-1),o=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(s,K.STATEMENT,[e,JSON.stringify(a)],void 0,void 0,this.class.name)));return Array.isArray(o)?o.map(e=>e[k.TABLE]&&e[k.TABLE]===t.tableName(this.class)?new this.class(e):e):o[k.TABLE]&&o[k.TABLE]===t.tableName(this.class)?new this.class(o):q.isSerializedPage(o)?Object.assign(o,{data:o.data.map(t=>new this.class(t))}):o}async countOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.tableName(this.class)}${e?" by "+e:""}`);const n=e?[e,...s]:s;return this.statement(U.COUNT_OF,...n)}async maxOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.tableName(this.class)}`),this.statement(U.MAX_OF,e,...s)}async minOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.tableName(this.class)}`),this.statement(U.MIN_OF,e,...s)}async avgOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.tableName(this.class)}`),this.statement(U.AVG_OF,e,...s)}async sumOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.tableName(this.class)}`),this.statement(U.SUM_OF,e,...s)}async distinctOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.tableName(this.class)}`),this.statement(U.DISTINCT_OF,e,...s)}async groupOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.tableName(this.class)} by ${e}`),this.statement(U.GROUP_OF,e,...s)}async healthcheck(...t){const{ctxArgs:e}=this.logCtx(t,this.healthcheck);return await this.adapter.healthcheck(this.class,...e)}async create(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.create);s.debug(`Creating new ${this.class.name} in table ${t.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const a=this.adapter.prepare(e,i),{record:o,id:c,transient:l}=a,d=await this.adapter.create(this.class,c,o,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:s,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const a=this.adapter.prepare(e,n),{id:o,transient:c}=a;let l=a.record;return s.debug(`updating ${this.class.name} in table ${t.tableName(this.class)} with id ${o}`),l=await this.adapter.update(this.class,o,l,c,...i),this.adapter.revert(l,this.class,o,c,n)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,l.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await d(this,r,t,l.CREATE,l.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=h(i);if(s)throw new u(s)}return[t,...i]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=a.map(t=>t.record),l=a.map(t=>t.transient),d=await this.adapter.createAll(this.class,o,c,l,...n);return Promise.all(d.map(async(t,e)=>{const r=o[e];return this.adapter.revert(t,this.class,r,l[e],i)}))}async updateAll(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.updateAll);s.debug(`Updating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=await this.adapter.updateAll(this.class,o,a.map(t=>t.record),a.map(t=>t.transient),...n);return Promise.all(c.map(async(t,e)=>{const r=o[e];return this.adapter.revert(t,this.class,r,a[e].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.mirroredAt(r)&&e.accumulate({legacy:!0})}}let me=class extends J{constructor(t){super(t)}};St([Y({type:String}),Et("design:type",String)],me.prototype,"name",void 0),St([V(),e(),Et("design:type",String)],me.prototype,"owner",void 0),St([V(),e(),Et("design:type",String)],me.prototype,"symbol",void 0),St([V(),e(),Et("design:type",Number)],me.prototype,"decimals",void 0),me=St([W("erc20_tokens"),r(),Et("design:paramtypes",[Object])],me);let ye=class extends J{constructor(t){super(t)}};St([Y({type:String}),Et("design:type",String)],ye.prototype,"id",void 0),St([V(),e(),Et("design:type",String)],ye.prototype,"token",void 0),St([V(),e(),Et("design:type",Number)],ye.prototype,"balance",void 0),St([V(),Et("design:type",String)],ye.prototype,"captive",void 0),ye=St([W("erc20_wallets"),r(),Et("design:paramtypes",[Object])],ye);let we=class extends J{constructor(t){super(t)}};St([Y({type:String}),V(),e(),Et("design:type",String)],we.prototype,"owner",void 0),St([V(),e(),Et("design:type",String)],we.prototype,"spender",void 0),St([V(),e(),Et("design:type",Number)],we.prototype,"value",void 0),we=St([W("erc20_allowances"),r(),Et("design:paramtypes",[Object])],we);class be extends i{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=Ot.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new g("Could not find metadata for "+t.constructor.name);i=e}return r[s.ANCHOR]=i,r}deserialize(e){const r=JSON.parse(e),i=r[s.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.build(r,i)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Ae extends fe{static{this.serializer=new be}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,r,i,...s){if(!this.observerHandler)throw new c("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:a}=this.logCtx(s,this.updateObservers);let o;n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.get(e):e,o=void 0===i?void 0:Array.isArray(i)?i.map(r=>Q.parseValue(t.sequenceFor(e).type,r)):Q.parseValue(t.sequenceFor(e).type,i),await this.observerHandler.updateObservers(e,r,o,...a)}decode(t){return Ae.decoder.decode(t)}constructor(t){super(t,ye),this.serializer=Ae.serializer}async tokenName(...t){const{ctx:e}=(await this.logCtx(t,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(e,"TokenName");return this.decode(r)}async symbol(...t){const{ctx:e}=(await this.logCtx(t,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(e,"Symbol");return this.decode(r)}async decimals(...t){const{ctx:e}=(await this.logCtx(t,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(e,"Decimals");return Number(this.decode(r))}async totalSupply(...t){const{ctx:e}=(await this.logCtx(t,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(e,"TotalSupply");return Number(this.decode(r))}async balanceOf(t,...e){const{ctx:r}=(await this.logCtx(e,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[t]);return Number(this.decode(i))}async transfer(t,e,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),s=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(s)}async transferFrom(t,e,r){const i=await X.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(i.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(n)}async approve(t,e){const r=await X.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),s=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(s)}async allowance(t,e){const r=await X.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),s=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(s))}async initialize(t){const e=await X.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Ae.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await X.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.checkInitialized);await this.adapter.evaluateTransaction(e,"CheckInitialized")}async mint(t){const e=await X.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[t.toString()])}async burn(t){const e=await X.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[t.toString()])}async burnFrom(t,e){const r=await X.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await X.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(e,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const t=await X.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(e,"ClientAccountID");return this.decode(r)}}function ve(e,r,i){let s,n,a;function o(r,i){if(s=s||t.pk(e),a=a||t.sequenceFor(e),n=n||t.composed(e,s),n)return p(r,n);const o=r[s]||i;if(void 0===o)throw new c("could not rebuild id for "+r.constructor.name);return o}if(Array.isArray(r)){if(!Array.isArray(i)||i.length!==r.length)throw new c("inconsistent parameters. both must be arrays of equal length");return r.map((t,e)=>o(t,i[e]))}return o(r,i)}let Ce=class extends J{constructor(t){super(t)}};var Se,Ee;St([xt("Unique identifier of the credentials record"),V(),Y(),Et("design:type",String)],Ce.prototype,"id",void 0),St([xt("PEM-encoded X.509 certificate for the identity"),V(),e(),Et("design:type",String)],Ce.prototype,"certificate",void 0),St([xt("PEM-encoded root or intermediate certificate"),V(),e(),Et("design:type",String)],Ce.prototype,"rootCertificate",void 0),St([xt("PEM-encoded private key"),V(),e(),Et("design:type",String)],Ce.prototype,"privateKey",void 0),Ce=St([r(),Et("design:paramtypes",[Object])],Ce),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(Se||(Se={})),(t=>{t.X509="X.509"})(Ee||(Ee={}));const Oe="hlf-fabric";let xe=class extends J{constructor(t){super(t),this.type=Ee.X509}};St([xt("Unique identifier of the identity"),Y(),Et("design:type",String)],xe.prototype,"id",void 0),St([Z(Ce,{update:tt.CASCADE,delete:tt.CASCADE}),Et("design:type",Ce)],xe.prototype,"credentials",void 0),St([V(),e(),et(),Et("design:type",String)],xe.prototype,"mspId",void 0),St([V(),e(),Et("design:type",String)],xe.prototype,"type",void 0),xe=St([r(),Et("design:paramtypes",[Object])],xe);class Ne{static{this.logger=new kt(Ne.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await rt(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(n("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new Kt(t),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);a.setCryptoSuite(c);const l=s?.hsm?await this.getHSMEnrollmentKey(c,r,s.hsm):this.getSoftwareEnrollmentKey(c,e);return await a.setEnrollment(l,r,i),a}static getCryptoSuite(t){return t?(Ne.cryptoSuite||(Ne.cryptoSuite=Kt.newCryptoSuite(t)),Ne.cryptoSuite):Kt.newCryptoSuite()}static getSoftwareEnrollmentKey(t,e){if(!e)throw Error("Private key must be provided when HSM configuration is not supplied");return t.createKeyFromRaw(e)}static async getHSMEnrollmentKey(t,e,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(e),s=await t.getKey(i);if(!s||"function"==typeof s.isPrivate&&!s.isPrivate())throw Error("Unable to resolve private key from HSM");return s}static async getCertificateSKI(t){const e=new Yt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return qt.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){return{mspId:t,credentials:await this.contentOfLoadFile(e,async t=>{const{promises:e}=await rt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await rt(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await rt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return zt.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await rt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function Ie(t){const e=new Wt(t),r=e.extensions?.find(t=>"2.5.29.35"===t.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:e.serialNumber}}const Te=new Jt;var $e,Re,Fe,De,ke;Vt.cryptoProvider.set(Te),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})($e||($e={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(Re||(Re={}));class Pe{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}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(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const s=t.length;for(;i!==s&&0===t[i];)i++,e++;const n=(s-i)*this.iFactor+1>>>0,a=new Uint8Array(n);for(;i!==s;){let e=t[i],s=0;for(let t=n-1;(0!==e||r>s)&&-1!==t;t--,s++)e+=256*a[t]>>>0,a[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=s,i++}let o=n-r;for(;o!==n&&0===a[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(a[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const s=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(s);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=s-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=s-i;for(;a!==s&&0===n[a];)a++;const o=new Uint8Array(r+(s-a));let c=r;for(;a!==s;)o[c++]=n[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class Be{static{this.b58encoder=new Pe($e.BASE58)}static{this.logger=new kt(Be.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(n("Parsing certificate: {0}",t));const e=new Vt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(n("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=Te.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await Te.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Vt.X509Certificate(t),s=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,Te.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Vt.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const s=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(s)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return Pt()?globalThis.window.crypto.subtle:Te.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=Te.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Re.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),s={name:Re.KEY_ALGORYTHM,hash:Re.HASH,salt:i,iterations:Re.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Re.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:Re.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Re.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Re.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class je extends c{constructor(t){super(t,je.name)}}class Le extends c{constructor(t){super(t,Le.name)}}class _e extends c{constructor(t){super(t,_e.name)}}class Me extends it{constructor(t){super(t,Me.name)}}class He extends c{constructor(t){super(t,He.name,500)}}class ze extends f{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ze.name,t,403)}}class Ue extends f{constructor(t){super(Ue.name,t,409)}}class Ge extends c{constructor(t){super(t,Ge.name,500)}}class Ke extends c{constructor(t){super(t,Ke.name,500)}}class qe extends c{constructor(t){super(t,qe.name,500)}}class Ye extends c{constructor(t){super(t,Ye.name,500)}}class Ve extends c{constructor(t){super(t,Ve.name,500)}}class We extends c{constructor(t,e=We.name,r=590){super(t,e,r)}}class Je extends c{constructor(t){super(t,Je.name,591)}}class Qe extends c{constructor(t){super(t,Qe.name,592)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Fe||(Fe={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(De||(De={}));class Xe extends Bt{constructor(t){Ne.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await Ne.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new c(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await Ne.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await Ne.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await Ne.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Dt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._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(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new Me(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new it(i);default:return new Me(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=jt.for(Xe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=Be.fabricIdFromCertificate(r),o=Be.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new xe({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=Xe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new y("Could not find enrollment with id "+t);let s;try{s=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new c(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new c(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ze extends t{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new u(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}St([e(),Et("design:type",String)],Ze.prototype,"affiliation",void 0),St([a(1),Et("design:type",Array)],Ze.prototype,"attrs",void 0),St([e(),Et("design:type",String)],Ze.prototype,"enrollmentID",void 0),St([e(),Et("design:type",String)],Ze.prototype,"enrollmentSecret",void 0),St([o(0),Et("design:type",Number)],Ze.prototype,"maxEnrollments",void 0),St([e(),Et("design:type",String)],Ze.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(ke||(ke={}));let tr=class extends t{constructor(t){super(t)}};St([xt("Stores the original timestamp of creation"),V(),st(),Et("design:type",Date)],tr.prototype,"createdAt",void 0),St([xt("Stores the timestamp of the last update"),V(),nt(),Et("design:type",Date)],tr.prototype,"updatedAt",void 0),St([xt("Stores the version of the model"),V(),w(),Et("design:type",Number)],tr.prototype,"version",void 0),tr=St([Nt(Oe),Et("design:paramtypes",[Object])],tr);let er=class extends tr{constructor(t){super(t)}};function rr(t){if(t)return"string"==typeof t?t:t.getMSPID()}function ir(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],s=r.clientIdentity.getID(),n=await this.tokenRepository.select(),a=await n.execute(r);if(0==a.length)throw new y("No tokens avaialble");if(a.length>1)throw new y("To many token available : "+a.length);if(a[0].owner!=s)throw new it(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function sr(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function nr(){return It.for(Se.OWNED_BY).define({decorator:()=>(t,r)=>Tt(e(),A(),v(),C(sr),$t(Ot.key(Se.FABRIC,Se.OWNED_BY),r))(t,r),args:[]}).apply()}async function ar(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function or(){return It.for(Se.TRANSACTION_ID).define({decorator:()=>(t,r)=>Tt(e(),v(),C(ar),S(ar),$t(Ot.key(Se.FABRIC,r,Se.TRANSACTION_ID),r))(t,r),args:[]}).apply()}async function cr(e,r,i){let s=r;if("string"!=typeof s)try{const n=t.ownerOf(e)||i.get("stub").getCreator().toString();r&&"function"==typeof r&&(s=await r(e,n,i))}catch(t){throw new c("Failed to resolve collection mirror name: "+t)}if(!s||"string"!=typeof s)throw new c("No collection found model "+e.constructor.name);return s}async function lr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e,o=s;a.put("mirror",!0),a.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(o,e);e.logger.info(`Mirror for ${t.tableName(this.class)} created with ${t.pk(s)}: ${i[t.pk(s)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function dr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e,o=s;a.put("mirror",!0),a.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(o,e),e.logger.info(`Mirror for ${t.tableName(this.class)} updated: ${s[t.pk(s)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function hr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e;a.put("mirror",!0),a.put("mirrorCollection",n),a.put("segregated",n);try{const r=s[t.pk(s)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.tableName(this.class)} deleted: ${r+""}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0),a.put("segregated",void 0)}}async function ur(t,e,r,i){const s=rr(t.get("identity"));if(s&&(s===e.mspId||e.condition&&e.condition(s)))throw new it(`Organization ${s} is not authorized to modify mirrored data`)}async function gr(t,e,r,i){const s=rr(t.get("identity"));if(!s)return;const n=await cr(i,e.resolver,t),a=t;(s===e.mspId||e.condition&&e.condition(s))&&(t.logger.info(`Mirror read: MSP ${s} matches, routing reads to mirror collection ${n}`),a.put("mirror",!0),a.put("mirrorCollection",n),a.put("fullySegregated",!0),a.readFrom(n))}function pr(t,e,r){const i="string"!=typeof e&&!!e,s=i?void 0:e,n=i?e:r;return It.for(Se.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Tt(Rt(Ot.key(Se.FABRIC,Se.MIRROR),i),E(gr,i,{priority:30}),C(ur,i,{priority:20}),S(ur,i,{priority:20}),O(ur,i,{priority:20}),C(lr,i,{priority:100}),S(dr,i,{priority:100}),O(hr,i,{priority:100}))},args:[t,s,n]}).apply()}St([xt("Stores the creator"),V(),at(),Et("design:type",String)],er.prototype,"createdBy",void 0),St([xt("Stores the user that last updated the model"),V(),ot(),Et("design:type",String)],er.prototype,"updatedBy",void 0),er=St([Nt(Oe),Et("design:paramtypes",[Object])],er),t.prototype.isShared=function(){return t.isShared(this.constructor)},t.prototype.isPrivate=function(){return t.isPrivate(this.constructor)},t.prototype.segregate=function(){return t.segregate(this)},t.segregate=(e=>{if(!t.isTransient(e))return{model:e};const r=Ot.getAttributes(e.constructor)||[],i=Ot.get(e.constructor,b.TRANSIENT),s=Ot.get(e.constructor,Se.PRIVATE),n=Ot.get(e.constructor,Se.SHARED),a={model:{},public:{},transient:{},privates:{},shared:{}},o=Object.keys(i||{}),c=Object.keys(s||{}),l=Object.keys(n||{});for(const t of r){const r=e[t],i=o.includes(t),s=!i,n=c.includes(t),d=l.includes(t);(i||n||d)&&(a.transient=a.transient||{},a.transient[t]=r),n&&(a.privates=a.privates||{},a.privates[t]=r),d&&(a.shared=a.shared||{},a.shared[t]=r),s&&(a.public=a.public||{},a.public[t]=r)}return a.model=t.build(a.public,e.constructor.name),a}).bind(t),t.isPrivate=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Se.PRIVATE)).bind(t),t.isShared=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Se.SHARED)).bind(t),t.mirrored=(t=>Ot.get("function"!=typeof t?t.constructor:t,Ot.key(Se.FABRIC,Se.MIRROR))).bind(t),t.ownerOf=(t=>{const e=Ot.get(t.constructor,Ot.key(Se.FABRIC,Se.OWNED_BY));if(e)return t[e]}).bind(t),t.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Ot.get(t,Ot.key(Se.FABRIC,Se.MIRROR)))).bind(t),t.collectionsFor=(t=>{const e=[Se.PRIVATE],r=[Se.SHARED],i=Ot.key(...e),s=Ot.key(...r),n="function"==typeof t?t:t.constructor,a=Ot.get(n,i),o=Ot.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(t);const fr=(e,r)=>{const i=r||("function"!=typeof e?t.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!i)throw new c(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Lt(s.name)}${i?Lt(i):""}`};function mr(e){return(r,i)=>{const s=i||("function"!=typeof r?t.ownerOf(r):void 0),n="function"==typeof r?r:r.constructor;if(!s)throw new c(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${s?Lt(s):""}`}}const yr=(e,r)=>{const i=r||("function"!=typeof e?t.ownerOf(e):void 0);if(!i)throw new c(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Lt(i)}PrivateCollection`},wr=35;function br(e,r,i){r.length>0&&i.readFrom(r),!i.isFullySegregated&&r.length&&((e=>{const r=Ot.getAttributes(e)||[],i=t.pk(e),s=Ot.get(e,b.TRANSIENT)||{},n=Ot.get(e,Ot.key(Se.PRIVATE))||{},a=Ot.get(e,Ot.key(Se.SHARED))||{};return r.some(t=>t!==i&&!(t in s)&&!(t in n)&&!(t in a))})(e.constructor)||i.markFullySegregated())}async function Ar(e,r,i){if(!r)return;const s=t.mirroredAt(e);if(!s)return;if(!(r===s.mspId||s.condition&&s.condition(r)))return;const n=await cr(new e,s.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)}async function vr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=t.ownerOf(s)||rr(e.get("identity"));if(!a)return;const o=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(s,a,e);i&&!o.includes(i)&&o.push(i)}br(s,o,e);const c=t.sequenceName(s,"pk");e.setSequenceSegregation(c,e.isFullySegregated,o)}async function Cr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=Array.isArray(i)?i:[i];if(a.length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const o=t.ownerOf(s)||rr(e.get("identity"));if(!o)throw new u("There's no assigned organization for model "+s.constructor.name);const l=n[0].collections,d="string"==typeof l?l:l(s,o,e);a.forEach((t,r)=>{const i="string"==typeof n[r].collections?n[r].collections:n[r].collections(s,o,e);if(i!==d)throw new ct(`Segregated data collection mismatch: ${i} vs ${d}`)});const h=a.map(t=>t+"");e.writeTo(d,h)}async function Sr(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||rr(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:await o(s,a,e);e.readFrom(l)}async function Er(e,r,i,s,n){const a=Array.isArray(r)?r:[r],o=Array.isArray(i)?i:[i];if(o.length!==a.length)throw new c("Segregated data keys and metadata length mismatch");const l=t.ownerOf(s)||rr(e.get("identity"));if(!l)throw new u("There's no assigned organization for model "+s.constructor.name);const d=a[0].collections,h="string"==typeof d?d:d(s,l,e);o.forEach((t,r)=>{const i="string"==typeof a[r].collections?a[r].collections:a[r].collections(s,l,e);if(i!==h)throw new ct(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=o.map(t=>t+"");e.writeTo(h,g)}async function Or(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||rr(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:o(s,a,e);e.readFrom(l)}function xr(t,e,r){return(r,i)=>{const s=[];if(!i){const i=Ot.getAttributes(r);return i?.forEach(i=>{xr(t,e)(r.prototype,i)}),r}{const r="string"==typeof t?t:t.toString(),i=r+":data",n={collections:t},a={priority:35,group:r+":extract"};s.push(Ft(),x(),(r,i)=>{const s=Ot.key(e,i),n=r.constructor,a=Ot.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],Ot.set(n,s,a);const c=Ot.get(n,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],Ot.set(n,e,c);const d={...Ot.get(n,b.TRANSIENT)||{},[i]:{}};Ot.set(n,b.TRANSIENT,d)},N(I.ALL,vr,n,a),C(Cr,{collections:t},{priority:95,group:i}),E(Sr,{collections:t},{priority:95,group:i}),S(Er,{collections:t},{priority:95,group:i}),O(Or,{collections:t},{priority:95,group:i}))}return Tt(...s)(r,i)}}function Nr(t=yr){return It.for(Se.PRIVATE).define({decorator:t=>xr(t,Se.PRIVATE),args:[t]}).apply()}function Ir(t){return It.for(Se.SHARED).define({decorator:t=>xr(t,Se.SHARED),args:[t]}).apply()}function Tr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Tr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Tr(t[r]),e),{})}class $r extends i{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=Ot.modelName(e.constructor)}catch(t){i=void 0}r[s.ANCHOR]=i||e.constructor.name;const n=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return t.relations(e).forEach(t=>{r[t]=n(r[t])}),r}deserialize(e){const r=JSON.parse(e),i=r[s.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.build(r,i)}serialize(t){return require("json-stringify-deterministic")(Tr(this.preSerialize(t)))}}function Rr(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Fr(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function Dr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new je(`Addition overflow: ${t} + ${e}`);return r}function kr(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new je(`Subtraction overflow: ${t} - ${e}`);return r}function Pr(t){if(!/^\d+$/.test(t))throw new u(n("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new u(n("Failed to parse: {0}","string is not a parsable integer"));return e}class Br extends i{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Tr(this.preSerialize(t,e)))}preSerialize(e,r=!0){const i=Object.assign({},e);let n;try{n=Ot.modelName(e.constructor)}catch(t){n=void 0}function a(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(a):this.preSerialize(t)}return r&&(i[s.ANCHOR]=n||e.constructor.name),t.relations(e).forEach(t=>{i[t]=a.call(this,i[t])}),i}}class jr extends lt{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new c("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(t,e){const r=e.logger.for(this.getUser),{caName:i,caCert:s,caKey:n,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+s);const l=await Ne.getFirstDirFileNameContent(s);let d;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new c(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),d=await Ne.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await Ne.getCAUser("admin",d,l,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,K.INITIALIZATION,!0)).for(this.initialize),[i]=t;if(!i)throw new c("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:l}=n,d=o[0];e.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const h=await Ne.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new Dt(s,{trustedRoots:Buffer.from(h),verify:l},a),g=await this.getUser(i,r);return e.debug("CA user loaded: "+g.getName()),{config:i,client:u}}async getCertificates(t,e=!0,...r){t instanceof X?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=(await this.logCtx(r,l.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new Me(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new it(i);default:return new Me(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,l.READ,!0)).for(this.read);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=(await this.logCtx(a,"register",!0)).for(this.register);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=Be.fabricIdFromCertificate(s),c=Be.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new xe({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=jr.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=(await this.logCtx(a,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async updateIdentity(t,e,r,...i){const{log:s,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{s.info("Renewing identity for "+t);const a=this.client.newIdentityService(),o=await a.getOne(t,this.user);await a.update(t,r,this.user);const c=Kt.createUser(t,"",this.user.getMspid(),e.certificate,e.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(o.result.attrs||[]).map(({name:t})=>({name:t,optional:!1})),d=await this.client.reenroll(c,l),h=jr.identityFromEnrollment(d,this.config.caName,n);s.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=Ie(e.certificate);return await this.revoke(t,{aki:u,serial:g},i),s.debug("Renew identity successful for "+t),h}catch(t){throw this.parseError(t)}}async revoke(t,e,...r){const{log:i}=(await this.logCtx(r,"revoke",!0)).for(this.revoke);i.verbose("Revoking identity with enrollment ID "+t);const s=await this.read(t);if(!s)throw new y("Could not find enrollment with id "+t);let n;try{const t={reason:e.serial||e.aki?"Revoke User Certificate":"User Deletion",...e,enrollmentID:s.id};n=await this.client.revoke(t,this.user)}catch(e){throw new c(`Could not revoke enrollment with id ${t}: ${e}`)}if(!n.success)throw new c(`Could not revoke enrollment with id ${t}: ${n.errors.join("\n")}`);return n}}var Lr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Lr||(Lr={}));const _r=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Mr=new kt("fabric-fs");async function Hr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function zr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await rt(import("fs"));return await e.readFile(t)})(t)}async function Ur(t,e,r,i){Mr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Kt(t),n=Kt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Gr(t,e){return{mspId:t,credentials:await Hr(e,async t=>{const{promises:e}=await rt(import("fs")),r=await Kr(t);return await e.readFile(r)})}}async function Kr(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path"));return r(t,(await e.readdir(t))[0])}async function qr(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function Yr(t){const e=await Hr(t,async t=>{const{promises:e}=await rt(import("fs")),r=await Kr(t);return await e.readFile(r)}),r=await Vr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return zt.newPrivateKeySigner(i)}async function Vr(t){let e;if(Pt())e=globalThis.crypto.subtle;else{const t=await rt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new c(t)}}function Wr(t){if(!t)return"\0";const e=Array.from(t);for(let t=e.length-1;t>=0;t-=1){const r=e[t].codePointAt(0);if(void 0!==r&&1114111>r)return e[t]=String.fromCodePoint(r+1),e.slice(0,t+1).join("")}return t+"\0"}class Jr extends dt{constructor(t,e){super(t,e)}squash(t){const e=super.squash(t);if(!e)return e;const{method:r,params:i,args:s}=e,{direction:n,limit:a}=i;switch(r){case U.FIND:break;case U.PAGE:s.push(n,a);break;case U.FIND_BY:break;case U.LIST_BY:s.push(n);break;case U.PAGE_BY:s.push(n,a);break;case U.FIND_ONE_BY:break;default:throw new c("Unsupported method "+r)}return e}async executePrepared(...t){const e=z.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return e.statement(r,...i,...t)}async prepare(t){if(t=t||await this.adapter.context(K.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},i={class:this.fromSelector,args:e,params:r},s=[ht.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);s.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&s.push(ht.SELECT,this.selectSelector.join(` ${ht.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(s.push(ht.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),i.method=_t(s.join(" ")),i.params=r,this.prepared=i,this}processRecord(t,e,r,i){if(t[k.ID]){const[,...e]=t[k.ID].split(k.SEPARATOR),s=e.join("_");return this.adapter.revert(t,this.fromSelector,Q.parseValue(r,s),void 0,i)}return t}async raw(e,...r){const{ctx:i}=this.logCtx(r,this.raw),s=e?.aggregateInfo;if(e?.aggregate&&s)return this.executeAggregate(s,i);const n=await this.adapter.raw(e,!0,this.fromSelector,i),a=t.pk(this.fromSelector),o=Ot.get(this.fromSelector,Ot.key(b.ID,a))?.type;return this.selectSelector?n:n.map(t=>this.processRecord(t,a,o,i))}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const i={};i[k.TABLE]={},i[k.TABLE]=t.tableName(this.fromSelector);const s={selector:i};if(this.selectSelector&&(s.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(ut.and(this.whereCondition,ut.attribute(k.TABLE).eq(s.selector[k.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(P).indexOf(r[0]))switch(r[0]){case P.AND:t[P.AND]=[...Object.values(t[P.AND]).reduce((t,e)=>{const r=Object.keys(e);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===P.AND?t.push(...e[i]):t.push(e),t},[])],s.selector=t;break;case P.OR:{const e={};e[P.AND]=[t,...Object.entries(s.selector).map(([t,e])=>{const r={};return r[t]=e,r})],s.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{s.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${s.selector[t]} by ${r}`),s.selector[t]=r})}if(this.orderBySelectors?.length){s.sort=s.sort||[],s.selector=s.selector||{};for(const[t,e]of this.orderBySelectors){const r=t,i={};i[r]=e,s.sort.push(i),s.selector[r]||(s.selector[r]={},s.selector[r][B.BIGGER]=null)}}return this.limitSelector?s.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+j),s.limit=j),this.offsetSelector&&(s.skip=this.offsetSelector),s}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===gt.STARTS_WITH){if("string"!=typeof e)throw new pt("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new pt("STARTS_WITH requires a string comparison");const t={start:s=i,end:Wr(s)},r={};return r[e]={},r[e][B.BIGGER_EQ]=t.start,r[e][B.SMALLER]=t.end,{selector:r}}var s,n;if(r===gt.ENDS_WITH){if("string"!=typeof e)throw new pt("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new pt("ENDS_WITH requires a string comparison");const t={};return t[e]={[B.REGEXP]:(n=i,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===gt.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new pt("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][L(gt.BIGGER_EQ)]=r,n[t][L(gt.SMALLER_EQ)]=s,{selector:n}}let a={};if(-1===[ft.AND,ft.OR,gt.NOT].indexOf(r))a[e]={},a[e][L(r)]=i;else if(r===gt.NOT)a=this.parseCondition(e).selector,a[L(gt.NOT)]={},a[L(gt.NOT)][e.attr1]=i;else{const t=this.parseCondition(e).selector,s=this.parseCondition(i).selector;a=((t,e,r)=>{const i={selector:{}};return i.selector[t]=[e,r],i})(L(r),t,s).selector}return{selector:a}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const t=this.avgSelector+"",e=this.createAggregateDescriptor("sum",t),r=this.createAggregateDescriptor("count",t);if(!e||!r)throw new pt("Avg operation requires sum and count views for attribute "+t);return this.createAggregateQuery({kind:"avg",attribute:t,sumDescriptor:e.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const t=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",e=this.createAggregateDescriptor("distinct",t);if(e)return e.countDistinct=!0,this.createAggregateQuery(e)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[t,e]of r){const r=e?e+"":void 0,i=this.createAggregateDescriptor(t,r);if(i)return this.createAggregateQuery(i)}if(e)throw new pt(`No CouchDB view metadata found for table ${t.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const i=_(this.fromSelector,e,r);if(!i.length)return;const s=i[0],n=t.tableName(this.fromSelector),a=M(n,s.attribute,e,s),o=s.ddoc||H(n,a),c={reduce:void 0!==s.reduce||!s.returnDocs};return"distinct"!==e&&"groupBy"!==e||(c.group=!0),{kind:e,meta:s,descriptor:{ddoc:o,view:a,options:c}}}createAggregateQuery(t){return{selector:{},aggregate:!0,aggregateInfo:t}}getFabricAdapter(){return this.adapter}async executeAggregate(t,e){if(!this.isViewAggregate(t))return this.handleAverage(t,e);const r=this.getFabricAdapter(),i=t,s=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,e);return this.processViewResponse(t,s)}async handleAverage(t,e){if("avg"!==t.kind)throw new pt("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,s]=[t.sumDescriptor,t.countDescriptor],[n,a]=await Promise.all([r.view(i.ddoc,i.view,i.options,e),r.view(s.ddoc,s.view,s.options,e)]),o=n.rows?.[0]?.value??0,c=a.rows?.[0]?.value??0;return c?o/c:0}processViewResponse(t,e){if("avg"===t.kind)throw new pt("Average results should be handled before processing rows");const r=e.rows||[],i=t,s=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(t=>t.key??t.value):s.returnDocs?r.map(t=>t.value??t.doc??t):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(t){return"avg"!==t.kind}}class Qr extends q{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new ct("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var Xr;class Zr extends mt{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new be}static{this.log=jt.for(Zr)}constructor(t,e){super(Object.assign({},_r,t),Oe,e),this.serializer=Zr.serializer}Statement(t){return new Jr(this,t)}Paginator(t,e,r){return new Qr(this,t,e,r)}async flags(t,e,r,...i){const s=Object.assign({},this.config,r);return Object.assign(await super.flags(t,e,s,...i))}async context(e,r,i,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.tableName(e)):t.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let n=s.pop();void 0===n||n instanceof X||(s.push(n),n=void 0),r=n?Object.assign({},n.toOverrides(),r):r;const a=await this.flags("string"==typeof e?e:e.name,i,r,...[...s,n].filter(Boolean));if(n){if(!(n instanceof this.Context)){const t=(new this.Context).accumulate({...n.cache,...a,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],t]}),t}const t=n.getOrUndefined("operation"),r=n.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const t=(new this.Context).accumulate({...n.cache,...a,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],t]}),t}return n.accumulate(a)}return(new this.Context).accumulate({...a})}decode(t){return Zr.decoder.decode(t)}repository(){return fe}createPrefix(e,r,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),a=t.tableName(e),o={};return o[k.TABLE]=a,Object.assign(o,i),[e,r,o,...n]}createAllPrefix(e,r,i,...s){const n=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(s,this.createAllPrefix),o=r.map((t,e)=>{const r={};return r[k.TABLE]=n,Object.assign(r,i[e]),r});return[e,r,o,...a]}updateAllPrefix(e,r,i,...s){const n=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(s,this.updateAllPrefix),o=r.map(()=>{const t={};return t[k.TABLE]=n,t});return[e,r,o,...a]}async createAll(e,r,i,...s){if(r.length!==i.length)throw new c("Ids and models must have the same length");const n=[...s],a=n.shift(),{log:o,ctx:l}=this.logCtx(n,this.createAll),d=t.tableName(e);o.info(`adding ${r.length} entries to ${d} table`),o.verbose("pks: "+r);const h=a&&Object.keys(a).length>0,u=h||this.shouldForceGatewayHydration(l),p=h?{[d]:a}:{},f=await this.submitTransaction(l,T.CREATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],p,this.getEndorsingOrganizations(l),e.name);let m;try{m=JSON.parse(this.decode(f)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,u,m[0][t.pk(e)]||r[0])?this.readAll(e,ve(e,i.map((e,r)=>t.merge(Object.assign({},e,a[r]||{}),m[r])),r),l):m}async readAll(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.readAll),a=t.tableName(e);s.info(`reading ${r.length} entries to ${a} table`),s.verbose("pks: "+r);const o=await this.evaluateTransaction(n,T.READ_ALL,[JSON.stringify(r)],void 0,void 0,e.name);try{return JSON.parse(this.decode(o)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}async updateAll(e,r,i,...s){if(r.length!==i.length)throw new c("Ids and models must have the same length");const n=[...s],a=n.shift(),{log:o,ctx:l}=this.logCtx(n,this.updateAll),d=t.tableName(e);o.info(`updating ${r.length} entries to ${d} table`),o.verbose("pks: "+r);const h=a&&Object.keys(a).length>0,u=h||this.shouldForceGatewayHydration(l),p=h?{[d]:a}:{},f=await this.submitTransaction(l,T.UPDATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],p,this.getEndorsingOrganizations(l),e.name);let m;try{m=JSON.parse(this.decode(f)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,u,r[0])?this.readAll(e,ve(e,i.map((e,r)=>t.merge(Object.assign({},e,a[r]||{}),m[r])),r),l):m}async deleteAll(e,r,...i){const{log:s,ctx:n,ctxArgs:a}=this.logCtx(i,this.deleteAll),o=t.tableName(e),c=t.isTransient(e)||this.shouldForceGatewayHydration(n);let l;const d=this.shouldRefreshAfterWrite(e,n,c,r[0]);d&&(l=await this.readAll(e,r,...a)),s.info(`deleting ${r.length} entries to ${o} table`),s.verbose("pks: "+r);const h=await this.submitTransaction(n,T.DELETE_ALL,[JSON.stringify(r)],void 0,this.getEndorsingOrganizations(n),e.name);try{return d?l:JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}prepare(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.prepare),n=t.segregate(e);e[K.METADATA]&&(i.silly("Passing along persistence metadata for "+e[K.METADATA]),Object.defineProperty(n.model,K.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[K.METADATA]}));const a=t.mirroredAt(e);if(a){const t=a.mspId;if(!t)throw new c("No mirror MSP could be found");const e=this.getEndorsingOrganizations(s)||[],r=[...new Set([...e,t])];s.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:n.model,model:n.model,id:e[t.pk(e.constructor)],transient:n.transient,privates:n.privates,shared:n.shared}}revert(t,e,r,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.revert);return i&&this.shouldRebuildWithTransient(a,a.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,t])=>void 0!==t).forEach(([e,r])=>{e in t&&void 0!==t[e]&&n.warn(`overwriting existing ${e}. if this is not a default value, this may pose a problem`),t[e]=r})),new e(t)}shouldRebuildWithTransient(t,e){if(!t)return!1;if(t.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof t.getFromChildren?t.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(t,e);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(t,e){return e||("function"==typeof t.getFromChildren?t.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,s){if(!i)return!1;const n=t.pk(e),a=t.composed(e,n),o=t.generated(e,n),c=null!=s;return!(c||!a)||(!c&&o?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}getEndorsingOrganizations(t){const e=t.getOrUndefined("endorsingOrgs")||t.getOrUndefined("endorsingOrgs");return e&&e.length?e:t.getFromChildren("endorsingOrgs")||t.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(t){return!!this.config.allowGatewayOverride}async create(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.create),d=t.tableName(e);o.verbose(`adding entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h||this.shouldForceGatewayHydration(c),g=h?{[d]:s}:{},p=await this.submitTransaction(c,l.CREATE,[this.serializer.serialize(i,e.name)],g,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,ve(e,t.merge(Object.assign({},i,s||{}),f,e),r),c):f}async healthcheck(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.healthcheck),n=t.tableName(e);i.verbose(`reading entry from ${n} table`);const a=await this.evaluateTransaction(s,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(a))}async read(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.read),a=t.tableName(e);s.verbose(`reading entry from ${a} table`),s.debug("pk: "+r);const o=await this.evaluateTransaction(n,l.READ,[r.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(o))}updatePrefix(e,r,i,...s){const n=t.tableName(e),{ctxArgs:a}=this.logCtx(s,this.updatePrefix),o={};return o[k.TABLE]=n,Object.assign(o,i),[e,r,o,...a]}async update(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.update);o.info("CLIENT UPDATE class : "+typeof e);const d=t.tableName(e);o.verbose(`updating entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h||this.shouldForceGatewayHydration(c),g=h?{[d]:s}:{},p=await this.submitTransaction(c,l.UPDATE,[this.serializer.serialize(i,e.name||e)],g,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,ve(e,t.merge(Object.assign({},i,s||{}),f,e),r),c):f}async delete(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.delete),a=t.tableName(e),o=t.isTransient(e)||this.shouldForceGatewayHydration(n);let c;const d=this.shouldRefreshAfterWrite(e,n,o,r);d&&(c=await this.read(e,r,n)),s.verbose(`deleting entry from ${a} table`),s.debug("pk: "+r);const h=await this.submitTransaction(n,l.DELETE,[r.toString()],void 0,this.getEndorsingOrganizations(n),e.name);return d?c:this.serializer.deserialize(this.decode(h))}async raw(e,r=!0,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.raw),o=i.name;let c,l;n.info("Performing raw statement on table "+t.tableName(i));try{c=await this.evaluateTransaction(a,"raw",[JSON.stringify(e),r],void 0,void 0,o)}catch(t){throw this.parseError(t)}try{l=JSON.parse(this.decode(c))}catch(t){throw new g("Failed to process result: "+t)}if(Array.isArray(l)){if(!l.length)return l;const e=l[0];return t.isModel(e)?l.map(e=>t.build(e)):l}return d=l,t.isModel(d)?t.build(d):d;var d}async view(t,e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.view);let a,o;s.info(`Querying view ${t}/${e}`);try{a=await this.evaluateTransaction(n,"view",[t,e,JSON.stringify(r)],void 0,void 0,void 0)}catch(t){throw this.parseError(t)}try{o=JSON.parse(this.decode(a))}catch(t){throw new g("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=Zr.getClient(this.config)),this._client}async Gateway(t){return Zr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return Zr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s={},n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:Object.entries(s).reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}),endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,e,d)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(t){return!!t.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(t){return(t||[]).map(t=>"string"==typeof t?t:JSON.stringify(t))}buildLegacyTransient(t){if(!t)return;const e=Object.entries(t);if(!e.length)return;const r={};for(const[t,i]of e)r[t]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(t){const e=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}],r=(this.getEndorsingOrganizations(t)?.filter(t=>!!t)||[]).filter(t=>t!==this.config.mspId);if(!r.length)return e;const i=this.config.mspMap;for(const t of r){const r=i?.[t];if(!r?.length)throw new ct(`No peer mapping available for MSP ${t}. Provide it via config.mspMap`);const s=r[Math.floor(Math.random()*r.length)];if(!s.endpoint)throw new ct(`Invalid peer mapping for MSP ${t}: missing endpoint`);e.push({mspId:t,peerEndpoint:s.endpoint,peerHostAlias:s.alias,tlsCert:s.tlsCert||this.config.tlsCert})}return e}async submitLegacyWithExplicitEndorsers(t,e,r,i,s,n){const a=this.log.for(this.submitLegacyWithExplicitEndorsers),o=this.normalizeLegacyPeers(s),c=await this.resolveLegacyIdentityMaterial(),l=await Zt.newInMemoryWallet(),d=this.config.mspId+"-legacy";await l.put(d,{credentials:{certificate:c.certificate,privateKey:c.privateKey},mspId:this.config.mspId,type:"X.509"});const h=await this.buildLegacyConnectionProfile(o),u=new te;try{await u.connect(h,{identity:d,wallet:l,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(o)},tlsInfo:{certificate:c.certificate,key:c.privateKey}});const t=await u.getNetwork(this.config.channel),s=t.getContract(this.config.chaincodeName,this.getContractName(n)).createTransaction(e);i&&s.setTransient(i);const g=o.map(e=>t.getChannel().getEndorser(e.name)).filter(t=>!!t);g.length&&s.setEndorsingPeers(g),a.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${e} via peers ${o.map(t=>t.peerEndpoint).join(", ")}`);const p=await s.submit(...r);return Uint8Array.from(p)}catch(t){throw this.parseError(t)}finally{u.disconnect()}}normalizeLegacyPeers(t){const e=new Map,r=t=>{const r=`${t.peerEndpoint}|${t.peerHostAlias||""}`;if(e.has(r))return;const i=`peer-${t.mspId}-${e.size}`;e.set(r,{...t,name:i})};return t.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(e.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(t){const e={},r={},i={};for(const s of t){const t=await this.readPemInput(s.tlsCert||this.config.tlsCert),n=s.peerHostAlias||this.extractHost(s.peerEndpoint);e[s.name]={url:this.ensureGrpcUrl(s.peerEndpoint),tlsCACerts:{pem:t},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[s.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[s.mspId]=i[s.mspId]||{mspid:s.mspId,peers:[]},i[s.mspId].peers.push(s.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:e,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(t){return t.every(t=>this.isLocalEndpoint(t.peerEndpoint))}isLocalEndpoint(t){const e=this.extractHost(t).toLowerCase();return"localhost"===e||"127.0.0.1"===e}extractHost(t){return t.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(t){return/^grpcs?:\/\//i.test(t)?t:"grpcs://"+t}async readPemInput(t){if(!t)throw new c("Missing certificate or key material");if(Buffer.isBuffer(t))return t.toString("utf8");const e=t.trim();if(/-----BEGIN [A-Z ]+-----/.test(e))return e;const r=await ee.promises.stat(t).catch(()=>{});return r?.isDirectory()?await qr(t):(await zr(t)).toString()}parseError(t){return Zr.parseError(t)}async submitTransaction(t,e,r,i,s,n){if(this.shouldUseLegacyGateway(t)){const s=this.prepareLegacyArgs(r),a=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs(t);return this.submitLegacyWithExplicitEndorsers(t,e,s,a,o,n)}return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=jt.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.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(ee.readFileSync(r,"utf8"))}catch(t){throw new c(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Qt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Xt(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=jt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Gr(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+Be.fabricIdFromCertificate(s.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let n;if(e.hsm)throw new ct("HSM NOT IMPLEMENTED");n=await Yr(e.keyCertOrDirectoryPath);const a={client:t,identity:s,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 "+e.mspId);const o=Ut(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new Zr._baseDispatch}static parseError(t){let e="string"==typeof t?t:t.message;return t instanceof Gt&&t.details.length&&10===t.code&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new qe(t):e.includes("DEADLINE_EXCEEDED")?new Je(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ve(t):e.includes("PHANTOM_READ_CONFLICT")?new Ye(t):t instanceof Error&&t.code&&9===t.code?new Ke(t):e.includes(u.name)?new u(t):e.includes(y.name)?new y(t):e.includes(m.name)?new m(t):e.includes($.name)?new $(t):e.includes(pt.name)?new pt(t):e.includes(yt.name)?new yt(t):e.includes(ct.name)?new ct(t):e.includes(wt.name)?new wt(t):e.includes(bt.name)?new bt(t):e.includes(it.name)?new it(t):e.includes(At.name)?new At(t):e.includes(vt.name)?new vt(t):e.includes(g.name)?new g(t):new c(t)}}St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"create",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,X]),Et("design:returntype",Promise)],Zr.prototype,"healthcheck",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"read",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"update",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"delete",null),St([Mt(),Et("design:type",Function),Et("design:paramtypes",[Object,"function"==typeof(Xr="undefined"!=typeof D&&D)?Xr:Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"raw",null),St([Mt(),Et("design:type",Function),Et("design:paramtypes",[String,String,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"view",null),Zr.decoration(),mt.setCurrent(Oe);class ti extends Ct{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof Zr))throw new ct("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(e,r,i,...s){const{log:n,ctxArgs:a}=mt.logCtx(this.updateObservers,r,!1,...s);if(this.adapter)try{await this.adapter.refresh(e,r,i,...a)}catch(t){throw new c("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.tableName(e)}:${r}`)}async handleEvents(e){if(!this.listeningStack)throw new c('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new c("No adapter found. should be impossible");const r=e||await this.adapter.context(l.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t),i=this.log.for(this.handleEvents);i.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:s,event:n,owner:a}=Fr(e.eventName);if(a&&a!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(s?t.get(s):t.get(this.models[0].name))??(s||this.models[0]?.name);await this.updateObservers(e,n,o.id,r)}catch(t){i.error(`Failed update observables for table ${s} event ${n} id: ${o.id}: ${t}`)}}}catch(t){i.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new c("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t),{ctx:r}=this.logCtx([e],this.initialize),i=(await Zr.getGateway(r,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new c("No adapter observed for dispatch");this.listeningStack=await i.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(r)}}Zr&&(Zr._baseDispatch=ti);const ei="##VERSION##",ri="##PACKAGE##";Ot.registerLibrary(ri,ei);export{_e as AllowanceError,$e as BASE_ALPHABET,Le as BalanceError,Pe as BaseEncoder,Lr as CA_ROLE,Re as CRYPTO,be as ClientSerializer,Ne as CoreUtils,Be as CryptoUtils,_r as DefaultFabricClientFlags,$r as DeterministicSerializer,ke as ERC20Events,Ke as EndorsementError,Ve as EndorsementPolicyError,tr as FabricBaseModel,Zr as FabricClientAdapter,ti as FabricClientDispatch,fe as FabricClientRepository,Ae as FabricERC20ClientRepository,Xe as FabricEnrollmentService,Oe as FabricFlavour,er as FabricIdentifiedBaseModel,jr as FabricIdentityService,Se as FabricModelKeys,De as HFCAIdentityAttributes,Fe as HFCAIdentityType,xe as Identity,Ce as IdentityCredentials,Ee as IdentityType,yr as ImplicitPrivateCollection,He as MissingContextError,Ge as MissingPKCSS11Lib,fr as ModelCollection,qe as MvccReadConflictError,mr as NamespaceCollection,Ue as NotInitializedError,je as OverflowError,ir as Owner,ri as PACKAGE_NAME,Ye as PhantomReadConflictError,Me as RegistrationError,Ze as RegistrationRequestBuilder,wr as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,Br as SimpleDeterministicSerializer,Qe as TransactionBufferSizeError,We as TransactionLimitsError,Je as TransactionTimeoutError,ze as UnauthorizedPrivateDataAccess,ei as VERSION,Dr as add,Ar as applyMirrorFlags,br as applySegregationFlags,le as collectionFor,Hr as contentOfLoadFile,lr as createMirrorHandler,hr as deleteMirrorHandler,cr as evalMirrorMetadata,ue as extractCollections,ve as extractIds,rr as extractMspId,Vr as extractPrivateKey,vr as extractSegregatedCollections,Rr as generateFabricEventName,se as generateModelDesignDocs,ie as generateModelIndexes,Ie as getAkiAndSerialFromCert,Ur as getCAUser,Kr as getFirstDirFileName,qr as getFirstDirFileNameContent,Gr as getIdentity,Yr as getSigner,pr as mirror,ur as mirrorWriteGuard,nr as ownedBy,sr as ownedByOnCreate,Fr as parseEventName,de as privateCollectionFor,Nr as privateData,zr as readFile,gr as readMirrorHandler,ne as readModelFile,ae as readModelFolders,Pr as safeParseInt,Cr as segregatedDataOnCreate,Or as segregatedDataOnDelete,Sr as segregatedDataOnRead,Er as segregatedDataOnUpdate,he as sharedCollectionFor,Ir as sharedData,Tr as sortKeysOnlyRecursive,kr as sub,or as transactionId,ar as transactionIdOnCreate,dr as updateMirrorHandler,pe as writeCollectionDesignDocs,ge as writeCollections,ce as writeDesignDocs,oe as writeIndexes};
1
+ import{Model as t,required as e,model as r,JSONSerializer as i,ModelKeys as s,stringFormat as n,minlength as a,min as o}from"@decaf-ts/decorator-validation";import{InternalError as c,OperationKeys as l,enforceDBDecorators as d,reduceErrorsToPrint as h,ValidationError as u,SerializationError as g,composeAttributeValue as p,BaseError as f,ConflictError as m,NotFoundError as y,version as w,DBKeys as b,generated as A,readonly as v,onCreate as C,onUpdate as S,onRead as E,onDelete as O,transient as x,on as N,DBOperations as I,BulkCrudOperationKeys as T,BadRequestError as $}from"@decaf-ts/db-decorators";import{generateIndexes as R,generateViews as F,CouchDBKeys as k,CouchDBGroupOperator as P,CouchDBOperator as B,CouchDBQueryLimit as j,translateOperators as L,findViewMetadata as _,generateViewName as M,generateDesignDocName as H}from"@decaf-ts/for-couchdb";import{Repository as z,PreparedStatementKeys as U,OrderDirection as G,PersistenceKeys as K,Paginator as q,pk as Y,column as V,table as W,BaseModel as J,Sequence as Q,Context as X,oneToOne as Z,Cascade as tt,index as et,normalizeImport as rt,AuthorizationError as it,createdAt as st,updatedAt as nt,createdBy as at,updatedBy as ot,UnsupportedError as ct,ClientBasedService as lt,Statement as dt,QueryClause as ht,Condition as ut,Operator as gt,QueryError as pt,GroupOperator as ft,Adapter as mt,PagingError as yt,MigrationError as wt,ObserverError as bt,ForbiddenError as At,ConnectionError as vt,Dispatch as Ct}from"@decaf-ts/core";import{__decorate as St,__metadata as Et}from"tslib";import{Metadata as Ot,description as xt,uses as Nt,Decoration as It,apply as Tt,propMetadata as $t,metadata as Rt,prop as Ft}from"@decaf-ts/decoration";import Dt from"fabric-ca-client";import{MiniLogger as kt,isBrowser as Pt,LoggedClass as Bt,Logging as jt,toPascalCase as Lt,toCamelCase as _t,debug as Mt,final as Ht}from"@decaf-ts/logging";import{signers as zt,connect as Ut,GatewayError as Gt}from"@hyperledger/fabric-gateway";import{User as Kt}from"fabric-common";import qt,{X509Certificate as Yt}from"crypto";import*as Vt from"@peculiar/x509";import{X509Certificate as Wt}from"@peculiar/x509";import{Crypto as Jt}from"@peculiar/webcrypto";import*as Qt from"@grpc/grpc-js";import{Client as Xt}from"@grpc/grpc-js";import{Wallets as Zt,Gateway as te}from"fabric-network";import ee from"fs";function re(t){const e=require("fs"),r=require("path").dirname(t);if(e.existsSync(r))return!0;re(r),e.mkdirSync(r)}function ie(t){return R([t])}function se(t,e){const r=F([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function ne(e){const r=require("path"),i=require(r.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof t}catch(e){return!1}})}async function ae(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...ne(e))}return r}function oe(t,e=process.cwd(),r){const i=require("fs"),s=require("path");t.forEach(t=>{const n=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));re(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))})}function ce(t,e=process.cwd(),r){if(!t.length)return;const i=require("fs"),s=require("path");t.forEach(t=>{const n=t._id.replace(/^_design\//,""),a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));re(a);const o={...t};delete o._rev,i.writeFileSync(a,JSON.stringify(o,void 0,2))})}function le(t,e,r,i,s,n,a){return{name:t,policy:e,requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n,memberOnlyWrite:a}}function de(t,e=t+"Private",r=0,i=0,s=0,n=!0,a=!0){const o=le(e,`OR('${t}.member')`,r,i,s,n,a);return o.endorsementPolicy={signaturePolicy:`OR('${t}.peer')`},o}function he(t,e,r=1,i=2,s=0,n=!0,a=!0){const o=le(e,`OR(${t.map(t=>`'${t}.member'`).join(",")})`,r,i,s,n,a);return o.endorsementPolicy={signaturePolicy:`AND(${t.map(t=>`'${t}.peer'`).join(",")})`},o}async function ue(e,r,i={},s=!1){let{privateCols:n,sharedCols:a}=t.collectionsFor(e);function o(t){try{return"string"==typeof t?t:t(e,r[0])}catch(t){throw new c(t)}}n=n.map(o),a=a.map(o);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},i?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},i?.sharedCols||{}),h=s?t.mirroredAt(e):void 0,u=r.map(t=>n.map(e=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n}=l;return de(t,e,r,i,s,n,!1)})).flat();if(h&&h.mspId){const t="string"==typeof h.resolver?h.resolver:h.resolver(e,h.mspId);if(t&&!u.some(e=>e.name===t&&e.policy.includes(h.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:s}=l;u.push(de(h.mspId,t,e,r,i,s,!1))}}return{privates:u,shared:a.map(t=>{const{requiredPeerCount:e,maxPeerCount:i,blockToLive:s,memberOnlyRead:n,memberOnlyWrite:a}=d;return he(r,t,e,i,s,n,a)})}}function ge(t,e=process.cwd(),r="collections_config"){const i=require("fs"),s=require("path"),n=s.resolve(s.join(e,`./META-INF/${r}.json`));!function t(e){const r=s.dirname(e);if(i.existsSync(r))return!0;t(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))}function pe(t,e=process.cwd(),r){t?.length&&ce(t,e,r)}class fe extends z{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(t){return super.override(Object.assign({},t,this._overrides)).for(t)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,U.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${t.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${t.tableName(this.class)} by ${e} ${r}`),await this.statement(this.listBy.name,e,r,...n)}async findBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...n)}async findOneBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...n)}async find(e,r=G.ASC,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,U.FIND,!0)).for(this.find);return s.verbose(`finding ${t.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...n)}async page(e,r=G.ASC,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,U.PAGE,!0)).for(this.page);return n.verbose(`paging ${t.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...a)}async statement(e,...r){const{log:i,ctx:s,ctxArgs:n}=(await this.logCtx(r,K.STATEMENT,!0)).for(this.statement);i.verbose("Executing prepared statement "+e);const a=n.slice(0,-1),o=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(s,K.STATEMENT,[e,JSON.stringify(a)],void 0,void 0,this.class.name)));return Array.isArray(o)?o.map(e=>e[k.TABLE]&&e[k.TABLE]===t.tableName(this.class)?new this.class(e):e):o[k.TABLE]&&o[k.TABLE]===t.tableName(this.class)?new this.class(o):q.isSerializedPage(o)?Object.assign(o,{data:o.data.map(t=>new this.class(t))}):o}async countOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.tableName(this.class)}${e?" by "+e:""}`);const n=e?[e,...s]:s;return this.statement(U.COUNT_OF,...n)}async maxOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.tableName(this.class)}`),this.statement(U.MAX_OF,e,...s)}async minOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.tableName(this.class)}`),this.statement(U.MIN_OF,e,...s)}async avgOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.tableName(this.class)}`),this.statement(U.AVG_OF,e,...s)}async sumOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.tableName(this.class)}`),this.statement(U.SUM_OF,e,...s)}async distinctOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.tableName(this.class)}`),this.statement(U.DISTINCT_OF,e,...s)}async groupOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,U.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.tableName(this.class)} by ${e}`),this.statement(U.GROUP_OF,e,...s)}async healthcheck(...t){const{ctxArgs:e}=this.logCtx(t,this.healthcheck);return await this.adapter.healthcheck(this.class,...e)}async create(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.create);s.debug(`Creating new ${this.class.name} in table ${t.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const a=this.adapter.prepare(e,i),{record:o,id:c,transient:l}=a,d=await this.adapter.create(this.class,c,o,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:s,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const a=this.adapter.prepare(e,n),{id:o,transient:c}=a;let l=a.record;return s.debug(`updating ${this.class.name} in table ${t.tableName(this.class)} with id ${o}`),l=await this.adapter.update(this.class,o,l,c,...i),this.adapter.revert(l,this.class,o,c,n)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,l.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await d(this,r,t,l.CREATE,l.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=h(i);if(s)throw new u(s)}return[t,...i]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=a.map(t=>t.record),l=a.map(t=>t.transient),d=await this.adapter.createAll(this.class,o,c,l,...n);return Promise.all(d.map(async(t,e)=>{const r=o[e];return this.adapter.revert(t,this.class,r,l[e],i)}))}async updateAll(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.updateAll);s.debug(`Updating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=await this.adapter.updateAll(this.class,o,a.map(t=>t.record),a.map(t=>t.transient),...n);return Promise.all(c.map(async(t,e)=>{const r=o[e];return this.adapter.revert(t,this.class,r,a[e].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.mirroredAt(r)&&e.accumulate({legacy:!0})}}let me=class extends J{constructor(t){super(t)}};St([Y({type:String}),Et("design:type",String)],me.prototype,"name",void 0),St([V(),e(),Et("design:type",String)],me.prototype,"owner",void 0),St([V(),e(),Et("design:type",String)],me.prototype,"symbol",void 0),St([V(),e(),Et("design:type",Number)],me.prototype,"decimals",void 0),me=St([W("erc20_tokens"),r(),Et("design:paramtypes",[Object])],me);let ye=class extends J{constructor(t){super(t)}};St([Y({type:String}),Et("design:type",String)],ye.prototype,"id",void 0),St([V(),e(),Et("design:type",String)],ye.prototype,"token",void 0),St([V(),e(),Et("design:type",Number)],ye.prototype,"balance",void 0),St([V(),Et("design:type",String)],ye.prototype,"captive",void 0),ye=St([W("erc20_wallets"),r(),Et("design:paramtypes",[Object])],ye);let we=class extends J{constructor(t){super(t)}};St([Y({type:String}),V(),e(),Et("design:type",String)],we.prototype,"owner",void 0),St([V(),e(),Et("design:type",String)],we.prototype,"spender",void 0),St([V(),e(),Et("design:type",Number)],we.prototype,"value",void 0),we=St([W("erc20_allowances"),r(),Et("design:paramtypes",[Object])],we);class be extends i{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=Ot.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new g("Could not find metadata for "+t.constructor.name);i=e}return r[s.ANCHOR]=i,r}deserialize(e){const r=JSON.parse(e),i=r[s.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.build(r,i)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Ae extends fe{static{this.serializer=new be}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,r,i,...s){if(!this.observerHandler)throw new c("ObserverHandler not initialized. Did you register any observables?");const{log:n,ctxArgs:a}=this.logCtx(s,this.updateObservers);let o;n.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.get(e):e,o=void 0===i?void 0:Array.isArray(i)?i.map(r=>Q.parseValue(t.sequenceFor(e).type,r)):Q.parseValue(t.sequenceFor(e).type,i),await this.observerHandler.updateObservers(e,r,o,...a)}decode(t){return Ae.decoder.decode(t)}constructor(t){super(t,ye),this.serializer=Ae.serializer}async tokenName(...t){const{ctx:e}=(await this.logCtx(t,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(e,"TokenName");return this.decode(r)}async symbol(...t){const{ctx:e}=(await this.logCtx(t,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(e,"Symbol");return this.decode(r)}async decimals(...t){const{ctx:e}=(await this.logCtx(t,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(e,"Decimals");return Number(this.decode(r))}async totalSupply(...t){const{ctx:e}=(await this.logCtx(t,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(e,"TotalSupply");return Number(this.decode(r))}async balanceOf(t,...e){const{ctx:r}=(await this.logCtx(e,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[t]);return Number(this.decode(i))}async transfer(t,e,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),s=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(s)}async transferFrom(t,e,r){const i=await X.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(i.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(n)}async approve(t,e){const r=await X.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),s=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(s)}async allowance(t,e){const r=await X.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),s=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(s))}async initialize(t){const e=await X.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Ae.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await X.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.checkInitialized);await this.adapter.evaluateTransaction(e,"CheckInitialized")}async mint(t){const e=await X.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[t.toString()])}async burn(t){const e=await X.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[t.toString()])}async burnFrom(t,e){const r=await X.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await X.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(e,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const t=await X.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(e,"ClientAccountID");return this.decode(r)}}function ve(e,r,i){let s,n,a;function o(r,i){if(s=s||t.pk(e),a=a||t.sequenceFor(e),n=n||t.composed(e,s),n)return p(r,n);const o=r[s]||i;if(void 0===o)throw new c("could not rebuild id for "+r.constructor.name);return o}if(Array.isArray(r)){if(!Array.isArray(i)||i.length!==r.length)throw new c("inconsistent parameters. both must be arrays of equal length");return r.map((t,e)=>o(t,i[e]))}return o(r,i)}let Ce=class extends J{constructor(t){super(t)}};var Se,Ee;St([xt("Unique identifier of the credentials record"),V(),Y(),Et("design:type",String)],Ce.prototype,"id",void 0),St([xt("PEM-encoded X.509 certificate for the identity"),V(),e(),Et("design:type",String)],Ce.prototype,"certificate",void 0),St([xt("PEM-encoded root or intermediate certificate"),V(),e(),Et("design:type",String)],Ce.prototype,"rootCertificate",void 0),St([xt("PEM-encoded private key"),V(),e(),Et("design:type",String)],Ce.prototype,"privateKey",void 0),Ce=St([r(),Et("design:paramtypes",[Object])],Ce),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(Se||(Se={})),(t=>{t.X509="X.509"})(Ee||(Ee={}));const Oe="hlf-fabric";let xe=class extends J{constructor(t){super(t),this.type=Ee.X509}};St([xt("Unique identifier of the identity"),Y(),Et("design:type",String)],xe.prototype,"id",void 0),St([Z(Ce,{update:tt.CASCADE,delete:tt.CASCADE}),Et("design:type",Ce)],xe.prototype,"credentials",void 0),St([V(),e(),et(),Et("design:type",String)],xe.prototype,"mspId",void 0),St([V(),e(),Et("design:type",String)],xe.prototype,"type",void 0),xe=St([r(),Et("design:paramtypes",[Object])],xe);class Ne{static{this.logger=new kt(Ne.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await rt(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(n("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new Kt(t),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);a.setCryptoSuite(c);const l=s?.hsm?await this.getHSMEnrollmentKey(c,r,s.hsm):this.getSoftwareEnrollmentKey(c,e);return await a.setEnrollment(l,r,i),a}static getCryptoSuite(t){return t?(Ne.cryptoSuite||(Ne.cryptoSuite=Kt.newCryptoSuite(t)),Ne.cryptoSuite):Kt.newCryptoSuite()}static getSoftwareEnrollmentKey(t,e){if(!e)throw Error("Private key must be provided when HSM configuration is not supplied");return t.createKeyFromRaw(e)}static async getHSMEnrollmentKey(t,e,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(e),s=await t.getKey(i);if(!s||"function"==typeof s.isPrivate&&!s.isPrivate())throw Error("Unable to resolve private key from HSM");return s}static async getCertificateSKI(t){const e=new Yt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return qt.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){return{mspId:t,credentials:await this.contentOfLoadFile(e,async t=>{const{promises:e}=await rt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await rt(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await rt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return zt.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await rt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function Ie(t){const e=new Wt(t),r=e.extensions?.find(t=>"2.5.29.35"===t.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:e.serialNumber}}const Te=new Jt;var $e,Re,Fe,De,ke;Vt.cryptoProvider.set(Te),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})($e||($e={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(Re||(Re={}));class Pe{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}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(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const s=t.length;for(;i!==s&&0===t[i];)i++,e++;const n=(s-i)*this.iFactor+1>>>0,a=new Uint8Array(n);for(;i!==s;){let e=t[i],s=0;for(let t=n-1;(0!==e||r>s)&&-1!==t;t--,s++)e+=256*a[t]>>>0,a[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=s,i++}let o=n-r;for(;o!==n&&0===a[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(a[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const s=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(s);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=s-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=s-i;for(;a!==s&&0===n[a];)a++;const o=new Uint8Array(r+(s-a));let c=r;for(;a!==s;)o[c++]=n[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class Be{static{this.b58encoder=new Pe($e.BASE58)}static{this.logger=new kt(Be.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(n("Parsing certificate: {0}",t));const e=new Vt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(n("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=Te.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await Te.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Vt.X509Certificate(t),s=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,Te.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Vt.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const s=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(s)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return Pt()?globalThis.window.crypto.subtle:Te.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=Te.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Re.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),s={name:Re.KEY_ALGORYTHM,hash:Re.HASH,salt:i,iterations:Re.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Re.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:Re.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Re.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Re.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class je extends c{constructor(t){super(t,je.name)}}class Le extends c{constructor(t){super(t,Le.name)}}class _e extends c{constructor(t){super(t,_e.name)}}class Me extends it{constructor(t){super(t,Me.name)}}class He extends c{constructor(t){super(t,He.name,500)}}class ze extends f{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ze.name,t,403)}}class Ue extends f{constructor(t){super(Ue.name,t,409)}}class Ge extends c{constructor(t){super(t,Ge.name,500)}}class Ke extends c{constructor(t){super(t,Ke.name,500)}}class qe extends c{constructor(t){super(t,qe.name,500)}}class Ye extends c{constructor(t){super(t,Ye.name,500)}}class Ve extends c{constructor(t){super(t,Ve.name,500)}}class We extends c{constructor(t,e=We.name,r=590){super(t,e,r)}}class Je extends c{constructor(t){super(t,Je.name,591)}}class Qe extends c{constructor(t){super(t,Qe.name,592)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Fe||(Fe={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(De||(De={}));class Xe extends Bt{constructor(t){Ne.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await Ne.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new c(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await Ne.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await Ne.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await Ne.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Dt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._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(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new Me(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new it(i);default:return new Me(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=jt.for(Xe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=Be.fabricIdFromCertificate(r),o=Be.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new xe({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=Xe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new y("Could not find enrollment with id "+t);let s;try{s=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new c(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new c(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ze extends t{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new u(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}St([e(),Et("design:type",String)],Ze.prototype,"affiliation",void 0),St([a(1),Et("design:type",Array)],Ze.prototype,"attrs",void 0),St([e(),Et("design:type",String)],Ze.prototype,"enrollmentID",void 0),St([e(),Et("design:type",String)],Ze.prototype,"enrollmentSecret",void 0),St([o(0),Et("design:type",Number)],Ze.prototype,"maxEnrollments",void 0),St([e(),Et("design:type",String)],Ze.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(ke||(ke={}));let tr=class extends t{constructor(t){super(t)}};St([xt("Stores the original timestamp of creation"),V(),st(),Et("design:type",Date)],tr.prototype,"createdAt",void 0),St([xt("Stores the timestamp of the last update"),V(),nt(),Et("design:type",Date)],tr.prototype,"updatedAt",void 0),St([xt("Stores the version of the model"),V(),w(),Et("design:type",Number)],tr.prototype,"version",void 0),tr=St([Nt(Oe),Et("design:paramtypes",[Object])],tr);let er=class extends tr{constructor(t){super(t)}};function rr(t){if(t)return"string"==typeof t?t:t.getMSPID()}function ir(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],s=r.clientIdentity.getID(),n=await this.tokenRepository.select(),a=await n.execute(r);if(0==a.length)throw new y("No tokens avaialble");if(a.length>1)throw new y("To many token available : "+a.length);if(a[0].owner!=s)throw new it(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function sr(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function nr(){return It.for(Se.OWNED_BY).define({decorator:()=>(t,r)=>Tt(e(),A(),v(),C(sr),$t(Ot.key(Se.FABRIC,Se.OWNED_BY),r))(t,r),args:[]}).apply()}async function ar(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function or(){return It.for(Se.TRANSACTION_ID).define({decorator:()=>(t,r)=>Tt(e(),v(),C(ar),S(ar),$t(Ot.key(Se.FABRIC,r,Se.TRANSACTION_ID),r))(t,r),args:[]}).apply()}async function cr(e,r,i){let s=r;if("string"!=typeof s)try{const n=t.ownerOf(e)||i.get("stub").getCreator().toString();r&&"function"==typeof r&&(s=await r(e,n,i))}catch(t){throw new c("Failed to resolve collection mirror name: "+t)}if(!s||"string"!=typeof s)throw new c("No collection found model "+e.constructor.name);return s}async function lr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e,o=s;a.put("mirror",!0),a.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(o,e);e.logger.info(`Mirror for ${t.tableName(this.class)} created with ${t.pk(s)}: ${i[t.pk(s)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function dr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e,o=s;a.put("mirror",!0),a.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(o,e),e.logger.info(`Mirror for ${t.tableName(this.class)} updated: ${s[t.pk(s)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function hr(e,r,i,s){const n=await cr(s,r.resolver,e),a=e;a.put("mirror",!0),a.put("mirrorCollection",n),a.put("segregated",n);try{const r=s[t.pk(s)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.tableName(this.class)} deleted: ${r+""}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0),a.put("segregated",void 0)}}async function ur(t,e,r,i){const s=rr(t.get("identity"));if(s&&(s===e.mspId||e.condition&&e.condition(s)))throw new it(`Organization ${s} is not authorized to modify mirrored data`)}async function gr(t,e,r,i){const s=rr(t.get("identity"));if(!s)return;const n=await cr(i,e.resolver,t),a=t;(s===e.mspId||e.condition&&e.condition(s))&&(t.logger.info(`Mirror read: MSP ${s} matches, routing reads to mirror collection ${n}`),a.put("mirror",!0),a.put("mirrorCollection",n),a.put("fullySegregated",!0),a.readFrom(n))}function pr(t,e,r){const i="string"!=typeof e&&!!e,s=i?void 0:e,n=i?e:r;return It.for(Se.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Tt(Rt(Ot.key(Se.FABRIC,Se.MIRROR),i),E(gr,i,{priority:30}),C(ur,i,{priority:20}),S(ur,i,{priority:20}),O(ur,i,{priority:20}),C(lr,i,{priority:100}),S(dr,i,{priority:100}),O(hr,i,{priority:100}))},args:[t,s,n]}).apply()}St([xt("Stores the creator"),V(),at(),Et("design:type",String)],er.prototype,"createdBy",void 0),St([xt("Stores the user that last updated the model"),V(),ot(),Et("design:type",String)],er.prototype,"updatedBy",void 0),er=St([Nt(Oe),Et("design:paramtypes",[Object])],er),t.prototype.isShared=function(){return t.isShared(this.constructor)},t.prototype.isPrivate=function(){return t.isPrivate(this.constructor)},t.prototype.segregate=function(){return t.segregate(this)},t.segregate=(e=>{if(!t.isTransient(e))return{model:e};const r=Ot.getAttributes(e.constructor)||[],i=Ot.get(e.constructor,b.TRANSIENT),s=Ot.get(e.constructor,Se.PRIVATE),n=Ot.get(e.constructor,Se.SHARED),a={model:{},public:{},transient:{},privates:{},shared:{}},o=Object.keys(i||{}),c=Object.keys(s||{}),l=Object.keys(n||{});for(const t of r){const r=e[t],i=o.includes(t),s=!i,n=c.includes(t),d=l.includes(t);(i||n||d)&&(a.transient=a.transient||{},a.transient[t]=r),n&&(a.privates=a.privates||{},a.privates[t]=r),d&&(a.shared=a.shared||{},a.shared[t]=r),s&&(a.public=a.public||{},a.public[t]=r)}return a.model=t.build(a.public,e.constructor.name),a}).bind(t),t.isPrivate=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Se.PRIVATE)).bind(t),t.isShared=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Se.SHARED)).bind(t),t.mirrored=(t=>Ot.get("function"!=typeof t?t.constructor:t,Ot.key(Se.FABRIC,Se.MIRROR))).bind(t),t.ownerOf=(t=>{const e=Ot.get(t.constructor,Ot.key(Se.FABRIC,Se.OWNED_BY));if(e)return t[e]}).bind(t),t.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Ot.get(t,Ot.key(Se.FABRIC,Se.MIRROR)))).bind(t),t.collectionsFor=(t=>{const e=[Se.PRIVATE],r=[Se.SHARED],i=Ot.key(...e),s=Ot.key(...r),n="function"==typeof t?t:t.constructor,a=Ot.get(n,i),o=Ot.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(t);const fr=(e,r)=>{const i=r||("function"!=typeof e?t.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!i)throw new c(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Lt(s.name)}${i?Lt(i):""}`};function mr(e){return(r,i)=>{const s=i||("function"!=typeof r?t.ownerOf(r):void 0),n="function"==typeof r?r:r.constructor;if(!s)throw new c(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${s?Lt(s):""}`}}const yr=(e,r)=>{const i=r||("function"!=typeof e?t.ownerOf(e):void 0);if(!i)throw new c(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Lt(i)}PrivateCollection`},wr=35;function br(e,r,i){r.length>0&&i.readFrom(r),!i.isFullySegregated&&r.length&&((e=>{const r=Ot.getAttributes(e)||[],i=t.pk(e),s=Ot.get(e,b.TRANSIENT)||{},n=Ot.get(e,Ot.key(Se.PRIVATE))||{},a=Ot.get(e,Ot.key(Se.SHARED))||{};return r.some(t=>t!==i&&!(t in s)&&!(t in n)&&!(t in a))})(e.constructor)||i.markFullySegregated())}async function Ar(e,r,i){if(!r)return;const s=t.mirroredAt(e);if(!s)return;if(!(r===s.mspId||s.condition&&s.condition(r)))return;const n=await cr(new e,s.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)}async function vr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=t.ownerOf(s)||rr(e.get("identity"));if(!a)return;const o=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(s,a,e);i&&!o.includes(i)&&o.push(i)}br(s,o,e);const c=t.sequenceName(s,"pk");e.setSequenceSegregation(c,e.isFullySegregated,o)}async function Cr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=Array.isArray(i)?i:[i];if(a.length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const o=t.ownerOf(s)||rr(e.get("identity"));if(!o)throw new u("There's no assigned organization for model "+s.constructor.name);const l=n[0].collections,d="string"==typeof l?l:l(s,o,e);a.forEach((t,r)=>{const i="string"==typeof n[r].collections?n[r].collections:n[r].collections(s,o,e);if(i!==d)throw new ct(`Segregated data collection mismatch: ${i} vs ${d}`)});const h=a.map(t=>t+"");e.writeTo(d,h)}async function Sr(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||rr(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:await o(s,a,e);e.readFrom(l)}async function Er(e,r,i,s,n){const a=Array.isArray(r)?r:[r],o=Array.isArray(i)?i:[i];if(o.length!==a.length)throw new c("Segregated data keys and metadata length mismatch");const l=t.ownerOf(s)||rr(e.get("identity"));if(!l)throw new u("There's no assigned organization for model "+s.constructor.name);const d=a[0].collections,h="string"==typeof d?d:d(s,l,e);o.forEach((t,r)=>{const i="string"==typeof a[r].collections?a[r].collections:a[r].collections(s,l,e);if(i!==h)throw new ct(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=o.map(t=>t+"");e.writeTo(h,g)}async function Or(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||rr(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:o(s,a,e);e.readFrom(l)}function xr(t,e,r){return(r,i)=>{const s=[];if(!i){const i=Ot.getAttributes(r);return i?.forEach(i=>{xr(t,e)(r.prototype,i)}),r}{const r="string"==typeof t?t:t.toString(),i=r+":data",n={collections:t},a={priority:35,group:r+":extract"};s.push(Ft(),x(),(r,i)=>{const s=Ot.key(e,i),n=r.constructor,a=Ot.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],Ot.set(n,s,a);const c=Ot.get(n,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],Ot.set(n,e,c);const d={...Ot.get(n,b.TRANSIENT)||{},[i]:{}};Ot.set(n,b.TRANSIENT,d)},N(I.ALL,vr,n,a),C(Cr,{collections:t},{priority:95,group:i}),E(Sr,{collections:t},{priority:95,group:i}),S(Er,{collections:t},{priority:95,group:i}),O(Or,{collections:t},{priority:95,group:i}))}return Tt(...s)(r,i)}}function Nr(t=yr){return It.for(Se.PRIVATE).define({decorator:t=>xr(t,Se.PRIVATE),args:[t]}).apply()}function Ir(t){return It.for(Se.SHARED).define({decorator:t=>xr(t,Se.SHARED),args:[t]}).apply()}function Tr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Tr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Tr(t[r]),e),{})}class $r extends i{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=Ot.modelName(e.constructor)}catch(t){i=void 0}r[s.ANCHOR]=i||e.constructor.name;const n=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return t.relations(e).forEach(t=>{r[t]=n(r[t])}),r}deserialize(e){const r=JSON.parse(e),i=r[s.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.build(r,i)}serialize(t){return require("json-stringify-deterministic")(Tr(this.preSerialize(t)))}}function Rr(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Fr(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function Dr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new je(`Addition overflow: ${t} + ${e}`);return r}function kr(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new je(`Subtraction overflow: ${t} - ${e}`);return r}function Pr(t){if(!/^\d+$/.test(t))throw new u(n("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new u(n("Failed to parse: {0}","string is not a parsable integer"));return e}class Br extends i{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Tr(this.preSerialize(t,e)))}preSerialize(e,r=!0){const i=Object.assign({},e);let n;try{n=Ot.modelName(e.constructor)}catch(t){n=void 0}function a(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(a):this.preSerialize(t)}return r&&(i[s.ANCHOR]=n||e.constructor.name),t.relations(e).forEach(t=>{i[t]=a.call(this,i[t])}),i}}class jr extends lt{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new c("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(t,e){const r=e.logger.for(this.getUser),{caName:i,caCert:s,caKey:n,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+s);const l=await Ne.getFirstDirFileNameContent(s);let d;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new c(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),d=await Ne.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await Ne.getCAUser("admin",d,l,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,K.INITIALIZATION,!0)).for(this.initialize),[i]=t;if(!i)throw new c("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:l}=n,d=o[0];e.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const h=await Ne.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new Dt(s,{trustedRoots:Buffer.from(h),verify:l},a),g=await this.getUser(i,r);return e.debug("CA user loaded: "+g.getName()),{config:i,client:u}}async getCertificates(t,e=!0,...r){t instanceof X?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=(await this.logCtx(r,l.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new Me(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new it(i);default:return new Me(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,l.READ,!0)).for(this.read);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=(await this.logCtx(a,"register",!0)).for(this.register);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=Be.fabricIdFromCertificate(s),c=Be.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new xe({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=jr.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=(await this.logCtx(a,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async updateIdentity(t,e,r,...i){const{log:s,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{s.info("Renewing identity for "+t);const a=this.client.newIdentityService(),o=await a.getOne(t,this.user);await a.update(t,r,this.user);const c=Kt.createUser(t,"",this.user.getMspid(),e.certificate,e.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(o.result.attrs||[]).map(({name:t})=>({name:t,optional:!1})),d=await this.client.reenroll(c,l),h=jr.identityFromEnrollment(d,this.config.caName,n);s.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=Ie(e.certificate);return await this.revoke(t,{aki:u,serial:g},i),s.debug("Renew identity successful for "+t),h}catch(t){throw this.parseError(t)}}async revoke(t,e,...r){const{log:i}=(await this.logCtx(r,"revoke",!0)).for(this.revoke);i.verbose("Revoking identity with enrollment ID "+t);const s=await this.read(t);if(!s)throw new y("Could not find enrollment with id "+t);let n;try{const t={reason:e.serial||e.aki?"Revoke User Certificate":"User Deletion",...e,enrollmentID:s.id};n=await this.client.revoke(t,this.user)}catch(e){throw new c(`Could not revoke enrollment with id ${t}: ${e}`)}if(!n.success)throw new c(`Could not revoke enrollment with id ${t}: ${n.errors.join("\n")}`);return n}}var Lr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Lr||(Lr={}));const _r=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Mr=new kt("fabric-fs");async function Hr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function zr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await rt(import("fs"));return await e.readFile(t)})(t)}async function Ur(t,e,r,i){Mr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Kt(t),n=Kt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Gr(t,e){return{mspId:t,credentials:await Hr(e,async t=>{const{promises:e}=await rt(import("fs")),r=await Kr(t);return await e.readFile(r)})}}async function Kr(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path"));return r(t,(await e.readdir(t))[0])}async function qr(t){const{promises:e}=await rt(import("fs")),{join:r}=await rt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function Yr(t){const e=await Hr(t,async t=>{const{promises:e}=await rt(import("fs")),r=await Kr(t);return await e.readFile(r)}),r=await Vr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return zt.newPrivateKeySigner(i)}async function Vr(t){let e;if(Pt())e=globalThis.crypto.subtle;else{const t=await rt(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new c(t)}}function Wr(t){if(!t)return"\0";const e=Array.from(t);for(let t=e.length-1;t>=0;t-=1){const r=e[t].codePointAt(0);if(void 0!==r&&1114111>r)return e[t]=String.fromCodePoint(r+1),e.slice(0,t+1).join("")}return t+"\0"}class Jr extends dt{constructor(t,e){super(t,e)}squash(t){const e=super.squash(t);if(!e)return e;const{method:r,params:i,args:s}=e,{direction:n,limit:a}=i;switch(r){case U.FIND:break;case U.PAGE:s.push(n,a);break;case U.FIND_BY:break;case U.LIST_BY:s.push(n);break;case U.PAGE_BY:s.push(n,a);break;case U.FIND_ONE_BY:break;default:throw new c("Unsupported method "+r)}return e}async executePrepared(...t){const e=z.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return e.statement(r,...i,...t)}async prepare(t){if(t=t||await this.adapter.context(K.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},i={class:this.fromSelector,args:e,params:r},s=[ht.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);s.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&s.push(ht.SELECT,this.selectSelector.join(` ${ht.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(s.push(ht.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),i.method=_t(s.join(" ")),i.params=r,this.prepared=i,this}processRecord(t,e,r,i){if(t[k.ID]){const[,...e]=t[k.ID].split(k.SEPARATOR),s=e.join("_");return this.adapter.revert(t,this.fromSelector,Q.parseValue(r,s),void 0,i)}return t}async raw(e,...r){const{ctx:i}=this.logCtx(r,this.raw),s=e?.aggregateInfo;if(e?.aggregate&&s)return this.executeAggregate(s,i);const n=await this.adapter.raw(e,!0,this.fromSelector,i),a=t.pk(this.fromSelector),o=Ot.get(this.fromSelector,Ot.key(b.ID,a))?.type;return this.selectSelector?n:n.map(t=>this.processRecord(t,a,o,i))}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const i={};i[k.TABLE]={},i[k.TABLE]=t.tableName(this.fromSelector);const s={selector:i};if(this.selectSelector&&(s.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(ut.and(this.whereCondition,ut.attribute(k.TABLE).eq(s.selector[k.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(P).indexOf(r[0]))switch(r[0]){case P.AND:t[P.AND]=[...Object.values(t[P.AND]).reduce((t,e)=>{const r=Object.keys(e);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===P.AND?t.push(...e[i]):t.push(e),t},[])],s.selector=t;break;case P.OR:{const e={};e[P.AND]=[t,...Object.entries(s.selector).map(([t,e])=>{const r={};return r[t]=e,r})],s.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{s.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${s.selector[t]} by ${r}`),s.selector[t]=r})}if(this.orderBySelectors?.length){s.sort=s.sort||[],s.selector=s.selector||{};for(const[t,e]of this.orderBySelectors){const r=t,i={};i[r]=e,s.sort.push(i),s.selector[r]||(s.selector[r]={},s.selector[r][B.BIGGER]=null)}}return this.limitSelector?s.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+j),s.limit=j),this.offsetSelector&&(s.skip=this.offsetSelector),s}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===gt.STARTS_WITH){if("string"!=typeof e)throw new pt("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new pt("STARTS_WITH requires a string comparison");const t={start:s=i,end:Wr(s)},r={};return r[e]={},r[e][B.BIGGER_EQ]=t.start,r[e][B.SMALLER]=t.end,{selector:r}}var s,n;if(r===gt.ENDS_WITH){if("string"!=typeof e)throw new pt("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new pt("ENDS_WITH requires a string comparison");const t={};return t[e]={[B.REGEXP]:(n=i,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===gt.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new pt("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][L(gt.BIGGER_EQ)]=r,n[t][L(gt.SMALLER_EQ)]=s,{selector:n}}let a={};if(-1===[ft.AND,ft.OR,gt.NOT].indexOf(r))a[e]={},a[e][L(r)]=i;else if(r===gt.NOT)a=this.parseCondition(e).selector,a[L(gt.NOT)]={},a[L(gt.NOT)][e.attr1]=i;else{const t=this.parseCondition(e).selector,s=this.parseCondition(i).selector;a=((t,e,r)=>{const i={selector:{}};return i.selector[t]=[e,r],i})(L(r),t,s).selector}return{selector:a}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const t=this.avgSelector+"",e=this.createAggregateDescriptor("sum",t),r=this.createAggregateDescriptor("count",t);if(!e||!r)throw new pt("Avg operation requires sum and count views for attribute "+t);return this.createAggregateQuery({kind:"avg",attribute:t,sumDescriptor:e.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const t=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",e=this.createAggregateDescriptor("distinct",t);if(e)return e.countDistinct=!0,this.createAggregateQuery(e)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[t,e]of r){const r=e?e+"":void 0,i=this.createAggregateDescriptor(t,r);if(i)return this.createAggregateQuery(i)}if(e)throw new pt(`No CouchDB view metadata found for table ${t.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const i=_(this.fromSelector,e,r);if(!i.length)return;const s=i[0],n=t.tableName(this.fromSelector),a=M(n,s.attribute,e,s),o=s.ddoc||H(n,a),c={reduce:void 0!==s.reduce||!s.returnDocs};return"distinct"!==e&&"groupBy"!==e||(c.group=!0),{kind:e,meta:s,descriptor:{ddoc:o,view:a,options:c}}}createAggregateQuery(t){return{selector:{},aggregate:!0,aggregateInfo:t}}getFabricAdapter(){return this.adapter}async executeAggregate(t,e){if(!this.isViewAggregate(t))return this.handleAverage(t,e);const r=this.getFabricAdapter(),i=t,s=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,e);return this.processViewResponse(t,s)}async handleAverage(t,e){if("avg"!==t.kind)throw new pt("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,s]=[t.sumDescriptor,t.countDescriptor],[n,a]=await Promise.all([r.view(i.ddoc,i.view,i.options,e),r.view(s.ddoc,s.view,s.options,e)]),o=n.rows?.[0]?.value??0,c=a.rows?.[0]?.value??0;return c?o/c:0}processViewResponse(t,e){if("avg"===t.kind)throw new pt("Average results should be handled before processing rows");const r=e.rows||[],i=t,s=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(t=>t.key??t.value):s.returnDocs?r.map(t=>t.value??t.doc??t):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(t){return"avg"!==t.kind}}class Qr extends q{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new ct("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var Xr;class Zr extends mt{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new be}static{this.log=jt.for(Zr)}constructor(t,e){super(Object.assign({},_r,t),Oe,e),this.serializer=Zr.serializer}Statement(t){return new Jr(this,t)}Paginator(t,e,r){return new Qr(this,t,e,r)}async flags(t,e,r,...i){const s=Object.assign({},this.config,r);return Object.assign(await super.flags(t,e,s,...i))}async context(e,r,i,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.tableName(e)):t.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let n=s.pop();void 0===n||n instanceof X||(s.push(n),n=void 0),r=n?Object.assign({},n.toOverrides(),r):r;const a=await this.flags("string"==typeof e?e:e.name,i,r,...[...s,n].filter(Boolean));if(n){if(!(n instanceof this.Context)){const t=(new this.Context).accumulate({...n.cache,...a,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],t]}),t}const t=n.getOrUndefined("operation"),r=n.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const t=(new this.Context).accumulate({...n.cache,...a,parentContext:n});return n.accumulate({childContexts:[...n.getOrUndefined("childContexts")||[],t]}),t}return n.accumulate(a)}return(new this.Context).accumulate({...a})}decode(t){return Zr.decoder.decode(t)}repository(){return fe}createPrefix(e,r,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),a=t.tableName(e),o={};return o[k.TABLE]=a,Object.assign(o,i),[e,r,o,...n]}createAllPrefix(e,r,i,...s){const n=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(s,this.createAllPrefix),o=r.map((t,e)=>{const r={};return r[k.TABLE]=n,Object.assign(r,i[e]),r});return[e,r,o,...a]}updateAllPrefix(e,r,i,...s){const n=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(s,this.updateAllPrefix),o=r.map(()=>{const t={};return t[k.TABLE]=n,t});return[e,r,o,...a]}async createAll(e,r,i,...s){if(r.length!==i.length)throw new c("Ids and models must have the same length");const n=[...s],a=n.shift(),{log:o,ctx:l}=this.logCtx(n,this.createAll),d=t.tableName(e);o.info(`adding ${r.length} entries to ${d} table`),o.verbose("pks: "+r);const h=a&&Object.keys(a).length>0,u=h||this.shouldForceGatewayHydration(l),p=h?{[d]:a}:{},f=await this.submitTransaction(l,T.CREATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],p,this.getEndorsingOrganizations(l),e.name);let m;try{m=JSON.parse(this.decode(f)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,u,m[0][t.pk(e)]||r[0])?this.readAll(e,ve(e,i.map((e,r)=>t.merge(Object.assign({},e,a[r]||{}),m[r])),r),l):m}async readAll(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.readAll),a=t.tableName(e);s.info(`reading ${r.length} entries to ${a} table`),s.verbose("pks: "+r);const o=await this.evaluateTransaction(n,T.READ_ALL,[JSON.stringify(r)],void 0,void 0,e.name);try{return JSON.parse(this.decode(o)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}async updateAll(e,r,i,...s){if(r.length!==i.length)throw new c("Ids and models must have the same length");const n=[...s],a=n.shift(),{log:o,ctx:l}=this.logCtx(n,this.updateAll),d=t.tableName(e);o.info(`updating ${r.length} entries to ${d} table`),o.verbose("pks: "+r);const h=a&&Object.keys(a).length>0,u=h||this.shouldForceGatewayHydration(l),p=h?{[d]:a}:{},f=await this.submitTransaction(l,T.UPDATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],p,this.getEndorsingOrganizations(l),e.name);let m;try{m=JSON.parse(this.decode(f)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,u,r[0])?this.readAll(e,ve(e,i.map((e,r)=>t.merge(Object.assign({},e,a[r]||{}),m[r])),r),l):m}async deleteAll(e,r,...i){const{log:s,ctx:n,ctxArgs:a}=this.logCtx(i,this.deleteAll),o=t.tableName(e),c=t.isTransient(e)||this.shouldForceGatewayHydration(n);let l;const d=this.shouldRefreshAfterWrite(e,n,c,r[0]);d&&(l=await this.readAll(e,r,...a)),s.info(`deleting ${r.length} entries to ${o} table`),s.verbose("pks: "+r);const h=await this.submitTransaction(n,T.DELETE_ALL,[JSON.stringify(r)],void 0,this.getEndorsingOrganizations(n),e.name);try{return d?l:JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}prepare(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.prepare),n=t.segregate(e);e[K.METADATA]&&(i.silly("Passing along persistence metadata for "+e[K.METADATA]),Object.defineProperty(n.model,K.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[K.METADATA]}));const a=t.mirroredAt(e);if(a){const t=a.mspId;if(!t)throw new c("No mirror MSP could be found");const e=this.getEndorsingOrganizations(s)||[],r=[...new Set([...e,t])];s.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:n.model,model:n.model,id:e[t.pk(e.constructor)],transient:n.transient,privates:n.privates,shared:n.shared}}revert(t,e,r,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.revert);return i&&this.shouldRebuildWithTransient(a,a.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,t])=>void 0!==t).forEach(([e,r])=>{e in t&&void 0!==t[e]&&n.warn(`overwriting existing ${e}. if this is not a default value, this may pose a problem`),t[e]=r})),new e(t)}shouldRebuildWithTransient(t,e){if(!t)return!1;if(t.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof t.getFromChildren?t.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(t,e);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(t,e){return e||("function"==typeof t.getFromChildren?t.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,s){if(!i)return!1;const n=t.pk(e),a=t.composed(e,n),o=t.generated(e,n),c=null!=s;return!(c||!a)||(!c&&o?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}getEndorsingOrganizations(t){const e=t.getOrUndefined("endorsingOrgs")||t.getOrUndefined("endorsingOrgs");return e&&e.length?e:t.getFromChildren("endorsingOrgs")||t.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(t){return!!this.config.allowGatewayOverride}async create(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.create),d=t.tableName(e);o.verbose(`adding entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h||this.shouldForceGatewayHydration(c),g=h?{[d]:s}:{},p=await this.submitTransaction(c,l.CREATE,[this.serializer.serialize(i,e.name)],g,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,ve(e,t.merge(Object.assign({},i,s||{}),f,e),r),c):f}async healthcheck(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.healthcheck),n=t.tableName(e);i.verbose(`reading entry from ${n} table`);const a=await this.evaluateTransaction(s,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(a))}async read(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.read),a=t.tableName(e);s.verbose(`reading entry from ${a} table`),s.debug("pk: "+r);const o=await this.evaluateTransaction(n,l.READ,[r.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(o))}updatePrefix(e,r,i,...s){const n=t.tableName(e),{ctxArgs:a}=this.logCtx(s,this.updatePrefix),o={};return o[k.TABLE]=n,Object.assign(o,i),[e,r,o,...a]}async update(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.update);o.info("CLIENT UPDATE class : "+typeof e);const d=t.tableName(e);o.verbose(`updating entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h||this.shouldForceGatewayHydration(c),g=h?{[d]:s}:{},p=await this.submitTransaction(c,l.UPDATE,[this.serializer.serialize(i,e.name||e)],g,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(p));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,ve(e,t.merge(Object.assign({},i,s||{}),f,e),r),c):f}async delete(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.delete),a=t.tableName(e),o=t.isTransient(e)||this.shouldForceGatewayHydration(n);let c;const d=this.shouldRefreshAfterWrite(e,n,o,r);d&&(c=await this.read(e,r,n)),s.verbose(`deleting entry from ${a} table`),s.debug("pk: "+r);const h=await this.submitTransaction(n,l.DELETE,[r.toString()],void 0,this.getEndorsingOrganizations(n),e.name);return d?c:this.serializer.deserialize(this.decode(h))}async raw(e,r=!0,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.raw),o=i.name;let c,l;n.info("Performing raw statement on table "+t.tableName(i));try{c=await this.evaluateTransaction(a,"raw",[JSON.stringify(e),r],void 0,void 0,o)}catch(t){throw this.parseError(t)}try{l=JSON.parse(this.decode(c))}catch(t){throw new g("Failed to process result: "+t)}if(Array.isArray(l)){if(!l.length)return l;const e=l[0];return t.isModel(e)?l.map(e=>t.build(e)):l}return d=l,t.isModel(d)?t.build(d):d;var d}async view(t,e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.view);let a,o;s.info(`Querying view ${t}/${e}`);try{a=await this.evaluateTransaction(n,"view",[t,e,JSON.stringify(r)],void 0,void 0,void 0)}catch(t){throw this.parseError(t)}try{o=JSON.parse(this.decode(a))}catch(t){throw new g("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=Zr.getClient(this.config)),this._client}async Gateway(t){return Zr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return Zr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s={},n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:Object.entries(s).reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}),endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,e,d)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(t){return!!t.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(t){return(t||[]).map(t=>"string"==typeof t?t:JSON.stringify(t))}buildLegacyTransient(t){if(!t)return;const e=Object.entries(t);if(!e.length)return;const r={};for(const[t,i]of e)r[t]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(t){const e=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}],r=(this.getEndorsingOrganizations(t)?.filter(t=>!!t)||[]).filter(t=>t!==this.config.mspId);if(!r.length)return e;const i=this.config.mspMap;for(const t of r){const r=i?.[t];if(!r?.length)throw new ct(`No peer mapping available for MSP ${t}. Provide it via config.mspMap`);const s=r[Math.floor(Math.random()*r.length)];if(!s.endpoint)throw new ct(`Invalid peer mapping for MSP ${t}: missing endpoint`);e.push({mspId:t,peerEndpoint:s.endpoint,peerHostAlias:s.alias,tlsCert:s.tlsCert||this.config.tlsCert})}return e}async submitLegacyWithExplicitEndorsers(t,e,r,i,s,n){const a=this.log.for(this.submitLegacyWithExplicitEndorsers),o=this.normalizeLegacyPeers(s),c=await this.resolveLegacyIdentityMaterial(),l=await Zt.newInMemoryWallet(),d=this.config.mspId+"-legacy";await l.put(d,{credentials:{certificate:c.certificate,privateKey:c.privateKey},mspId:this.config.mspId,type:"X.509"});const h=await this.buildLegacyConnectionProfile(o),u=new te;try{await u.connect(h,{identity:d,wallet:l,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(o)},tlsInfo:{certificate:c.certificate,key:c.privateKey}});const t=await u.getNetwork(this.config.channel),s=t.getContract(this.config.chaincodeName,this.getContractName(n)).createTransaction(e);i&&s.setTransient(i);const g=o.map(e=>t.getChannel().getEndorser(e.name)).filter(t=>!!t);g.length&&s.setEndorsingPeers(g),a.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${e} via peers ${o.map(t=>t.peerEndpoint).join(", ")}`);const p=await s.submit(...r);return Uint8Array.from(p)}catch(t){throw this.parseError(t)}finally{u.disconnect()}}normalizeLegacyPeers(t){const e=new Map,r=t=>{const r=`${t.peerEndpoint}|${t.peerHostAlias||""}`;if(e.has(r))return;const i=`peer-${t.mspId}-${e.size}`;e.set(r,{...t,name:i})};return t.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(e.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(t){const e={},r={},i={};for(const s of t){const t=await this.readPemInput(s.tlsCert||this.config.tlsCert),n=s.peerHostAlias||this.extractHost(s.peerEndpoint);e[s.name]={url:this.ensureGrpcUrl(s.peerEndpoint),tlsCACerts:{pem:t},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[s.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[s.mspId]=i[s.mspId]||{mspid:s.mspId,peers:[]},i[s.mspId].peers.push(s.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:e,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(t){return t.every(t=>this.isLocalEndpoint(t.peerEndpoint))}isLocalEndpoint(t){const e=this.extractHost(t).toLowerCase();return"localhost"===e||"127.0.0.1"===e}extractHost(t){return t.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(t){return/^grpcs?:\/\//i.test(t)?t:"grpcs://"+t}async readPemInput(t){if(!t)throw new c("Missing certificate or key material");if(Buffer.isBuffer(t))return t.toString("utf8");const e=t.trim();if(/-----BEGIN [A-Z ]+-----/.test(e))return e;const r=await ee.promises.stat(t).catch(()=>{});return r?.isDirectory()?await qr(t):(await zr(t)).toString()}parseError(t){return Zr.parseError(t)}async submitTransaction(t,e,r,i,s,n){if(this.shouldUseLegacyGateway(t)){const s=this.prepareLegacyArgs(r),a=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs(t);return this.submitLegacyWithExplicitEndorsers(t,e,s,a,o,n)}return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=jt.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.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(ee.readFileSync(r,"utf8"))}catch(t){throw new c(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Qt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Xt(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=jt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Gr(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+Be.fabricIdFromCertificate(s.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let n;if(e.hsm)throw new ct("HSM NOT IMPLEMENTED");n=await Yr(e.keyCertOrDirectoryPath);const a={client:t,identity:s,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 "+e.mspId);const o=Ut(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new Zr._baseDispatch}static parseError(t){let e="string"==typeof t?t:t.message;return t instanceof Gt&&t.details.length&&10===t.code&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new qe(t):e.includes("DEADLINE_EXCEEDED")?new Je(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ve(t):e.includes("PHANTOM_READ_CONFLICT")?new Ye(t):t instanceof Error&&t.code&&9===t.code?new Ke(t):e.includes(u.name)?new u(t):e.includes(y.name)?new y(t):e.includes(m.name)?new m(t):e.includes($.name)?new $(t):e.includes(pt.name)?new pt(t):e.includes(yt.name)?new yt(t):e.includes(ct.name)?new ct(t):e.includes(wt.name)?new wt(t):e.includes(bt.name)?new bt(t):e.includes(it.name)?new it(t):e.includes(At.name)?new At(t):e.includes(vt.name)?new vt(t):e.includes(g.name)?new g(t):new c(t)}}St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"create",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,X]),Et("design:returntype",Promise)],Zr.prototype,"healthcheck",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"read",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"update",null),St([Mt(),Ht(),Et("design:type",Function),Et("design:paramtypes",[Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"delete",null),St([Mt(),Et("design:type",Function),Et("design:paramtypes",[Object,"function"==typeof(Xr="undefined"!=typeof D&&D)?Xr:Object,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"raw",null),St([Mt(),Et("design:type",Function),Et("design:paramtypes",[String,String,Object,X]),Et("design:returntype",Promise)],Zr.prototype,"view",null),Zr.decoration(),mt.setCurrent(Oe);class ti extends Ct{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof Zr))throw new ct("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(e,r,i,...s){const{log:n,ctxArgs:a}=mt.logCtx(this.updateObservers,r,!1,...s);if(this.adapter)try{await this.adapter.refresh(e,r,i,...a)}catch(t){throw new c("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.tableName(e)}:${r}`)}async handleEvents(e){if(!this.listeningStack)throw new c('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new c("No adapter found. should be impossible");const r=e||await this.adapter.context(l.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t),i=this.log.for(this.handleEvents);i.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:s,event:n,owner:a}=Fr(e.eventName);if(a&&a!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(s?t.get(s):t.get(this.models[0].name))??(s||this.models[0]?.name);await this.updateObservers(e,n,o.id,r)}catch(t){i.error(`Failed update observables for table ${s} event ${n} id: ${o.id}: ${t}`)}}}catch(t){i.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new c("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t),{ctx:r}=this.logCtx([e],this.initialize),i=(await Zr.getGateway(r,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new c("No adapter observed for dispatch");this.listeningStack=await i.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(r)}}Zr&&(Zr._baseDispatch=ti);const ei="##VERSION##",ri="##PACKAGE##";Ot.registerLibrary(ri,ei);export{_e as AllowanceError,$e as BASE_ALPHABET,Le as BalanceError,Pe as BaseEncoder,Lr as CA_ROLE,Re as CRYPTO,be as ClientSerializer,Ne as CoreUtils,Be as CryptoUtils,_r as DefaultFabricClientFlags,$r as DeterministicSerializer,ke as ERC20Events,Ke as EndorsementError,Ve as EndorsementPolicyError,tr as FabricBaseModel,Zr as FabricClientAdapter,ti as FabricClientDispatch,fe as FabricClientRepository,Ae as FabricERC20ClientRepository,Xe as FabricEnrollmentService,Oe as FabricFlavour,er as FabricIdentifiedBaseModel,jr as FabricIdentityService,Se as FabricModelKeys,De as HFCAIdentityAttributes,Fe as HFCAIdentityType,xe as Identity,Ce as IdentityCredentials,Ee as IdentityType,yr as ImplicitPrivateCollection,He as MissingContextError,Ge as MissingPKCSS11Lib,fr as ModelCollection,qe as MvccReadConflictError,mr as NamespaceCollection,Ue as NotInitializedError,je as OverflowError,ir as Owner,ri as PACKAGE_NAME,Ye as PhantomReadConflictError,Me as RegistrationError,Ze as RegistrationRequestBuilder,wr as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,Br as SimpleDeterministicSerializer,Qe as TransactionBufferSizeError,We as TransactionLimitsError,Je as TransactionTimeoutError,ze as UnauthorizedPrivateDataAccess,ei as VERSION,Dr as add,Ar as applyMirrorFlags,br as applySegregationFlags,le as collectionFor,Hr as contentOfLoadFile,lr as createMirrorHandler,hr as deleteMirrorHandler,cr as evalMirrorMetadata,ue as extractCollections,ve as extractIds,rr as extractMspId,Vr as extractPrivateKey,vr as extractSegregatedCollections,Rr as generateFabricEventName,se as generateModelDesignDocs,ie as generateModelIndexes,Ie as getAkiAndSerialFromCert,Ur as getCAUser,Kr as getFirstDirFileName,qr as getFirstDirFileNameContent,Gr as getIdentity,Yr as getSigner,pr as mirror,ur as mirrorWriteGuard,nr as ownedBy,sr as ownedByOnCreate,Fr as parseEventName,de as privateCollectionFor,Nr as privateData,zr as readFile,gr as readMirrorHandler,ne as readModelFile,ae as readModelFolders,Pr as safeParseInt,Cr as segregatedDataOnCreate,Or as segregatedDataOnDelete,Sr as segregatedDataOnRead,Er as segregatedDataOnUpdate,he as sharedCollectionFor,Ir as sharedData,Tr as sortKeysOnlyRecursive,kr as sub,or as transactionId,ar as transactionIdOnCreate,dr as updateMirrorHandler,pe as writeCollectionDesignDocs,ge as writeCollections,ce as writeDesignDocs,oe as writeIndexes};
2
2
  //# sourceMappingURL=for-fabric.js.map
@@ -23,7 +23,7 @@ function collectionFor(collectionName, policy, requiredPeerCount, maxPeerCount,
23
23
  function privateCollectionFor(mspId, collectionName = `${mspId}Private`, requiredPeerCount = 0, maxPeerCount = 0, blockToLive = 0, memberOnlyRead = true, memberOnlyWrite = true) {
24
24
  const c = collectionFor(collectionName, `OR('${mspId}.member')`, requiredPeerCount, maxPeerCount, blockToLive, memberOnlyRead, memberOnlyWrite);
25
25
  c.endorsementPolicy = {
26
- signaturePolicy: `OR('${mspId}'.peer)`,
26
+ signaturePolicy: `OR('${mspId}.peer')`,
27
27
  };
28
28
  return c;
29
29
  }
@@ -15,7 +15,7 @@ export function collectionFor(collectionName, policy, requiredPeerCount, maxPeer
15
15
  export function privateCollectionFor(mspId, collectionName = `${mspId}Private`, requiredPeerCount = 0, maxPeerCount = 0, blockToLive = 0, memberOnlyRead = true, memberOnlyWrite = true) {
16
16
  const c = collectionFor(collectionName, `OR('${mspId}.member')`, requiredPeerCount, maxPeerCount, blockToLive, memberOnlyRead, memberOnlyWrite);
17
17
  c.endorsementPolicy = {
18
- signaturePolicy: `OR('${mspId}'.peer)`,
18
+ signaturePolicy: `OR('${mspId}.peer')`,
19
19
  };
20
20
  return c;
21
21
  }
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.3.20";
1
+ export declare const VERSION = "0.3.21";
2
2
  export declare const PACKAGE_NAME = "@decaf-ts/for-fabric";
@@ -1,5 +1,5 @@
1
1
  import { Metadata } from "@decaf-ts/decoration";
2
- export const VERSION = "0.3.20";
2
+ export const VERSION = "0.3.21";
3
3
  export const PACKAGE_NAME = "@decaf-ts/for-fabric";
4
4
  Metadata.registerLibrary(PACKAGE_NAME, VERSION);
5
5
  //# sourceMappingURL=version.js.map
package/lib/version.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PACKAGE_NAME = exports.VERSION = void 0;
4
4
  const decoration_1 = require("@decaf-ts/decoration");
5
- exports.VERSION = "0.3.20";
5
+ exports.VERSION = "0.3.21";
6
6
  exports.PACKAGE_NAME = "@decaf-ts/for-fabric";
7
7
  decoration_1.Metadata.registerLibrary(exports.PACKAGE_NAME, exports.VERSION);
8
8
  //# sourceMappingURL=version.js.map
package/lib/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.3.20";
1
+ export declare const VERSION = "0.3.21";
2
2
  export declare const PACKAGE_NAME = "@decaf-ts/for-fabric";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decaf-ts/for-fabric",
3
- "version": "0.3.21",
3
+ "version": "0.3.22",
4
4
  "description": "Abstracts fabric logic",
5
5
  "type": "module",
6
6
  "exports": {