@decaf-ts/for-fabric 0.13.25 → 0.13.28

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
- 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,BaseError as l,enforceDBDecorators as d,OperationKeys as h,reduceErrorsToPrint as u,ValidationError as g,SerializationError as f,composeAttributeValue as p,ConflictError as m,NotFoundError as y,DBKeys as w,version as b,onRead as v,onCreate as A,onUpdate as C,onDelete as E,generated as S,readonly as O,transient as x,on as N,DBOperations as T,BulkCrudOperationKeys as I,BadRequestError as R}from"@decaf-ts/db-decorators";import{generateIndexes as $,generateViews as F,CouchDBKeys as k,CouchDBGroupOperator as P,CouchDBOperator as L,CouchDBQueryLimit as j,translateOperators as B,findViewMetadata as _,generateViewName as M,generateDesignDocName as U}from"@decaf-ts/for-couchdb";import{Paginator as H,UnsupportedError as z,AuthorizationError as G,Repository as K,PreparedStatementKeys as q,OrderDirection as V,PersistenceKeys as Y,pk as W,column as J,table as Q,BaseModel as X,Sequence as Z,Context as tt,oneToOne as et,Cascade as rt,index as it,normalizeImport as st,createdAt as nt,updatedAt as at,createdBy as ot,updatedBy as ct,ClientBasedService as lt,Statement as dt,QueryClause as ht,Condition as ut,Operator as gt,QueryError as ft,GroupOperator as pt,Adapter as mt,PagingError as yt,MigrationError as wt,ObserverError as bt,ForbiddenError as vt,ConnectionError as At,Dispatch as Ct}from"@decaf-ts/core";import{__decorate as Et,__metadata as St}from"tslib";import{Metadata as Ot,description as xt,uses as Nt,metadata as Tt,Decoration as It,apply as Rt,propMetadata as $t,prop as Ft}from"@decaf-ts/decoration";import Dt from"fabric-ca-client";import{MiniLogger as kt,isBrowser as Pt,LoggedClass as Lt,Logging as jt,toPascalCase as Bt,toCamelCase as _t,debug as Mt,final as Ut}from"@decaf-ts/logging";import{signers as Ht,connect as zt,GatewayError as Gt,EndorseError as Kt}from"@hyperledger/fabric-gateway";import{User as qt}from"fabric-common";import Vt,{X509Certificate as Yt}from"crypto";import*as Wt from"@peculiar/x509";import{X509Certificate as Jt}from"@peculiar/x509";import{Crypto as Qt}from"@peculiar/webcrypto";import*as Xt from"@grpc/grpc-js";import{Client as Zt}from"@grpc/grpc-js";import{Wallets as te,Gateway as ee}from"fabric-network";import re from"fs";function ie(t){const e=require("fs"),r=require("path").dirname(t);if(e.existsSync(r))return!0;ie(r),e.mkdirSync(r)}function se(e,r){const i=$([e]),s=((e,r)=>{try{return t.pk(e)+""}catch(t){const i=`Skipping ${e.name} while extracting indexes: no primary key is defined`;return void r.verbose(i)}})(e,r);return((t,e)=>e?t.map(t=>{const r=t?.index?.fields;if(!t?.name||"string"!=typeof t.name||!t.name.includes("defaultQuery")||!Array.isArray(r)||0===r.length)return t;if(r.filter(t=>"object"==typeof t&&!Array.isArray(t)).length!==r.length)return t;if(r.some(t=>!(!t||"object"!=typeof t||Array.isArray(t))&&Object.prototype.hasOwnProperty.call(t,e)))return t;const i=r[r.length-1],s="desc"===((Object.values(i||{})[0]||"asc")+"").toLowerCase()?"desc":"asc";return Object.assign({},t,{index:Object.assign({},t.index,{fields:[...r,{[e]:s}]})})}):t)(i,s||"")}function ne(t,e){const r=F([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function ae(e){const r=require("path").resolve(e.parentPath,e.name),i=require(r);return Object.values(i).filter(e=>{try{return new e instanceof t}catch{return!1}})}async function oe(...t){const e=require("fs"),r=require("path"),i=[];for(const s of t){const t=r.resolve(s),n=e.readdirSync(t,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const t of n)i.push(...ae(t))}return i}function ce(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`));ie(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))})}function le(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`));ie(a);const o={...t};delete o._rev,i.writeFileSync(a,JSON.stringify(o,void 0,2))})}function de(t,e,r,i,s,n,a){return{name:t,policy:e,requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n,memberOnlyWrite:a}}function he(t,e=t+"Private",r=0,i=0,s=0,n=!0,a=!0){const o=de(e,`OR('${t}.member')`,r,i,s,n,a);return o.endorsementPolicy={signaturePolicy:`OR('${t}.peer')`},o}function ue(t,e,r=1,i=2,s=0,n=!0,a=!0){const o=de(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 ge(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 he(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(he(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 ue(r,t,e,i,s,n,a)})}}function fe(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&&le(t,e,r)}class me extends H{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new z("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)}}class ye extends c{constructor(t){super(t,ye.name)}}class we extends c{constructor(t){super(t,we.name)}}class be extends c{constructor(t){super(t,be.name)}}class ve extends G{constructor(t){super(t,ve.name)}}class Ae extends c{constructor(t){super(t,Ae.name,500)}}class Ce extends l{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(Ce.name,t,403)}}class Ee extends l{constructor(t){super(Ee.name,t,409)}}class Se extends c{constructor(t){super(t,Se.name,500)}}class Oe extends c{constructor(t){super(t,Oe.name,500)}}class xe extends c{constructor(t){super(t,xe.name,500)}}class Ne extends c{constructor(t){super(t,Ne.name,500)}}class Te extends c{constructor(t){super(t,Te.name,500)}}class Ie extends c{constructor(t,e=Ie.name,r=590){super(t,e,r)}}class Re extends c{constructor(t){super(t,Re.name,591)}}class $e extends c{constructor(t){super(t,$e.name,592)}}class Fe extends Ie{constructor(t){super(t,Fe.name,593)}}class De extends K{constructor(t,e,r=!1){super(t,e,r),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,q.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,q.LIST_BY,!0)).for(this.listBy);s.verbose(`listing ${t.tableName(this.class)} by ${e} ${r}`);try{return await this.statement(this.listBy.name,e,r,...n)}catch(i){if(i instanceof Fe)return s.warn(`listBy result set too large for ${t.tableName(this.class)} key=${e+""} order=${r}. Returning empty list. Use paginateBy for large datasets.`),[];throw i}}async findBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,q.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,q.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=V.ASC,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,q.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=V.ASC,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,q.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,Y.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,Y.STATEMENT,[e,JSON.stringify(a)],void 0,void 0,this.class)));let c;return c=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):me.isSerializedPage(o)?Object.assign(o,{data:o.data.map(t=>new this.class(t))}):o,this.applyAfterRead(c,s)}async applyAfterRead(e,r){return r.getOrUndefined("afterQueryHandlers")?e instanceof t?(await d(this,r,e,h.READ,h.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(t=>this.applyAfterRead(t,r))),e):me.isSerializedPage(e)?(await this.applyAfterRead(e.data,r),e):e:e}async countOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.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(q.COUNT_OF,...n)}async maxOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.tableName(this.class)}`),this.statement(q.MAX_OF,e,...s)}async minOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.tableName(this.class)}`),this.statement(q.MIN_OF,e,...s)}async avgOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.tableName(this.class)}`),this.statement(q.AVG_OF,e,...s)}async sumOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.tableName(this.class)}`),this.statement(q.SUM_OF,e,...s)}async distinctOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.tableName(this.class)}`),this.statement(q.DISTINCT_OF,e,...s)}async groupOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,q.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.tableName(this.class)} by ${e}`),this.statement(q.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,h.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,h.CREATE,h.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=u(i);if(s)throw new g(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 readAll(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${t.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...n)).map((t,r)=>this.adapter.revert(t,this.class,e[r],{},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 ke=class extends X{constructor(t){super(t)}};Et([W({type:String}),St("design:type",String)],ke.prototype,"name",void 0),Et([J(),e(),St("design:type",String)],ke.prototype,"owner",void 0),Et([J(),e(),St("design:type",String)],ke.prototype,"symbol",void 0),Et([J(),e(),St("design:type",Number)],ke.prototype,"decimals",void 0),ke=Et([Q("erc20_tokens"),r(),St("design:paramtypes",[Object])],ke);let Pe=class extends X{constructor(t){super(t)}};Et([W({type:String}),St("design:type",String)],Pe.prototype,"id",void 0),Et([J(),e(),St("design:type",String)],Pe.prototype,"token",void 0),Et([J(),e(),St("design:type",Number)],Pe.prototype,"balance",void 0),Et([J(),St("design:type",String)],Pe.prototype,"captive",void 0),Pe=Et([Q("erc20_wallets"),r(),St("design:paramtypes",[Object])],Pe);let Le=class extends X{constructor(t){super(t)}};Et([W({type:String}),J(),e(),St("design:type",String)],Le.prototype,"owner",void 0),Et([J(),e(),St("design:type",String)],Le.prototype,"spender",void 0),Et([J(),e(),St("design:type",Number)],Le.prototype,"value",void 0),Le=Et([Q("erc20_allowances"),r(),St("design:paramtypes",[Object])],Le);class je 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 f("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 Be extends De{static{this.serializer=new je}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=>Z.parseValue(t.sequenceFor(e).type,r)):Z.parseValue(t.sequenceFor(e).type,i),await this.observerHandler.updateObservers(e,r,o,...a)}decode(t){return Be.decoder.decode(t)}constructor(t){super(t,Pe),this.serializer=Be.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 tt.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 tt.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 tt.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 tt.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Be.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await tt.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 tt.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 tt.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 tt.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 tt.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 tt.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 _e(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 Me=class extends X{constructor(t){super(t)}};var Ue,He;Et([xt("Unique identifier of the credentials record"),J(),W(),St("design:type",String)],Me.prototype,"id",void 0),Et([xt("PEM-encoded X.509 certificate for the identity"),J(),e(),St("design:type",String)],Me.prototype,"certificate",void 0),Et([xt("PEM-encoded root or intermediate certificate"),J(),e(),St("design:type",String)],Me.prototype,"rootCertificate",void 0),Et([xt("PEM-encoded private key"),J(),e(),St("design:type",String)],Me.prototype,"privateKey",void 0),Me=Et([r(),St("design:paramtypes",[Object])],Me),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror",t.CONTRACT="fabric.contract",t.CHAINCODE="fabric.chaincode",t.CHANNEL="fabric.channel",t.OVERRIDES="__overrides"})(Ue||(Ue={})),(t=>{t.X509="X.509"})(He||(He={}));const ze="hlf-fabric";let Ge=class extends X{constructor(t){super(t),this.type=He.X509}};Et([xt("Unique identifier of the identity"),W(),St("design:type",String)],Ge.prototype,"id",void 0),Et([et(Me,{update:rt.CASCADE,delete:rt.CASCADE}),St("design:type",Me)],Ge.prototype,"credentials",void 0),Et([J(),e(),it(),St("design:type",String)],Ge.prototype,"mspId",void 0),Et([J(),e(),St("design:type",String)],Ge.prototype,"type",void 0),Ge=Et([r(),St("design:paramtypes",[Object])],Ge);class Ke{static{this.logger=new kt(Ke.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 st(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 qt(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?(Ke.cryptoSuite||(Ke.cryptoSuite=qt.newCryptoSuite(t)),Ke.cryptoSuite):qt.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 Vt.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 st(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await st(import("fs")),{join:r}=await st(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await st(import("fs")),{join:r}=await st(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await st(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await st(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await st(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 qe(t){const e=new Jt(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 Ve=new Qt;var Ye,We,Je,Qe,Xe;Wt.cryptoProvider.set(Ve),(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-_.!~"})(Ye||(Ye={})),(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"})(We||(We={}));class Ze{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 tr{static{this.b58encoder=new Ze(Ye.BASE58)}static{this.logger=new kt(tr.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(n("Parsing certificate: {0}",t));const e=new Wt.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=Ve.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 Ve.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 Wt.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,Ve.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Wt.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:Ve.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=Ve.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,We.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:We.KEY_ALGORYTHM,hash:We.HASH,salt:i,iterations:We.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*We.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:We.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:We.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:We.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Je||(Je={})),(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"})(Qe||(Qe={}));class er extends Lt{constructor(t){Ke.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 Ke.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 Ke.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await Ke.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 Ke.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 ve(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new G(i);default:return new ve(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(er,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=tr.fabricIdFromCertificate(r),o=tr.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new Ge({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=er.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 rr extends t{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new g(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}}Et([e(),St("design:type",String)],rr.prototype,"affiliation",void 0),Et([a(1),St("design:type",Array)],rr.prototype,"attrs",void 0),Et([e(),St("design:type",String)],rr.prototype,"enrollmentID",void 0),Et([e(),St("design:type",String)],rr.prototype,"enrollmentSecret",void 0),Et([o(0),St("design:type",Number)],rr.prototype,"maxEnrollments",void 0),Et([e(),St("design:type",String)],rr.prototype,"role",void 0),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,w.TRANSIENT),s=Ot.get(e.constructor,Ue.PRIVATE),n=Ot.get(e.constructor,Ue.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,Ue.PRIVATE)).bind(t),t.isShared=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Ue.SHARED)).bind(t),t.mirrored=(t=>Ot.get("function"!=typeof t?t.constructor:t,Ot.key(Ue.FABRIC,Ue.MIRROR))).bind(t),t.ownerOf=(t=>{const e=Ot.get(t.constructor,Ot.key(Ue.FABRIC,Ue.OWNED_BY));if(e)return t[e]}).bind(t),t.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Ot.get(t,Ot.key(Ue.FABRIC,Ue.MIRROR)))).bind(t),t.collectionsFor=(t=>{const e=[Ue.PRIVATE],r=[Ue.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),t.chaincodeOf=((t,...e)=>{const r=Ot.get(t,Ue.CHAINCODE);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),t.contractOf=((t,...e)=>{const r=Ot.get(t,Ue.CONTRACT);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),t.channelOf=((t,...e)=>{const r=Ot.get(t,Ue.CHANNEL);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Xe||(Xe={}));let ir=class extends t{constructor(t){super(t)}};Et([xt("Stores the original timestamp of creation"),J(),nt(),St("design:type",Date)],ir.prototype,"createdAt",void 0),Et([xt("Stores the timestamp of the last update"),J(),at(),St("design:type",Date)],ir.prototype,"updatedAt",void 0),Et([xt("Stores the version of the model"),J(),b(),St("design:type",Number)],ir.prototype,"version",void 0),ir=Et([Nt(ze),St("design:paramtypes",[Object])],ir);let sr=class extends ir{constructor(t){super(t)}};Et([xt("Stores the creator"),J(),ot(),St("design:type",String)],sr.prototype,"createdBy",void 0),Et([xt("Stores the user that last updated the model"),J(),ct(),St("design:type",String)],sr.prototype,"updatedBy",void 0),sr=Et([Nt(ze),St("design:paramtypes",[Object])],sr);const nr=(t,...e)=>t.name+"Contract";function ar(t){const e={resolver:t};return Tt(Ue.CONTRACT,e)}function or(t){const e={resolver:t};return Tt(Ue.CHAINCODE,e)}function cr(t){const e={resolver:t};return Tt(Ue.CHANNEL,e)}function lr(t){if(t)return"string"==typeof t?t:t.getMSPID()}function dr(){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 G(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function hr(t,e,r,i){const{stub:s}=t,n=t.getOrUndefined("allowGenerationOverride")||!1;let a=(await s.getCreator()).mspid;t.logger.info(`Expected mspid to be ${i[r]} | ${a}. \n Using allowGenerationOverride: ${n}`),n&&(a=i[r]?i[r]:a),Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:a})}function ur(){return It.for(Ue.OWNED_BY).define({decorator:()=>(t,r)=>Rt(e(),S(),O(),A(hr),$t(Ot.key(Ue.FABRIC,Ue.OWNED_BY),r))(t,r),args:[]}).apply()}async function gr(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function fr(){return It.for(Ue.TRANSACTION_ID).define({decorator:()=>(t,r)=>Rt(e(),O(),A(gr),C(gr),$t(Ot.key(Ue.FABRIC,r,Ue.TRANSACTION_ID),r))(t,r),args:[]}).apply()}async function pr(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 mr(e,r,i,s){const n=await pr(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 yr(e,r,i,s){const n=await pr(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 wr(e,r,i,s){const n=await pr(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 br(t,e,r,i){const s=lr(t.get("identity"));if(s&&(s===e.mspId||e.condition&&e.condition(s)))throw new G(`Organization ${s} is not authorized to modify mirrored data`)}async function vr(t,e,r,i){const s=lr(t.get("identity"));if(!s)return;const n=await pr(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 Ar(t,e,r){const i="string"!=typeof e&&!!e,s=i?void 0:e,n=i?e:r;return It.for(Ue.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Rt(Tt(Ot.key(Ue.FABRIC,Ue.MIRROR),i),v(vr,i,{priority:30}),A(br,i,{priority:20}),C(br,i,{priority:20}),E(br,i,{priority:20}),A(mr,i,{priority:100}),C(yr,i,{priority:100}),E(wr,i,{priority:100}))},args:[t,s,n]}).apply()}const Cr=(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`${Bt(s.name)}${i?Bt(i):""}`};function Er(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?Bt(s):""}`}}const Sr=(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`__${Bt(i)}PrivateCollection`},Or=35;function xr(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,w.TRANSIENT)||{},n=Ot.get(e,Ot.key(Ue.PRIVATE))||{},a=Ot.get(e,Ot.key(Ue.SHARED))||{};return r.some(t=>t!==i&&!(t in s)&&!(t in n)&&!(t in a))})(e.constructor)||i.markFullySegregated())}async function Nr(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 pr(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 Tr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(s)||lr(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)}xr(s,o,e);const c=Array.isArray(i)?i:[i],l=t.pk(s.constructor),d=t.sequenceName(s,"pk"),h=s[l],u=null!=h;if(e.setSequenceSegregation(d,e.isFullySegregated,o),u)for(const r of c){const i=t.sequenceName(s,h+"",r+"");e.setSequenceSegregation(i,e.isFullySegregated,o)}}async function Ir(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)||lr(e.get("identity"));if(!o)throw new g("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 z(`Segregated data collection mismatch: ${i} vs ${d}`)});const h=a.map(t=>t+"");e.writeTo(d,h)}async function Rr(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=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(s)||lr(e.get("identity"));if(!a)throw new g("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 $r(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)||lr(e.get("identity"));if(!l)throw new g("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 z(`Segregated data collection mismatch: ${i} vs ${h}`)});const u=o.map(t=>t+"");e.writeTo(h,u)}async function Fr(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=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(s)||lr(e.get("identity"));if(!a)throw new g("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 Dr(t,e,r){return(r,i)=>{const s=[];if(!i){const i=Ot.getAttributes(r);return i?.forEach(i=>{Dr(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,w.TRANSIENT)||{},[i]:{}};Ot.set(n,w.TRANSIENT,d)},N(T.ALL,Tr,n,a),A(Ir,{collections:t},{priority:95,group:i}),v(Rr,{collections:t},{priority:95,group:i}),C($r,{collections:t},{priority:95,group:i}),E(Fr,{collections:t},{priority:95,group:i}))}return Rt(...s)(r,i)}}function kr(t=Sr){return It.for(Ue.PRIVATE).define({decorator:t=>Dr(t,Ue.PRIVATE),args:[t]}).apply()}function Pr(t){return It.for(Ue.SHARED).define({decorator:t=>Dr(t,Ue.SHARED),args:[t]}).apply()}function Lr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Lr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Lr(t[r]),e),{})}class jr 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")(Lr(this.preSerialize(t)))}}function Br(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function _r(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 Mr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ye(`Addition overflow: ${t} + ${e}`);return r}function Ur(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ye(`Subtraction overflow: ${t} - ${e}`);return r}function Hr(t){if(!/^\d+$/.test(t))throw new g(n("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new g(n("Failed to parse: {0}","string is not a parsable integer"));return e}class zr extends i{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Lr(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 Gr 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 Ke.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 Ke.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await Ke.getCAUser("admin",d,l,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,Y.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 Ke.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 tt?(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,h.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 ve(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new G(i);default:return new ve(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,h.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=tr.fabricIdFromCertificate(s),c=tr.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new Ge({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=Gr.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=qt.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=Gr.identityFromEnrollment(d,this.config.caName,n);s.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=qe(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 Kr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Kr||(Kr={}));const qr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,allowContextTransientMap:!1,rebuildWithTransient:!0,encryptTransient:!1,syntheticEvents:!0}),Vr=new kt("fabric-fs");async function Yr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Wr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await st(import("fs"));return await e.readFile(t)})(t)}async function Jr(t,e,r,i){Vr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new qt(t),n=qt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Qr(t,e){return{mspId:t,credentials:await Yr(e,async t=>{const{promises:e}=await st(import("fs")),r=await Xr(t);return await e.readFile(r)})}}async function Xr(t){const{promises:e}=await st(import("fs")),{join:r}=await st(import("path"));return r(t,(await e.readdir(t))[0])}async function Zr(t){const{promises:e}=await st(import("fs")),{join:r}=await st(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function ti(t){const e=await Yr(t,async t=>{const{promises:e}=await st(import("fs")),r=await Xr(t);return await e.readFile(r)}),r=await ei(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}async function ei(t){let e;if(Pt())e=globalThis.crypto.subtle;else{const t=await st(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)}}const ri=["allowGenerationOverride"];class ii extends tt{constructor(t){super(t)}toOverrides(){const t={};for(const e of ri){const r=this.getOrUndefined(e);void 0!==r&&(t[e]=r)}return t}}function si(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 ni 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 q.FIND:break;case q.PAGE:s.push(n,a);break;case q.FIND_BY:break;case q.LIST_BY:s.push(n);break;case q.PAGE_BY:s.push(n,a);break;case q.FIND_ONE_BY:break;default:throw new c("Unsupported method "+r)}return e}async executePrepared(...t){const e=K.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(Y.QUERY,this.overrides||{},this.fromSelector)))throw new c("No context available for statement");if(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(e,r){const i=t.pk(this.fromSelector),s=Ot.get(this.fromSelector,Ot.key(w.ID,i))?.type;if(e[k.ID]){const[,...t]=e[k.ID].split(k.SEPARATOR),r=t.join("_");e[i]=Z.parseValue(s,r)}return super.processRecord(e,r)}async raw(t,...e){const{ctx:r}=this.logCtx(e,this.raw),i=t?.aggregateInfo;if(t?.aggregate&&i)return this.executeAggregate(i,r);const s=await this.adapter.raw(t,!0,this.fromSelector,r);if(!this.selectSelector){const t=s.map(t=>this.processRecord(t,r));return r.getOrUndefined("afterQueryHandlers")?await this.applyAfterHandlersToResult(t,r):t}return s}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][L.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 ft("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new ft("STARTS_WITH requires a string comparison");const t={start:s=i,end:si(s)},r={};return r[e]={},r[e][L.BIGGER_EQ]=t.start,r[e][L.SMALLER]=t.end,{selector:r}}var s,n;if(r===gt.ENDS_WITH){if("string"!=typeof e)throw new ft("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new ft("ENDS_WITH requires a string comparison");const t={};return t[e]={[L.REGEXP]:(n=i,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===gt.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new ft("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][B(gt.BIGGER_EQ)]=r,n[t][B(gt.SMALLER_EQ)]=s,{selector:n}}let a={};if(-1===[pt.AND,pt.OR,gt.NOT].indexOf(r))a[e]={},a[e][B(r)]=i;else if(r===gt.NOT)a=this.parseCondition(e).selector,a[B(gt.NOT)]={},a[B(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})(B(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 ft("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 ft(`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||U(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 ft("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 ft("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}}var ai;class oi extends mt{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new je}static{this.log=jt.for(oi)}get Context(){return ii}constructor(t,e){super(Object.assign({},qr,t),ze,e),this.serializer=oi.serializer}chaincodeFor(t,...e){return oi.chaincodeFor(t,this.config,...e)}channelFor(t,...e){return oi.channelFor(t,this.config,...e)}contractFor(t,...e){return oi.contractFor(t,this.config,...e)}Statement(t){return new ni(this,t)}Paginator(t,e,r){return new me(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 tt||(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 oi.decoder.decode(t)}repository(){return De}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),g=i.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,I.CREATE_ALL,[JSON.stringify(g)],h?{[d]:a}:void 0,this.getEndorsingOrganizations(l),e);let m;try{m=JSON.parse(this.decode(p)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}return this.shouldRefreshAfterWrite(e,l,u,m[0][t.pk(e)]||r[0])?this.readAll(e,_e(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,I.READ_ALL,[JSON.stringify(r)],void 0,void 0,e);try{return JSON.parse(this.decode(o)).map(t=>JSON.parse(t))}catch(t){throw new f(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),g=i.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,I.UPDATE_ALL,[JSON.stringify(g)],h?{[d]:a}:void 0,this.getEndorsingOrganizations(l),e);let m;try{m=JSON.parse(this.decode(p)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}return this.shouldRefreshAfterWrite(e,l,u,r[0])?this.readAll(e,_e(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,I.DELETE_ALL,[JSON.stringify(r)],void 0,this.getEndorsingOrganizations(n),e);try{return d?l:JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}}prepare(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.prepare),n=t.segregate(e);e[Y.METADATA]&&(i.silly("Passing along persistence metadata for "+e[Y.METADATA]),Object.defineProperty(n.model,Y.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[Y.METADATA]}));const a=t.mirroredAt(e);if(a){const t=a.mspId;if(!t)throw new c("No mirror MSP could be found");let e=this.getEndorsingOrganizations(s)||[];e=Array.isArray(e)?e:[e];const 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)}injectTransientOverrides(t,e){const r=this.hasMeaningfulTransientData(t),i=!!e.getOrUndefined("allowContextTransientMap");if(!r&&!i)return;const s=e.toOverrides(),n=r?Object.assign({},t):{};return i&&Object.keys(s).length&&(n[Ue.OVERRIDES]=s),Object.keys(n).length?n:void 0}hasMeaningfulTransientData(t){if(null==t)return!1;if(Array.isArray(t))return t.some(t=>this.hasMeaningfulTransientData(t));if("object"!=typeof t)return!0;const e=Object.entries(t);return!!e.length&&e.some(([,t])=>this.hasMeaningfulTransientData(t))}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),l=t.tableName(e);o.verbose(`adding entry to ${l} table`),o.debug("pk: "+r);const d=s&&Object.keys(s).length>0,u=d||this.shouldForceGatewayHydration(c),g=await this.submitTransaction(c,h.CREATE,[this.serializer.serialize(i,e.name)],d?{[l]:s}:void 0,this.getEndorsingOrganizations(c),e),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,_e(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);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,h.READ,[r.toString()],void 0,void 0,e);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 l=t.tableName(e);o.verbose(`updating entry to ${l} table`),o.debug("pk: "+r);const d=s&&Object.keys(s).length>0,u=d||this.shouldForceGatewayHydration(c),g=await this.submitTransaction(c,h.UPDATE,[this.serializer.serialize(i,e.name)],d?{[l]:s}:void 0,this.getEndorsingOrganizations(c),e),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,_e(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 l=this.shouldRefreshAfterWrite(e,n,o,r);l&&(c=await this.read(e,r,n)),s.verbose(`deleting entry from ${a} table`),s.debug("pk: "+r);const d=await this.submitTransaction(n,h.DELETE,[r.toString()],void 0,this.getEndorsingOrganizations(n),e);return l?c:this.serializer.deserialize(this.decode(d))}async raw(e,r=!0,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.raw);let o,c;n.info("Performing raw statement on table "+t.tableName(i));try{o=await this.evaluateTransaction(a,"raw",[JSON.stringify(e),r],void 0,void 0,i)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new f("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const e=c[0];return t.isModel(e)?c.map(e=>t.build(e)):c}return l=c,t.isModel(l)?t.build(l):l;var l}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 f("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=oi.getClient(this.config)),this._client}async Gateway(t){return oi.getGateway(t,this.config,this.client)}async Contract(t,e){return oi.getContract(await this.Gateway(t),this.config,e,t)}async transaction(t,e,r=!0,i,s={},n,a){const o=this.log.for(this.transaction);if(s=this.injectTransientOverrides(s,t),r&&this.shouldUseLegacyGateway(t)){const r=this.prepareLegacyArgs(i),n=this.buildLegacyTransient(s),o=this.buildLegacyPeerConfigs(t);return await this.submitLegacyWithExplicitEndorsers(t,e,r,n,o,a)}const c=await this.Gateway(t);try{const c=await this.Contract(t,a);o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${c.getContractName()}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate,d=(i||[]).map(t=>this.normalizeTransactionArgument(t)),h=Object.entries(s||{});n=n?.length?n:void 0;const u={arguments:d,transientData:h.length?h.reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}):void 0,endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,e,u)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}normalizeTransactionArgument(t){return null==t||"string"==typeof t||"object"!=typeof t||t instanceof Uint8Array?t:JSON.stringify(t)}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}resolveLegacyMspCount(){const t=this.config.legacyMspCount??1,e=Number(t);return!Number.isFinite(e)||1>e?1:Math.floor(e)}pickLegacyCandidates(t,e){if(!t.length||0>=e)return[];const r=[...t],i=Math.min(e,r.length),s=[];for(;s.length<i&&r.length;){const t=Math.floor(Math.random()*r.length),[e]=r.splice(t,1);e&&s.push(e)}return s}buildLegacyPeerConfigs(t){const e=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}];let r=this.getEndorsingOrganizations(t)||[];r=Array.isArray(r)?r:[r];const i=(r.filter(t=>!!t)||[]).filter(t=>t!==this.config.mspId);if(!i.length)return e;const s=this.config.mspMap,n=this.resolveLegacyMspCount();for(const t of i){const r=s?.[t];if(!r?.length)throw new z(`No peer mapping available for MSP ${t}. Provide it via config.mspMap`);const i=this.pickLegacyCandidates(r,n);if(!i.length)throw new z(`No valid peer mapping available for MSP ${t}. Provide it via config.mspMap`);for(const r of i){if(!r.endpoint)throw new z(`Invalid peer mapping for MSP ${t}: missing endpoint`);e.push({mspId:t,peerEndpoint:r.endpoint,peerHostAlias:r.alias,tlsCert:r.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),l=await this.resolveLegacyIdentityMaterial(),d=await te.newInMemoryWallet(),h=this.config.mspId+"-legacy";await d.put(h,{credentials:{certificate:l.certificate,privateKey:l.privateKey},mspId:this.config.mspId,type:"X.509"});const u=await this.buildLegacyConnectionProfile(o),g=new ee;try{await g.connect(u,{identity:h,wallet:d,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(o)},tlsInfo:{certificate:l.certificate,key:l.privateKey}});let s=this.config.channel,f=this.config.chaincodeName,p=this.config.contractName;if(n)if("string"==typeof n)p=n;else{if(!t)throw new c("No context received to determine chaincode config");s=await this.channelFor(n,t)||s,f=await this.chaincodeFor(n,t)||f,p=await this.contractFor(n,t)}const m=await g.getNetwork(s),y=m.getContract(f,p).createTransaction(e);i&&y.setTransient(i);const w=o.map(t=>m.getChannel().getEndorser(t.name)).filter(t=>!!t);w.length&&y.setEndorsingPeers(w),a.verbose(`Legacy submitting ${p}.${e} via peers ${o.map(t=>t.peerEndpoint).join(", ")}`);const b=await y.submit(...r);return Uint8Array.from(b)}catch(t){throw this.parseError(t)}finally{g.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 re.promises.stat(t).catch(()=>{});return r?.isDirectory()?await Zr(t):(await Wr(t)).toString()}parseError(t){return oi.parseError(t)}async submitTransaction(t,e,r,i,s,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 migrate(t,...e){const{ctxArgs:r}=(await this.logCtx([e],Y.MIGRATION,!0)).for(this.migrate);return this.submitTransaction(r[0],"migrate",[t,e],void 0,void 0)}async shutdown(...t){await super.shutdown(...t),this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static async getContract(t,e,r,i){const s=this.log.for(this.getContract);let n=e.channel,a=e.chaincodeName,o=e.contractName;if(r)if("string"==typeof r)o=r;else{if(!i)throw new c("No context received to determine chaincode config");n=await this.channelFor(r,e,i)||n,a=await this.chaincodeFor(r,e,i)||a,o=await this.contractFor(r,e,i)}const l=this.getNetwork(t,n);let d;try{s.debug(`Retrieving chaincode ${a} contract ${o} from network ${n}`),d=l.getContract(a,o)}catch(t){throw this.parseError(t)}return d}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(re.readFileSync(r,"utf8"))}catch(t){throw new c(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Xt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Zt(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 Qr(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+tr.fabricIdFromCertificate(s.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let n;if(e.hsm)throw new z("HSM NOT IMPLEMENTED");n=await ti(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=zt(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new oi._baseDispatch(this.client)}static chaincodeFor(e,r,...i){return t.chaincodeOf(e,...i)||r.chaincodeName}static channelFor(e,r,...i){return t.channelOf(e,...i)||r.channel}static contractFor(e,r,...i){return t.contractOf(e,...i)||nr(e,...i)}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),t instanceof Kt&&t.details.length&&10===t.code&&t.details[0].message?.includes(z.name)&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new xe(t):e.includes("DEADLINE_EXCEEDED")?new Re(t):e.includes("chaincode stream terminated")||e.includes("RESOURCE_EXHAUSTED")||e.includes("received message larger than max")||e.includes("grpc: received message larger")?new Fe(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Te(t):e.includes("PHANTOM_READ_CONFLICT")?new Ne(t):t instanceof Error&&t.code&&9===t.code?new Oe(t):e.includes(g.name)?new g(t):e.includes(y.name)?new y(t):e.includes(m.name)?new m(t):e.includes(R.name)?new R(t):e.includes(ft.name)?new ft(t):e.includes(yt.name)?new yt(t):e.includes(z.name)?new z(t):e.includes(wt.name)?new wt(t):e.includes(bt.name)?new bt(t):e.includes(G.name)?new G(t):e.includes(vt.name)?new vt(t):e.includes(At.name)?new At(t):e.includes(f.name)?new f(t):new c(t)}}Et([Mt(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"create",null),Et([Mt(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,ii]),St("design:returntype",Promise)],oi.prototype,"healthcheck",null),Et([Mt(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"read",null),Et([Mt(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"update",null),Et([Mt(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"delete",null),Et([Mt(),St("design:type",Function),St("design:paramtypes",[Object,"function"==typeof(ai="undefined"!=typeof D&&D)?ai:Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"raw",null),Et([Mt(),St("design:type",Function),St("design:paramtypes",[String,String,Object,ii]),St("design:returntype",Promise)],oi.prototype,"view",null),oi.decoration(),mt.setCurrent(ze);class ci extends Ct{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Y.SHUTDOWN,!0)).for(this.close);try{await super.close(...r)}catch(t){e.error("Failed to close Fabric proxies event listener",t)}if(this.listeningStack)try{await this.listeningStack.close()}catch(t){e.error("Failed to close Fabric event listener",t)}finally{this.listeningStack=void 0}}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof oi))throw new z("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(h.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}=_r(e.eventName);if(this.adapter.config?.mspEventOnly&&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),i=o.result?[o.result,r]:[r];await this.updateObservers(e,n,o.id,...i)}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(r)}}async initialize(){if(!this.adapter)throw new c("No adapter or config observed for dispatch");const e=!1!==this.adapter.config.syntheticEvents;if(!e){const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t),{ctx:r}=this.logCtx([e],this.initialize),i=(await oi.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)}[h.CREATE,h.UPDATE,h.DELETE,I.CREATE_ALL,I.UPDATE_ALL,I.DELETE_ALL].forEach(r=>{if(!this.adapter)throw new c("No adapter provided for the fallback of fully segregated models");if(!this.adapter[r])throw new c(`Method ${r} not found in ${this.adapter.alias} adapter to bind Observables Dispatch`);let i=Object.getOwnPropertyDescriptor(this.adapter,r),s=this.adapter;for(;!i&&s!==Object.prototype;)s=Object.getPrototypeOf(s),i=Object.getOwnPropertyDescriptor(s,r);function n(t){switch(t){case I.CREATE_ALL:return h.CREATE;case I.UPDATE_ALL:return h.UPDATE;case I.DELETE_ALL:return h.DELETE;default:return t}}i&&i.writable?this.adapter[r]=new Proxy(this.adapter[r],{apply:async(i,s,a)=>{const o=await i.apply(s,a),c=a[0];if(!e&&!t.isTransient(c))return o;const{log:l,ctxArgs:d,ctx:h}=s.logCtx(a.slice(a.length-1),i),u=a[1],g=[c,n(r),u];return h.getOrUndefined("observeFullResult")&&g.push(o),this.updateObservers(g[0],g[1],g[2],...g.slice(3),...d).catch(t=>l.error(`Failed to dispatch observer refresh for ${r} on ${c.name||c} for ${u}: ${t}`)),o}}):this.log.error(`Could not find method ${r} to bind Observables Dispatch`)})}}oi&&(oi._baseDispatch=ci);const li="##VERSION##",di="##COMMIT##",hi="##FULL_VERSION##",ui="##PACKAGE##";Ot.registerLibrary(ui,li);export{be as AllowanceError,Ye as BASE_ALPHABET,we as BalanceError,Ze as BaseEncoder,Kr as CA_ROLE,di as COMMIT,We as CRYPTO,je as ClientSerializer,Ke as CoreUtils,tr as CryptoUtils,nr as DefaultContractResolver,qr as DefaultFabricClientFlags,jr as DeterministicSerializer,Xe as ERC20Events,Oe as EndorsementError,Te as EndorsementPolicyError,hi as FULL_VERSION,ir as FabricBaseModel,oi as FabricClientAdapter,ii as FabricClientContext,ci as FabricClientDispatch,De as FabricClientRepository,Be as FabricERC20ClientRepository,er as FabricEnrollmentService,ze as FabricFlavour,sr as FabricIdentifiedBaseModel,Gr as FabricIdentityService,Ue as FabricModelKeys,Qe as HFCAIdentityAttributes,Je as HFCAIdentityType,Ge as Identity,Me as IdentityCredentials,He as IdentityType,Sr as ImplicitPrivateCollection,Ae as MissingContextError,Se as MissingPKCSS11Lib,Cr as ModelCollection,xe as MvccReadConflictError,Er as NamespaceCollection,Ee as NotInitializedError,ye as OverflowError,dr as Owner,ui as PACKAGE_NAME,Ne as PhantomReadConflictError,Fe as QueryResultTooLargeError,ve as RegistrationError,rr as RegistrationRequestBuilder,Or as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,zr as SimpleDeterministicSerializer,$e as TransactionBufferSizeError,Ie as TransactionLimitsError,Re as TransactionTimeoutError,Ce as UnauthorizedPrivateDataAccess,li as VERSION,Mr as add,Nr as applyMirrorFlags,xr as applySegregationFlags,or as chaincode,cr as channel,de as collectionFor,Yr as contentOfLoadFile,ar as contract,mr as createMirrorHandler,wr as deleteMirrorHandler,pr as evalMirrorMetadata,ge as extractCollections,_e as extractIds,lr as extractMspId,ei as extractPrivateKey,Tr as extractSegregatedCollections,Br as generateFabricEventName,ne as generateModelDesignDocs,se as generateModelIndexes,qe as getAkiAndSerialFromCert,Jr as getCAUser,Xr as getFirstDirFileName,Zr as getFirstDirFileNameContent,Qr as getIdentity,ti as getSigner,Ar as mirror,br as mirrorWriteGuard,ur as ownedBy,hr as ownedByOnCreate,_r as parseEventName,he as privateCollectionFor,kr as privateData,Wr as readFile,vr as readMirrorHandler,ae as readModelFile,oe as readModelFolders,Hr as safeParseInt,Ir as segregatedDataOnCreate,Fr as segregatedDataOnDelete,Rr as segregatedDataOnRead,$r as segregatedDataOnUpdate,ue as sharedCollectionFor,Pr as sharedData,Lr as sortKeysOnlyRecursive,Ur as sub,fr as transactionId,gr as transactionIdOnCreate,yr as updateMirrorHandler,pe as writeCollectionDesignDocs,fe as writeCollections,le as writeDesignDocs,ce as writeIndexes};
1
+ import{Model as t,required as e,model as r,JSONSerializer as i,ModelKeys as n,stringFormat as s,minlength as a,min as o}from"@decaf-ts/decorator-validation";import{InternalError as c,BaseError as l,enforceDBDecorators as d,OperationKeys as h,reduceErrorsToPrint as u,ValidationError as g,SerializationError as f,composeAttributeValue as p,ConflictError as m,NotFoundError as y,DBKeys as w,version as b,onRead as v,onCreate as A,onUpdate as C,onDelete as E,generated as S,readonly as O,transient as x,on as N,DBOperations as T,BulkCrudOperationKeys as I,BadRequestError as R}from"@decaf-ts/db-decorators";import{generateIndexes as $,generateViews as F,CouchDBKeys as k,CouchDBGroupOperator as P,CouchDBOperator as L,CouchDBQueryLimit as j,translateOperators as B,findViewMetadata as M,generateViewName as _,generateDesignDocName as U}from"@decaf-ts/for-couchdb";import{Paginator as H,UnsupportedError as z,AuthorizationError as G,Repository as K,PreparedStatementKeys as q,OrderDirection as V,PersistenceKeys as Y,pk as W,column as J,table as Q,BaseModel as X,Sequence as Z,Context as tt,oneToOne as et,Cascade as rt,index as it,normalizeImport as nt,createdAt as st,updatedAt as at,createdBy as ot,updatedBy as ct,ClientBasedService as lt,Statement as dt,QueryClause as ht,Condition as ut,Operator as gt,QueryError as ft,GroupOperator as pt,Adapter as mt,PagingError as yt,MigrationError as wt,ObserverError as bt,ForbiddenError as vt,ConnectionError as At,Dispatch as Ct}from"@decaf-ts/core";import{__decorate as Et,__metadata as St}from"tslib";import{Metadata as Ot,description as xt,uses as Nt,metadata as Tt,Decoration as It,apply as Rt,propMetadata as $t,prop as Ft}from"@decaf-ts/decoration";import Dt from"fabric-ca-client";import{MiniLogger as kt,isBrowser as Pt,LoggedClass as Lt,Logging as jt,toPascalCase as Bt,toCamelCase as Mt,debug as _t,final as Ut}from"@decaf-ts/logging";import{signers as Ht,connect as zt,GatewayError as Gt,EndorseError as Kt}from"@hyperledger/fabric-gateway";import{User as qt}from"fabric-common";import Vt,{X509Certificate as Yt}from"crypto";import*as Wt from"@peculiar/x509";import{X509Certificate as Jt}from"@peculiar/x509";import{Crypto as Qt}from"@peculiar/webcrypto";import*as Xt from"@grpc/grpc-js";import{Client as Zt}from"@grpc/grpc-js";import{Wallets as te,Gateway as ee}from"fabric-network";import re from"fs";function ie(t){const e=require("fs"),r=require("path").dirname(t);if(e.existsSync(r))return!0;ie(r),e.mkdirSync(r)}function ne(e,r){const i=$([e]),n=((e,r)=>{try{return t.pk(e)+""}catch{const t=`Skipping ${e.name} while extracting indexes: no primary key is defined`;return void r.verbose(t)}})(e,r);return((t,e)=>e?t.map(t=>{const r=t?.index?.fields;if(!t?.name||"string"!=typeof t.name||!t.name.includes("defaultQuery")||!Array.isArray(r)||0===r.length)return t;if(r.filter(t=>"object"==typeof t&&!Array.isArray(t)).length!==r.length)return t;if(r.some(t=>!(!t||"object"!=typeof t||Array.isArray(t))&&Object.prototype.hasOwnProperty.call(t,e)))return t;const i=r[r.length-1],n="desc"===((Object.values(i||{})[0]||"asc")+"").toLowerCase()?"desc":"asc";return Object.assign({},t,{index:Object.assign({},t.index,{fields:[...r,{[e]:n}]})})}):t)(i,n||"")}function se(t,e){const r=F([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function ae(e){const r=require("path").resolve(e.parentPath,e.name),i=require(r);return Object.values(i).filter(e=>{try{return new e instanceof t}catch{return!1}})}async function oe(...t){const e=require("fs"),r=require("path"),i=[];for(const n of t){const t=r.resolve(n),s=e.readdirSync(t,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const t of s)i.push(...ae(t))}return i}function ce(t,e=process.cwd(),r){const i=require("fs"),n=require("path");t.forEach(t=>{const s=n.resolve(n.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));ie(s),i.writeFileSync(s,JSON.stringify(t,void 0,2))})}function le(t,e=process.cwd(),r){if(!t.length)return;const i=require("fs"),n=require("path");t.forEach(t=>{const s=t._id.replace(/^_design\//,""),a=n.resolve(n.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${s}.json`));ie(a);const o={...t};delete o._rev,i.writeFileSync(a,JSON.stringify(o,void 0,2))})}function de(t,e,r,i,n,s,a){return{name:t,policy:e,requiredPeerCount:r,maxPeerCount:i,blockToLive:n,memberOnlyRead:s,memberOnlyWrite:a}}function he(t,e=t+"Private",r=0,i=0,n=0,s=!0,a=!0){const o=de(e,`OR('${t}.member')`,r,i,n,s,a);return o.endorsementPolicy={signaturePolicy:`OR('${t}.peer')`},o}function ue(t,e,r=1,i=2,n=0,s=!0,a=!0){const o=de(e,`OR(${t.map(t=>`'${t}.member'`).join(",")})`,r,i,n,s,a);return o.endorsementPolicy={signaturePolicy:`AND(${t.map(t=>`'${t}.peer'`).join(",")})`},o}async function ge(e,r,i={},n=!1){let{privateCols:s,sharedCols:a}=t.collectionsFor(e);function o(t){try{return"string"==typeof t?t:t(e,r[0])}catch(t){throw new c(t)}}s=s.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=n?t.mirroredAt(e):void 0,u=r.map(t=>s.map(e=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:n,memberOnlyRead:s}=l;return he(t,e,r,i,n,s,!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:n}=l;u.push(he(h.mspId,t,e,r,i,n,!1))}}return{privates:u,shared:a.map(t=>{const{requiredPeerCount:e,maxPeerCount:i,blockToLive:n,memberOnlyRead:s,memberOnlyWrite:a}=d;return ue(r,t,e,i,n,s,a)})}}function fe(t,e=process.cwd(),r="collections_config"){const i=require("fs"),n=require("path"),s=n.resolve(n.join(e,`./META-INF/${r}.json`));!function t(e){const r=n.dirname(e);if(i.existsSync(r))return!0;t(r),i.mkdirSync(r)}(s),i.writeFileSync(s,JSON.stringify(t,void 0,2))}function pe(t,e=process.cwd(),r){t?.length&&le(t,e,r)}class me extends H{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new z("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)}}class ye extends c{constructor(t){super(t,ye.name)}}class we extends c{constructor(t){super(t,we.name)}}class be extends c{constructor(t){super(t,be.name)}}class ve extends G{constructor(t){super(t,ve.name)}}class Ae extends c{constructor(t){super(t,Ae.name,500)}}class Ce extends l{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(Ce.name,t,403)}}class Ee extends l{constructor(t){super(Ee.name,t,409)}}class Se extends c{constructor(t){super(t,Se.name,500)}}class Oe extends c{constructor(t){super(t,Oe.name,500)}}class xe extends c{constructor(t){super(t,xe.name,500)}}class Ne extends c{constructor(t){super(t,Ne.name,500)}}class Te extends c{constructor(t){super(t,Te.name,500)}}class Ie extends c{constructor(t,e=Ie.name,r=590){super(t,e,r)}}class Re extends c{constructor(t){super(t,Re.name,591)}}class $e extends c{constructor(t){super(t,$e.name,592)}}class Fe extends Ie{constructor(t){super(t,Fe.name,593)}}class De extends K{constructor(t,e,r=!1){super(t,e,r),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},...n){const{log:s,ctxArgs:a}=(await this.logCtx(n,q.PAGE_BY,!0)).for(this.paginateBy);return s.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:n,ctxArgs:s}=(await this.logCtx(i,q.LIST_BY,!0)).for(this.listBy);n.verbose(`listing ${t.tableName(this.class)} by ${e} ${r}`);try{return await this.statement(this.listBy.name,e,r,...s)}catch(i){if(i instanceof Fe)return n.warn(`listBy result set too large for ${t.tableName(this.class)} key=${e+""} order=${r}. Returning empty list. Use paginateBy for large datasets.`),[];throw i}}async findBy(e,r,...i){const{log:n,ctxArgs:s}=(await this.logCtx(i,q.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...s)}async findOneBy(e,r,...i){const{log:n,ctxArgs:s}=(await this.logCtx(i,q.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${t.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...s)}async find(e,r=V.ASC,...i){const{log:n,ctxArgs:s}=(await this.logCtx(i,q.FIND,!0)).for(this.find);return n.verbose(`finding ${t.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...s)}async page(e,r=V.ASC,i={offset:1,limit:10},...n){const{log:s,ctxArgs:a}=(await this.logCtx(n,q.PAGE,!0)).for(this.page);return s.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:n,ctxArgs:s}=(await this.logCtx(r,Y.STATEMENT,!0)).for(this.statement);i.verbose("Executing prepared statement "+e);const a=s.slice(0,-1),o=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,Y.STATEMENT,[e,JSON.stringify(a)],void 0,void 0,this.class)));let c;return c=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):me.isSerializedPage(o)?Object.assign(o,{data:o.data.map(t=>new this.class(t))}):o,this.applyAfterRead(c,n)}async applyAfterRead(e,r){return r.getOrUndefined("afterQueryHandlers")?e instanceof t?(await d(this,r,e,h.READ,h.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(t=>this.applyAfterRead(t,r))),e):me.isSerializedPage(e)?(await this.applyAfterRead(e.data,r),e):e:e}async countOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.tableName(this.class)}${e?" by "+e:""}`);const s=e?[e,...n]:n;return this.statement(q.COUNT_OF,...s)}async maxOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.tableName(this.class)}`),this.statement(q.MAX_OF,e,...n)}async minOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.tableName(this.class)}`),this.statement(q.MIN_OF,e,...n)}async avgOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.tableName(this.class)}`),this.statement(q.AVG_OF,e,...n)}async sumOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.tableName(this.class)}`),this.statement(q.SUM_OF,e,...n)}async distinctOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.tableName(this.class)}`),this.statement(q.DISTINCT_OF,e,...n)}async groupOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,q.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.tableName(this.class)} by ${e}`),this.statement(q.GROUP_OF,e,...n)}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:n,ctxArgs:s}=this.logCtx(r,this.create);n.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,...s);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:n,ctx:s}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(s,e);const a=this.adapter.prepare(e,s),{id:o,transient:c}=a;let l=a.record;return n.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,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,h.CREATE,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),s=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),n||await d(this,r,t,h.CREATE,h.ON),t))),!s){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),n=u(i);if(n)throw new g(n)}return[t,...i]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:n,ctxArgs:s}=this.logCtx(r,this.createAll);n.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,...s);return Promise.all(d.map(async(t,e)=>{const r=o[e];return this.adapter.revert(t,this.class,r,l[e],i)}))}async readAll(e,...r){const{ctx:i,log:n,ctxArgs:s}=this.logCtx(r,this.readAll);return n.debug(`reading ${e.length} ${this.class.name} in table ${t.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,r)=>this.adapter.revert(t,this.class,e[r],{},i))}async updateAll(e,...r){const{ctx:i,log:n,ctxArgs:s}=this.logCtx(r,this.updateAll);n.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),...s);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 ke=class extends X{constructor(t){super(t)}};Et([W({type:String}),St("design:type",String)],ke.prototype,"name",void 0),Et([J(),e(),St("design:type",String)],ke.prototype,"owner",void 0),Et([J(),e(),St("design:type",String)],ke.prototype,"symbol",void 0),Et([J(),e(),St("design:type",Number)],ke.prototype,"decimals",void 0),ke=Et([Q("erc20_tokens"),r(),St("design:paramtypes",[Object])],ke);let Pe=class extends X{constructor(t){super(t)}};Et([W({type:String}),St("design:type",String)],Pe.prototype,"id",void 0),Et([J(),e(),St("design:type",String)],Pe.prototype,"token",void 0),Et([J(),e(),St("design:type",Number)],Pe.prototype,"balance",void 0),Et([J(),St("design:type",String)],Pe.prototype,"captive",void 0),Pe=Et([Q("erc20_wallets"),r(),St("design:paramtypes",[Object])],Pe);let Le=class extends X{constructor(t){super(t)}};Et([W({type:String}),J(),e(),St("design:type",String)],Le.prototype,"owner",void 0),Et([J(),e(),St("design:type",String)],Le.prototype,"spender",void 0),Et([J(),e(),St("design:type",Number)],Le.prototype,"value",void 0),Le=Et([Q("erc20_allowances"),r(),St("design:paramtypes",[Object])],Le);class je 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 f("Could not find metadata for "+t.constructor.name);i=e}return r[n.ANCHOR]=i,r}deserialize(e){const r=JSON.parse(e),i=r[n.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 Be extends De{static{this.serializer=new je}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,r,i,...n){if(!this.observerHandler)throw new c("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:a}=this.logCtx(n,this.updateObservers);let o;s.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=>Z.parseValue(t.sequenceFor(e).type,r)):Z.parseValue(t.sequenceFor(e).type,i),await this.observerHandler.updateObservers(e,r,o,...a)}decode(t){return Be.decoder.decode(t)}constructor(t){super(t,Pe),this.serializer=Be.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),n=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(n)}async transferFrom(t,e,r){const i=await tt.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(i.args,this.transferFrom),s=await this.adapter.submitTransaction(n,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(s)}async approve(t,e){const r=await tt.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),n=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(n)}async allowance(t,e){const r=await tt.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),n=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(n))}async initialize(t){const e=await tt.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Be.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await tt.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 tt.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 tt.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 tt.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 tt.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 tt.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 Me(e,r,i){let n,s,a;function o(r,i){if(n=n||t.pk(e),a=a||t.sequenceFor(e),s=s||t.composed(e,n),s)return p(r,s);const o=r[n]||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 _e=class extends X{constructor(t){super(t)}};var Ue,He;Et([xt("Unique identifier of the credentials record"),J(),W(),St("design:type",String)],_e.prototype,"id",void 0),Et([xt("PEM-encoded X.509 certificate for the identity"),J(),e(),St("design:type",String)],_e.prototype,"certificate",void 0),Et([xt("PEM-encoded root or intermediate certificate"),J(),e(),St("design:type",String)],_e.prototype,"rootCertificate",void 0),Et([xt("PEM-encoded private key"),J(),e(),St("design:type",String)],_e.prototype,"privateKey",void 0),_e=Et([r(),St("design:paramtypes",[Object])],_e),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror",t.CONTRACT="fabric.contract",t.CHAINCODE="fabric.chaincode",t.CHANNEL="fabric.channel",t.OVERRIDES="__overrides"})(Ue||(Ue={})),(t=>{t.X509="X.509"})(He||(He={}));const ze="hlf-fabric";let Ge=class extends X{constructor(t){super(t),this.type=He.X509}};Et([xt("Unique identifier of the identity"),W(),St("design:type",String)],Ge.prototype,"id",void 0),Et([et(_e,{update:rt.CASCADE,delete:rt.CASCADE}),St("design:type",_e)],Ge.prototype,"credentials",void 0),Et([J(),e(),it(),St("design:type",String)],Ge.prototype,"mspId",void 0),Et([J(),e(),St("design:type",String)],Ge.prototype,"type",void 0),Ge=Et([r(),St("design:paramtypes",[Object])],Ge);class Ke{static{this.logger=new kt(Ke.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 nt(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,n){this.logger.debug(s("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new qt(t),o=n?.hsm?{software:!1,lib:n.hsm.library,slot:n.hsm.slot,label:n.hsm.tokenLabel,pin:n.hsm.pin+""}:void 0,c=this.getCryptoSuite(o);a.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,r,n.hsm):this.getSoftwareEnrollmentKey(c,e);return await a.setEnrollment(l,r,i),a}static getCryptoSuite(t){return t?(Ke.cryptoSuite||(Ke.cryptoSuite=qt.newCryptoSuite(t)),Ke.cryptoSuite):qt.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),n=await t.getKey(i);if(!n||"function"==typeof n.isPrivate&&!n.isPrivate())throw Error("Unable to resolve private key from HSM");return n}static async getCertificateSKI(t){const e=new Yt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),n=Buffer.from(e.y||"","base64url");return Vt.createHash("sha256").update(Buffer.concat([r,i,n])).digest()}static async getIdentity(t,e){return{mspId:t,credentials:await this.contentOfLoadFile(e,async t=>{const{promises:e}=await nt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await nt(import("fs")),{join:r}=await nt(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await nt(import("fs")),{join:r}=await nt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await nt(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await nt(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await nt(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 qe(t){const e=new Jt(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 Ve=new Qt;var Ye,We,Je,Qe,Xe;Wt.cryptoProvider.set(Ve),(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-_.!~"})(Ye||(Ye={})),(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"})(We||(We={}));class Ze{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 n=t.length;for(;i!==n&&0===t[i];)i++,e++;const s=(n-i)*this.iFactor+1>>>0,a=new Uint8Array(s);for(;i!==n;){let e=t[i],n=0;for(let t=s-1;(0!==e||r>n)&&-1!==t;t--,n++)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=n,i++}let o=s-r;for(;o!==s&&0===a[o];)o++;let c=this.leader.repeat(e);for(;s>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 n=(t.length-e)*this.factor+1>>>0,s=new Uint8Array(n);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=n-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*s[t]>>>0,s[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=n-i;for(;a!==n&&0===s[a];)a++;const o=new Uint8Array(r+(n-a));let c=r;for(;a!==n;)o[c++]=s[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class tr{static{this.b58encoder=new Ze(Ye.BASE58)}static{this.logger=new kt(tr.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(s("Parsing certificate: {0}",t));const e=new Wt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(s("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=Ve.subtle,n=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),s=Buffer.from(n,"base64").toString("binary"),a=this.stringToArrayBuffer(s);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 Ve.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 Wt.X509Certificate(t),n=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,Ve.subtle.verify({name:"ECDSA",hash:"SHA-256"},n,e,r)}static async encrypt(t,e){const r=new Wt.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const n=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return Pt()?globalThis.window.crypto.subtle:Ve.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=Ve.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,We.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),n={name:We.KEY_ALGORYTHM,hash:We.HASH,salt:i,iterations:We.ITERATIONS},s=await this.getSubtleCrypto().deriveBits(n,e,8*We.KEYLENGTH);return this.getKey(s)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:We.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:We.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:We.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Je||(Je={})),(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"})(Qe||(Qe={}));class er extends Lt{constructor(t){Ke.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:n}=this.caConfig,s=this.log.for(this.User);s.debug(`Creating CA user for ${t} at ${i}`),s.debug("Retrieving CA certificate from "+e);const a=await Ke.getFirstDirFileNameContent(e);let o;if(n)s.debug(`Using HSM configuration for CA ${t} with library ${n.library}`);else{if(!r)throw new c(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);s.debug("Retrieving CA key from "+r),o=await Ke.getFirstDirFileNameContent(r)}return s.debug("Loading Admin user for ca "+t),this.user=await Ke.getCAUser("admin",o,a,t,{hsm:n}),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:n,verify:s}=r;const a=n[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await Ke.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Dt(e,{trustedRoots:Buffer.from(o),verify:s},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(),n=this.log.for(this.getCertificates);n.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const s=(await r.getCertificates(t||{},i)).result;return n.debug(`Found ${s.certs.length} certificates: ${JSON.stringify(s)}`),e?s.certs.map(t=>t.PEM):s}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 ve(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new G(i);default:return new ve(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,n,s){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:n,maxEnrollments:s};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:n}=t,s=jt.for(er,{}).for(this.identityFromEnrollment);s.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=tr.fabricIdFromCertificate(r),o=tr.encode(a);s.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new Ge({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:n,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 n=await this.CA();i.debug("Enrolling "+t);const s=await n.enroll({enrollmentID:t,enrollmentSecret:e});r=er.identityFromEnrollment(s,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,n,s){const a=await this.register(t,e,r,i,n,s),{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 n;try{n=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}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}}class rr extends t{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new g(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}}Et([e(),St("design:type",String)],rr.prototype,"affiliation",void 0),Et([a(1),St("design:type",Array)],rr.prototype,"attrs",void 0),Et([e(),St("design:type",String)],rr.prototype,"enrollmentID",void 0),Et([e(),St("design:type",String)],rr.prototype,"enrollmentSecret",void 0),Et([o(0),St("design:type",Number)],rr.prototype,"maxEnrollments",void 0),Et([e(),St("design:type",String)],rr.prototype,"role",void 0),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,w.TRANSIENT),n=Ot.get(e.constructor,Ue.PRIVATE),s=Ot.get(e.constructor,Ue.SHARED),a={model:{},public:{},transient:{},privates:{},shared:{}},o=Object.keys(i||{}),c=Object.keys(n||{}),l=Object.keys(s||{});for(const t of r){const r=e[t],i=o.includes(t),n=!i,s=c.includes(t),d=l.includes(t);(i||s||d)&&(a.transient=a.transient||{},a.transient[t]=r),s&&(a.privates=a.privates||{},a.privates[t]=r),d&&(a.shared=a.shared||{},a.shared[t]=r),n&&(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,Ue.PRIVATE)).bind(t),t.isShared=(t=>!!Ot.get("function"!=typeof t?t.constructor:t,Ue.SHARED)).bind(t),t.mirrored=(t=>Ot.get("function"!=typeof t?t.constructor:t,Ot.key(Ue.FABRIC,Ue.MIRROR))).bind(t),t.ownerOf=(t=>{const e=Ot.get(t.constructor,Ot.key(Ue.FABRIC,Ue.OWNED_BY));if(e)return t[e]}).bind(t),t.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Ot.get(t,Ot.key(Ue.FABRIC,Ue.MIRROR)))).bind(t),t.collectionsFor=(t=>{const e=[Ue.PRIVATE],r=[Ue.SHARED],i=Ot.key(...e),n=Ot.key(...r),s="function"==typeof t?t:t.constructor,a=Ot.get(s,i),o=Ot.get(s,n);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(t),t.chaincodeOf=((t,...e)=>{const r=Ot.get(t,Ue.CHAINCODE);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),t.contractOf=((t,...e)=>{const r=Ot.get(t,Ue.CONTRACT);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),t.channelOf=((t,...e)=>{const r=Ot.get(t,Ue.CHANNEL);if(!r||!r.resolver)return;if("string"==typeof r.resolver)return r.resolver;const i=e.pop();if(!(i&&i instanceof tt))throw new c("No context provided for chaincode resolution");return r.resolver(t,...e,i)}).bind(t),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Xe||(Xe={}));let ir=class extends t{constructor(t){super(t)}};Et([xt("Stores the original timestamp of creation"),J(),st(),St("design:type",Date)],ir.prototype,"createdAt",void 0),Et([xt("Stores the timestamp of the last update"),J(),at(),St("design:type",Date)],ir.prototype,"updatedAt",void 0),Et([xt("Stores the version of the model"),J(),b(),St("design:type",Number)],ir.prototype,"version",void 0),ir=Et([Nt(ze),St("design:paramtypes",[Object])],ir);let nr=class extends ir{constructor(t){super(t)}};Et([xt("Stores the creator"),J(),ot(),St("design:type",String)],nr.prototype,"createdBy",void 0),Et([xt("Stores the user that last updated the model"),J(),ct(),St("design:type",String)],nr.prototype,"updatedBy",void 0),nr=Et([Nt(ze),St("design:paramtypes",[Object])],nr);const sr=(t,...e)=>t.name+"Contract";function ar(t){const e={resolver:t};return Tt(Ue.CONTRACT,e)}function or(t){const e={resolver:t};return Tt(Ue.CHAINCODE,e)}function cr(t){const e={resolver:t};return Tt(Ue.CHANNEL,e)}function lr(t){if(t)return"string"==typeof t?t:t.getMSPID()}function dr(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],n=r.clientIdentity.getID(),s=await this.tokenRepository.select(),a=await s.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!=n)throw new G(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function hr(t,e,r,i){const{stub:n}=t,s=t.getOrUndefined("allowGenerationOverride")||!1;let a=(await n.getCreator()).mspid;t.logger.info(`Expected mspid to be ${i[r]} | ${a}. \n Using allowGenerationOverride: ${s}`),s&&(a=i[r]?i[r]:a),Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:a})}function ur(){return It.for(Ue.OWNED_BY).define({decorator:()=>(t,r)=>Rt(e(),S(),O(),A(hr),$t(Ot.key(Ue.FABRIC,Ue.OWNED_BY),r))(t,r),args:[]}).apply()}async function gr(t,e,r,i){const{stub:n}=t;i[r]=n.getTxID()}function fr(){return It.for(Ue.TRANSACTION_ID).define({decorator:()=>(t,r)=>Rt(e(),O(),A(gr),C(gr),$t(Ot.key(Ue.FABRIC,r,Ue.TRANSACTION_ID),r))(t,r),args:[]}).apply()}async function pr(e,r,i){let n=r;if("string"!=typeof n)try{const s=t.ownerOf(e)||i.get("stub").getCreator().toString();r&&"function"==typeof r&&(n=await r(e,s,i))}catch(t){throw new c("Failed to resolve collection mirror name: "+t)}if(!n||"string"!=typeof n)throw new c("No collection found model "+e.constructor.name);return n}async function mr(e,r,i,n){const s=await pr(n,r.resolver,e),a=e,o=n;a.put("mirror",!0),a.put("mirrorCollection",s);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(o,e);e.logger.info(`Mirror for ${t.tableName(this.class)} created with ${t.pk(n)}: ${i[t.pk(n)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function yr(e,r,i,n){const s=await pr(n,r.resolver,e),a=e,o=n;a.put("mirror",!0),a.put("mirrorCollection",s);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(o,e),e.logger.info(`Mirror for ${t.tableName(this.class)} updated: ${n[t.pk(n)]}`)}finally{a.put("mirror",void 0),a.put("mirrorCollection",void 0)}}async function wr(e,r,i,n){const s=await pr(n,r.resolver,e),a=e;a.put("mirror",!0),a.put("mirrorCollection",s),a.put("segregated",s);try{const r=n[t.pk(n)],i=this.override(Object.assign({},this._overrides,{segregated:s,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 br(t,e,r,i){const n=lr(t.get("identity"));if(n&&(n===e.mspId||e.condition&&e.condition(n)))throw new G(`Organization ${n} is not authorized to modify mirrored data`)}async function vr(t,e,r,i){const n=lr(t.get("identity"));if(!n)return;const s=await pr(i,e.resolver,t),a=t;(n===e.mspId||e.condition&&e.condition(n))&&(t.logger.info(`Mirror read: MSP ${n} matches, routing reads to mirror collection ${s}`),a.put("mirror",!0),a.put("mirrorCollection",s),a.put("fullySegregated",!0),a.readFrom(s))}function Ar(t,e,r){const i="string"!=typeof e&&!!e,n=i?void 0:e,s=i?e:r;return It.for(Ue.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Rt(Tt(Ot.key(Ue.FABRIC,Ue.MIRROR),i),v(vr,i,{priority:30}),A(br,i,{priority:20}),C(br,i,{priority:20}),E(br,i,{priority:20}),A(mr,i,{priority:100}),C(yr,i,{priority:100}),E(wr,i,{priority:100}))},args:[t,n,s]}).apply()}const Cr=(e,r)=>{const i=r||("function"!=typeof e?t.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!i)throw new c(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Bt(n.name)}${i?Bt(i):""}`};function Er(e){return(r,i)=>{const n=i||("function"!=typeof r?t.ownerOf(r):void 0),s="function"==typeof r?r:r.constructor;if(!n)throw new c(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${n?Bt(n):""}`}}const Sr=(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`__${Bt(i)}PrivateCollection`},Or=35;function xr(e,r,i){r.length>0&&i.readFrom(r),!i.isFullySegregated&&r.length&&((e=>{const r=Ot.getAttributes(e)||[],i=t.pk(e),n=Ot.get(e,w.TRANSIENT)||{},s=Ot.get(e,Ot.key(Ue.PRIVATE))||{},a=Ot.get(e,Ot.key(Ue.SHARED))||{};return r.some(t=>t!==i&&!(t in n)&&!(t in s)&&!(t in a))})(e.constructor)||i.markFullySegregated())}async function Nr(e,r,i){if(!r)return;const n=t.mirroredAt(e);if(!n)return;if(!(r===n.mspId||n.condition&&n.condition(r)))return;const s=await pr(new e,n.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",s),i.readFrom(s)}async function Tr(e,r,i,n){const s=Array.isArray(r)?r:[r],a=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(n)||lr(e.get("identity"));if(!a)return;const o=[];for(const t of s){const r=t.collections,i="string"==typeof r?r:r(n,a,e);i&&!o.includes(i)&&o.push(i)}xr(n,o,e);const c=Array.isArray(i)?i:[i],l=t.pk(n.constructor),d=t.sequenceName(n,"pk"),h=n[l],u=null!=h;if(e.setSequenceSegregation(d,e.isFullySegregated,o),u)for(const r of c){const i=t.sequenceName(n,h+"",r+"");e.setSequenceSegregation(i,e.isFullySegregated,o)}}async function Ir(e,r,i,n){const s=Array.isArray(r)?r:[r],a=Array.isArray(i)?i:[i];if(a.length!==s.length)throw new c("Segregated data keys and metadata length mismatch");const o=t.ownerOf(n)||lr(e.get("identity"));if(!o)throw new g("There's no assigned organization for model "+n.constructor.name);const l=s[0].collections,d="string"==typeof l?l:l(n,o,e);a.forEach((t,r)=>{const i="string"==typeof s[r].collections?s[r].collections:s[r].collections(n,o,e);if(i!==d)throw new z(`Segregated data collection mismatch: ${i} vs ${d}`)});const h=a.map(t=>t+"");e.writeTo(d,h)}async function Rr(e,r,i,n){const s=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==s.length)throw new c("Segregated data keys and metadata length mismatch");const a=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(n)||lr(e.get("identity"));if(!a)throw new g("There's no assigned organization for model "+n.constructor.name);const o=s[0].collections,l="string"==typeof o?o:await o(n,a,e);e.readFrom(l)}async function $r(e,r,i,n,s){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(n)||lr(e.get("identity"));if(!l)throw new g("There's no assigned organization for model "+n.constructor.name);const d=a[0].collections,h="string"==typeof d?d:d(n,l,e);o.forEach((t,r)=>{const i="string"==typeof a[r].collections?a[r].collections:a[r].collections(n,l,e);if(i!==h)throw new z(`Segregated data collection mismatch: ${i} vs ${h}`)});const u=o.map(t=>t+"");e.writeTo(h,u)}async function Fr(e,r,i,n){const s=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==s.length)throw new c("Segregated data keys and metadata length mismatch");const a=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.ownerOf(n)||lr(e.get("identity"));if(!a)throw new g("There's no assigned organization for model "+n.constructor.name);const o=s[0].collections,l="string"==typeof o?o:o(n,a,e);e.readFrom(l)}function Dr(t,e,r){return(r,i)=>{const n=[];if(!i){const i=Ot.getAttributes(r);return i?.forEach(i=>{Dr(t,e)(r.prototype,i)}),r}{const r="string"==typeof t?t:t.toString(),i=r+":data",s={collections:t},a={priority:35,group:r+":extract"};n.push(Ft(),x(),(r,i)=>{const n=Ot.key(e,i),s=r.constructor,a=Ot.get(s,n)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],Ot.set(s,n,a);const c=Ot.get(s,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],Ot.set(s,e,c);const d={...Ot.get(s,w.TRANSIENT)||{},[i]:{}};Ot.set(s,w.TRANSIENT,d)},N(T.ALL,Tr,s,a),A(Ir,{collections:t},{priority:95,group:i}),v(Rr,{collections:t},{priority:95,group:i}),C($r,{collections:t},{priority:95,group:i}),E(Fr,{collections:t},{priority:95,group:i}))}return Rt(...n)(r,i)}}function kr(t=Sr){return It.for(Ue.PRIVATE).define({decorator:t=>Dr(t,Ue.PRIVATE),args:[t]}).apply()}function Pr(t){return It.for(Ue.SHARED).define({decorator:t=>Dr(t,Ue.SHARED),args:[t]}).apply()}function Lr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Lr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Lr(t[r]),e),{})}class jr 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[n.ANCHOR]=i||e.constructor.name;const s=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]=s(r[t])}),r}deserialize(e){const r=JSON.parse(e),i=r[n.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")(Lr(this.preSerialize(t)))}}function Br(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Mr(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 _r(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ye(`Addition overflow: ${t} + ${e}`);return r}function Ur(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ye(`Subtraction overflow: ${t} - ${e}`);return r}function Hr(t){if(!/^\d+$/.test(t))throw new g(s("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new g(s("Failed to parse: {0}","string is not a parsable integer"));return e}class zr extends i{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Lr(this.preSerialize(t,e)))}preSerialize(e,r=!0){const i=Object.assign({},e);let s;try{s=Ot.modelName(e.constructor)}catch(t){s=void 0}function a(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(a):this.preSerialize(t)}return r&&(i[n.ANCHOR]=s||e.constructor.name),t.relations(e).forEach(t=>{i[t]=a.call(this,i[t])}),i}}class Gr 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:n,caKey:s,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+n);const l=await Ke.getFirstDirFileNameContent(n);let d;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!s)throw new c(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+s),d=await Ke.getFirstDirFileNameContent(s)}return r.debug("Loading Admin user for ca "+i),this._user=await Ke.getCAUser("admin",d,l,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,Y.INITIALIZATION,!0)).for(this.initialize),[i]=t;if(!i)throw new c("Missing Fabric CA configuration");const{url:n,tls:s,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:l}=s,d=o[0];e.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const h=await Ke.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new Dt(n,{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 tt?(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,h.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const n=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${n.certs.length} certificates`),i.debug(n.certs),e?n.certs.map(t=>t.PEM):n}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 ve(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new G(i);default:return new ve(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,h.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,n,s,...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:n,maxEnrollments:s};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:n,key:s,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${n} in msp ${e}`);const o=tr.fabricIdFromCertificate(n),c=tr.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new Ge({id:c,credentials:{id:c,certificate:n,privateKey:s.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:n}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let s;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});s=Gr.identityFromEnrollment(r,this.config.caName,n),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${s.id}`)}catch(t){throw this.parseError(t)}return s}async registerAndEnroll(t,e=!1,r="",i,n,s,...a){const{ctx:o}=(await this.logCtx(a,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(t,e,r,i,n,s,o),{userName:l}=t;return this.enroll(l,c,o)}async updateIdentity(t,e,r,...i){const{log:n,ctx:s}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{n.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=qt.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=Gr.identityFromEnrollment(d,this.config.caName,s);n.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=qe(e.certificate);return await this.revoke(t,{aki:u,serial:g},i),n.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 n=await this.read(t);if(!n)throw new y("Could not find enrollment with id "+t);let s;try{const t={reason:e.serial||e.aki?"Revoke User Certificate":"User Deletion",...e,enrollmentID:n.id};s=await this.client.revoke(t,this.user)}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}}var Kr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Kr||(Kr={}));const qr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,allowContextTransientMap:!1,rebuildWithTransient:!0,encryptTransient:!1,syntheticEvents:!0}),Vr=new kt("fabric-fs");async function Yr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Wr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await nt(import("fs"));return await e.readFile(t)})(t)}async function Jr(t,e,r,i){Vr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const n=new qt(t),s=qt.newCryptoSuite();n.setCryptoSuite(s);const a=s.createKeyFromRaw(e);return await n.setEnrollment(a,r,i),n}async function Qr(t,e){return{mspId:t,credentials:await Yr(e,async t=>{const{promises:e}=await nt(import("fs")),r=await Xr(t);return await e.readFile(r)})}}async function Xr(t){const{promises:e}=await nt(import("fs")),{join:r}=await nt(import("path"));return r(t,(await e.readdir(t))[0])}async function Zr(t){const{promises:e}=await nt(import("fs")),{join:r}=await nt(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function ti(t){const e=await Yr(t,async t=>{const{promises:e}=await nt(import("fs")),r=await Xr(t);return await e.readFile(r)}),r=await ei(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}async function ei(t){let e;if(Pt())e=globalThis.crypto.subtle;else{const t=await nt(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)}}const ri=["allowGenerationOverride"];class ii extends tt{constructor(t){super(t)}toOverrides(){const t={};for(const e of ri){const r=this.getOrUndefined(e);void 0!==r&&(t[e]=r)}return t}}function ni(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 si 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:n}=e,{direction:s,limit:a}=i;switch(r){case q.FIND:break;case q.PAGE:n.push(s,a);break;case q.FIND_BY:break;case q.LIST_BY:n.push(s);break;case q.PAGE_BY:n.push(s,a);break;case q.FIND_ONE_BY:break;default:throw new c("Unsupported method "+r)}return e}async executePrepared(...t){const e=K.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(Y.QUERY,this.overrides||{},this.fromSelector)))throw new c("No context available for statement");if(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},n=[ht.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);n.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&n.push(ht.SELECT,this.selectSelector.join(` ${ht.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(ht.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),i.method=Mt(n.join(" ")),i.params=r,this.prepared=i,this}processRecord(e,r){const i=t.pk(this.fromSelector),n=Ot.get(this.fromSelector,Ot.key(w.ID,i))?.type;if(e[k.ID]){const[,...t]=e[k.ID].split(k.SEPARATOR),r=t.join("_");e[i]=Z.parseValue(n,r)}return super.processRecord(e,r)}async raw(t,...e){const{ctx:r}=this.logCtx(e,this.raw),i=t?.aggregateInfo;if(t?.aggregate&&i)return this.executeAggregate(i,r);const n=await this.adapter.raw(t,!0,this.fromSelector,r);if(!this.selectSelector){const t=n.map(t=>this.processRecord(t,r));return r.getOrUndefined("afterQueryHandlers")?await this.applyAfterHandlersToResult(t,r):t}return n}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 n={selector:i};if(this.selectSelector&&(n.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(ut.and(this.whereCondition,ut.attribute(k.TABLE).eq(n.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},[])],n.selector=t;break;case P.OR:{const e={};e[P.AND]=[t,...Object.entries(n.selector).map(([t,e])=>{const r={};return r[t]=e,r})],n.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{n.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${n.selector[t]} by ${r}`),n.selector[t]=r})}if(this.orderBySelectors?.length){n.sort=n.sort||[],n.selector=n.selector||{};for(const[t,e]of this.orderBySelectors){const r=t,i={};i[r]=e,n.sort.push(i),n.selector[r]||(n.selector[r]={},n.selector[r][L.BIGGER]=null)}}return this.limitSelector?n.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+j),n.limit=j),this.offsetSelector&&(n.skip=this.offsetSelector),n}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===gt.STARTS_WITH){if("string"!=typeof e)throw new ft("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new ft("STARTS_WITH requires a string comparison");const t={start:n=i,end:ni(n)},r={};return r[e]={},r[e][L.BIGGER_EQ]=t.start,r[e][L.SMALLER]=t.end,{selector:r}}var n,s;if(r===gt.ENDS_WITH){if("string"!=typeof e)throw new ft("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new ft("ENDS_WITH requires a string comparison");const t={};return t[e]={[L.REGEXP]:(s=i,s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===gt.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new ft("BETWEEN operator requires [min, max] comparison");const[r,n]=i,s={};return s[t]={},s[t][B(gt.BIGGER_EQ)]=r,s[t][B(gt.SMALLER_EQ)]=n,{selector:s}}let a={};if(-1===[pt.AND,pt.OR,gt.NOT].indexOf(r))a[e]={},a[e][B(r)]=i;else if(r===gt.NOT)a=this.parseCondition(e).selector,a[B(gt.NOT)]={},a[B(gt.NOT)][e.attr1]=i;else{const t=this.parseCondition(e).selector,n=this.parseCondition(i).selector;a=((t,e,r)=>{const i={selector:{}};return i.selector[t]=[e,r],i})(B(r),t,n).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 ft("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 ft(`No CouchDB view metadata found for table ${t.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const i=M(this.fromSelector,e,r);if(!i.length)return;const n=i[0],s=t.tableName(this.fromSelector),a=_(s,n.attribute,e,n),o=n.ddoc||U(s,a),c={reduce:void 0!==n.reduce||!n.returnDocs};return"distinct"!==e&&"groupBy"!==e||(c.group=!0),{kind:e,meta:n,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,n=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,e);return this.processViewResponse(t,n)}async handleAverage(t,e){if("avg"!==t.kind)throw new ft("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,n]=[t.sumDescriptor,t.countDescriptor],[s,a]=await Promise.all([r.view(i.ddoc,i.view,i.options,e),r.view(n.ddoc,n.view,n.options,e)]),o=s.rows?.[0]?.value??0,c=a.rows?.[0]?.value??0;return c?o/c:0}processViewResponse(t,e){if("avg"===t.kind)throw new ft("Average results should be handled before processing rows");const r=e.rows||[],i=t,n=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(t=>t.key??t.value):n.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}}var ai;class oi extends mt{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new je}static{this.log=jt.for(oi)}get Context(){return ii}constructor(t,e){super(Object.assign({},qr,t),ze,e),this.serializer=oi.serializer}chaincodeFor(t,...e){return oi.chaincodeFor(t,this.config,...e)}channelFor(t,...e){return oi.channelFor(t,this.config,...e)}contractFor(t,...e){return oi.contractFor(t,this.config,...e)}Statement(t){return new si(this,t)}Paginator(t,e,r){return new me(this,t,e,r)}async flags(t,e,r,...i){const n=Object.assign({},this.config,r);return Object.assign(await super.flags(t,e,n,...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.tableName(e)):t.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let s=n.pop();void 0===s||s instanceof tt||(n.push(s),s=void 0),r=s?Object.assign({},s.toOverrides(),r):r;const a=await this.flags("string"==typeof e?e:e.name,i,r,...[...n,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...a,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}const t=s.getOrUndefined("operation"),r=s.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const t=(new this.Context).accumulate({...s.cache,...a,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(a)}return(new this.Context).accumulate({...a})}decode(t){return oi.decoder.decode(t)}repository(){return De}createPrefix(e,r,i,...n){const{ctxArgs:s}=this.logCtx(n,this.createPrefix),a=t.tableName(e),o={};return o[k.TABLE]=a,Object.assign(o,i),[e,r,o,...s]}createAllPrefix(e,r,i,...n){const s=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(n,this.createAllPrefix),o=r.map((t,e)=>{const r={};return r[k.TABLE]=s,Object.assign(r,i[e]),r});return[e,r,o,...a]}updateAllPrefix(e,r,i,...n){const s=t.tableName(e);if(r.length!==i.length)throw new c("Ids and models must have the same length");const{ctxArgs:a}=this.logCtx(n,this.updateAllPrefix),o=r.map(()=>{const t={};return t[k.TABLE]=s,t});return[e,r,o,...a]}async createAll(e,r,i,...n){if(r.length!==i.length)throw new c("Ids and models must have the same length");const s=[...n],a=s.shift(),{log:o,ctx:l}=this.logCtx(s,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),g=i.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,I.CREATE_ALL,[JSON.stringify(g)],h?{[d]:a}:void 0,this.getEndorsingOrganizations(l),e);let m;try{m=JSON.parse(this.decode(p)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}return this.shouldRefreshAfterWrite(e,l,u,m[0][t.pk(e)]||r[0])?this.readAll(e,Me(e,i.map((e,r)=>t.merge(Object.assign({},e,a?.[r]||{}),m[r])),r),l):m}async readAll(e,r,...i){const{log:n,ctx:s}=this.logCtx(i,this.readAll),a=t.tableName(e);n.info(`reading ${r.length} entries to ${a} table`),n.verbose("pks: "+r);const o=await this.evaluateTransaction(s,I.READ_ALL,[JSON.stringify(r)],void 0,void 0,e);try{return JSON.parse(this.decode(o)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}}async updateAll(e,r,i,...n){if(r.length!==i.length)throw new c("Ids and models must have the same length");const s=[...n],a=s.shift(),{log:o,ctx:l}=this.logCtx(s,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),g=i.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,I.UPDATE_ALL,[JSON.stringify(g)],h?{[d]:a}:void 0,this.getEndorsingOrganizations(l),e);let m;try{m=JSON.parse(this.decode(p)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}return this.shouldRefreshAfterWrite(e,l,u,r[0])?this.readAll(e,Me(e,i.map((e,r)=>t.merge(Object.assign({},e,a?.[r]||{}),m[r])),r),l):m}async deleteAll(e,r,...i){const{log:n,ctx:s,ctxArgs:a}=this.logCtx(i,this.deleteAll),o=t.tableName(e),c=t.isTransient(e)||this.shouldForceGatewayHydration(s);let l;const d=this.shouldRefreshAfterWrite(e,s,c,r[0]);d&&(l=await this.readAll(e,r,...a)),n.info(`deleting ${r.length} entries to ${o} table`),n.verbose("pks: "+r);const h=await this.submitTransaction(s,I.DELETE_ALL,[JSON.stringify(r)],void 0,this.getEndorsingOrganizations(s),e);try{return d?l:JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new f(t)}}prepare(e,...r){const{log:i,ctx:n}=this.logCtx(r,this.prepare),s=t.segregate(e);e[Y.METADATA]&&(i.silly("Passing along persistence metadata for "+e[Y.METADATA]),Object.defineProperty(s.model,Y.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[Y.METADATA]}));const a=t.mirroredAt(e);if(a){const t=a.mspId;if(!t)throw new c("No mirror MSP could be found");let e=this.getEndorsingOrganizations(n)||[];e=Array.isArray(e)?e:[e];const r=[...new Set([...e,t])];n.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:s.model,model:s.model,id:e[t.pk(e.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(t,e,r,i,...n){const{log:s,ctx:a}=this.logCtx(n,this.revert);return i&&this.shouldRebuildWithTransient(a,a.getOrUndefined("operation"))&&(s.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]&&s.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,n){if(!i)return!1;const s=t.pk(e),a=t.composed(e,s),o=t.generated(e,s),c=null!=n;return!(c||!a)||(!c&&o?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}injectTransientOverrides(t,e){const r=this.hasMeaningfulTransientData(t),i=!!e.getOrUndefined("allowContextTransientMap");if(!r&&!i)return;const n=e.toOverrides(),s=r?Object.assign({},t):{};return i&&Object.keys(n).length&&(s[Ue.OVERRIDES]=n),Object.keys(s).length?s:void 0}hasMeaningfulTransientData(t){if(null==t)return!1;if(Array.isArray(t))return t.some(t=>this.hasMeaningfulTransientData(t));if("object"!=typeof t)return!0;const e=Object.entries(t);return!!e.length&&e.some(([,t])=>this.hasMeaningfulTransientData(t))}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,n={},...s){const a=[...s],{log:o,ctx:c}=this.logCtx(a,this.create),l=t.tableName(e);o.verbose(`adding entry to ${l} table`),o.debug("pk: "+r);const d=n&&Object.keys(n).length>0,u=d||this.shouldForceGatewayHydration(c),g=await this.submitTransaction(c,h.CREATE,[this.serializer.serialize(i,e.name)],d?{[l]:n}:void 0,this.getEndorsingOrganizations(c),e),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,Me(e,t.merge(Object.assign({},i,n||{}),f,e),r),c):f}async healthcheck(e,...r){const{log:i,ctx:n}=this.logCtx(r,this.healthcheck),s=t.tableName(e);i.verbose(`reading entry from ${s} table`);const a=await this.evaluateTransaction(n,"healthcheck",[],void 0,void 0,e);return JSON.parse(this.decode(a))}async read(e,r,...i){const{log:n,ctx:s}=this.logCtx(i,this.read),a=t.tableName(e);n.verbose(`reading entry from ${a} table`),n.debug("pk: "+r);const o=await this.evaluateTransaction(s,h.READ,[r.toString()],void 0,void 0,e);return this.serializer.deserialize(this.decode(o))}updatePrefix(e,r,i,...n){const s=t.tableName(e),{ctxArgs:a}=this.logCtx(n,this.updatePrefix),o={};return o[k.TABLE]=s,Object.assign(o,i),[e,r,o,...a]}async update(e,r,i,n={},...s){const a=[...s],{log:o,ctx:c}=this.logCtx(a,this.update);o.info("CLIENT UPDATE class : "+typeof e);const l=t.tableName(e);o.verbose(`updating entry to ${l} table`),o.debug("pk: "+r);const d=n&&Object.keys(n).length>0,u=d||this.shouldForceGatewayHydration(c),g=await this.submitTransaction(c,h.UPDATE,[this.serializer.serialize(i,e.name)],d?{[l]:n}:void 0,this.getEndorsingOrganizations(c),e),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,u,r)?this.read(e,Me(e,t.merge(Object.assign({},i,n||{}),f,e),r),c):f}async delete(e,r,...i){const{log:n,ctx:s}=this.logCtx(i,this.delete),a=t.tableName(e),o=t.isTransient(e)||this.shouldForceGatewayHydration(s);let c;const l=this.shouldRefreshAfterWrite(e,s,o,r);l&&(c=await this.read(e,r,s)),n.verbose(`deleting entry from ${a} table`),n.debug("pk: "+r);const d=await this.submitTransaction(s,h.DELETE,[r.toString()],void 0,this.getEndorsingOrganizations(s),e);return l?c:this.serializer.deserialize(this.decode(d))}async raw(e,r=!0,i,...n){const{log:s,ctx:a}=this.logCtx(n,this.raw);let o,c;s.info("Performing raw statement on table "+t.tableName(i));try{o=await this.evaluateTransaction(a,"raw",[JSON.stringify(e),r],void 0,void 0,i)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new f("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const e=c[0];return t.isModel(e)?c.map(e=>t.build(e)):c}return l=c,t.isModel(l)?t.build(l):l;var l}async view(t,e,r,...i){const{log:n,ctx:s}=this.logCtx(i,this.view);let a,o;n.info(`Querying view ${t}/${e}`);try{a=await this.evaluateTransaction(s,"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 f("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=oi.getClient(this.config)),this._client}async Gateway(t){return oi.getGateway(t,this.config,this.client)}async Contract(t,e){return oi.getContract(await this.Gateway(t),this.config,e,t)}async transaction(t,e,r=!0,i,n={},s,a){const o=this.log.for(this.transaction);if(n=this.injectTransientOverrides(n,t),r&&this.shouldUseLegacyGateway(t)){const r=this.prepareLegacyArgs(i),s=this.buildLegacyTransient(n),o=this.buildLegacyPeerConfigs(t);return await this.submitLegacyWithExplicitEndorsers(t,e,r,s,o,a)}const c=await this.Gateway(t);try{const c=await this.Contract(t,a);o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${c.getContractName()}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate,d=(i||[]).map(t=>this.normalizeTransactionArgument(t)),h=Object.entries(n||{});s=s?.length?s:void 0;const u={arguments:d,transientData:h.length?h.reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}):void 0,endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&s||void 0};return await l.call(c,e,u)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}normalizeTransactionArgument(t){return null==t||"string"==typeof t||"object"!=typeof t||t instanceof Uint8Array?t:JSON.stringify(t)}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}resolveLegacyMspCount(){const t=this.config.legacyMspCount??1,e=Number(t);return!Number.isFinite(e)||1>e?1:Math.floor(e)}pickLegacyCandidates(t,e){if(!t.length||0>=e)return[];const r=[...t],i=Math.min(e,r.length),n=[];for(;n.length<i&&r.length;){const t=Math.floor(Math.random()*r.length),[e]=r.splice(t,1);e&&n.push(e)}return n}buildLegacyPeerConfigs(t){const e=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}];let r=this.getEndorsingOrganizations(t)||[];r=Array.isArray(r)?r:[r];const i=(r.filter(t=>!!t)||[]).filter(t=>t!==this.config.mspId);if(!i.length)return e;const n=this.config.mspMap,s=this.resolveLegacyMspCount();for(const t of i){const r=n?.[t];if(!r?.length)throw new z(`No peer mapping available for MSP ${t}. Provide it via config.mspMap`);const i=this.pickLegacyCandidates(r,s);if(!i.length)throw new z(`No valid peer mapping available for MSP ${t}. Provide it via config.mspMap`);for(const r of i){if(!r.endpoint)throw new z(`Invalid peer mapping for MSP ${t}: missing endpoint`);e.push({mspId:t,peerEndpoint:r.endpoint,peerHostAlias:r.alias,tlsCert:r.tlsCert||this.config.tlsCert})}}return e}async submitLegacyWithExplicitEndorsers(t,e,r,i,n,s){const a=this.log.for(this.submitLegacyWithExplicitEndorsers),o=this.normalizeLegacyPeers(n),l=await this.resolveLegacyIdentityMaterial(),d=await te.newInMemoryWallet(),h=this.config.mspId+"-legacy";await d.put(h,{credentials:{certificate:l.certificate,privateKey:l.privateKey},mspId:this.config.mspId,type:"X.509"});const u=await this.buildLegacyConnectionProfile(o),g=new ee;try{await g.connect(u,{identity:h,wallet:d,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(o)},tlsInfo:{certificate:l.certificate,key:l.privateKey}});let n=this.config.channel,f=this.config.chaincodeName,p=this.config.contractName;if(s)if("string"==typeof s)p=s;else{if(!t)throw new c("No context received to determine chaincode config");n=await this.channelFor(s,t)||n,f=await this.chaincodeFor(s,t)||f,p=await this.contractFor(s,t)}const m=await g.getNetwork(n),y=m.getContract(f,p).createTransaction(e);i&&y.setTransient(i);const w=o.map(t=>m.getChannel().getEndorser(t.name)).filter(t=>!!t);w.length&&y.setEndorsingPeers(w),a.verbose(`Legacy submitting ${p}.${e} via peers ${o.map(t=>t.peerEndpoint).join(", ")}`);const b=await y.submit(...r);return Uint8Array.from(b)}catch(t){throw this.parseError(t)}finally{g.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 n of t){const t=await this.readPemInput(n.tlsCert||this.config.tlsCert),s=n.peerHostAlias||this.extractHost(n.peerEndpoint);e[n.name]={url:this.ensureGrpcUrl(n.peerEndpoint),tlsCACerts:{pem:t},grpcOptions:{"ssl-target-name-override":s,hostnameOverride:s}},r[n.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[n.mspId]=i[n.mspId]||{mspid:n.mspId,peers:[]},i[n.mspId].peers.push(n.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 re.promises.stat(t).catch(()=>{});return r?.isDirectory()?await Zr(t):(await Wr(t)).toString()}parseError(t){return oi.parseError(t)}async submitTransaction(t,e,r,i,n,s){return this.transaction(t,e,!0,r,i,n,s)}async evaluateTransaction(t,e,r,i,n,s){return this.transaction(t,e,!1,r,i,n,s)}async migrate(t,...e){const{ctx:r}=(await this.logCtx(e,Y.MIGRATION,!0)).for(this.migrate);return this.submitTransaction(r,"migrate",[t,e],void 0,void 0,"MigrationContract")}async shutdown(...t){await super.shutdown(...t),this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static async getContract(t,e,r,i){const n=this.log.for(this.getContract);let s=e.channel,a=e.chaincodeName,o=e.contractName;if(r)if("string"==typeof r)o=r;else{if(!i)throw new c("No context received to determine chaincode config");s=await this.channelFor(r,e,i)||s,a=await this.chaincodeFor(r,e,i)||a,o=await this.contractFor(r,e,i)}const l=this.getNetwork(t,s);let d;try{n.debug(`Retrieving chaincode ${a} contract ${o} from network ${s}`),d=l.getContract(a,o)}catch(t){throw this.parseError(t)}return d}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(re.readFileSync(r,"utf8"))}catch(t){throw new c(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Xt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Zt(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 n=await Qr(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+tr.fabricIdFromCertificate(n.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let s;if(e.hsm)throw new z("HSM NOT IMPLEMENTED");s=await ti(e.keyCertOrDirectoryPath);const a={client:t,identity:n,signer:s,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+e.mspId);const o=zt(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new oi._baseDispatch(this.client)}static chaincodeFor(e,r,...i){return t.chaincodeOf(e,...i)||r.chaincodeName}static channelFor(e,r,...i){return t.channelOf(e,...i)||r.channel}static contractFor(e,r,...i){return t.contractOf(e,...i)||sr(e,...i)}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),t instanceof Kt&&t.details.length&&10===t.code&&t.details[0].message?.includes(z.name)&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new xe(t):e.includes("DEADLINE_EXCEEDED")?new Re(t):e.includes("chaincode stream terminated")||e.includes("RESOURCE_EXHAUSTED")||e.includes("received message larger than max")||e.includes("grpc: received message larger")?new Fe(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Te(t):e.includes("PHANTOM_READ_CONFLICT")?new Ne(t):t instanceof Error&&t.code&&9===t.code?new Oe(t):e.includes(g.name)?new g(t):e.includes(y.name)?new y(t):e.includes(m.name)?new m(t):e.includes(R.name)?new R(t):e.includes(ft.name)?new ft(t):e.includes(yt.name)?new yt(t):e.includes(z.name)?new z(t):e.includes(wt.name)?new wt(t):e.includes(bt.name)?new bt(t):e.includes(G.name)?new G(t):e.includes(vt.name)?new vt(t):e.includes(At.name)?new At(t):e.includes(f.name)?new f(t):new c(t)}}Et([_t(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"create",null),Et([_t(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,ii]),St("design:returntype",Promise)],oi.prototype,"healthcheck",null),Et([_t(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"read",null),Et([_t(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"update",null),Et([_t(),Ut(),St("design:type",Function),St("design:paramtypes",[Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"delete",null),Et([_t(),St("design:type",Function),St("design:paramtypes",[Object,"function"==typeof(ai="undefined"!=typeof D&&D)?ai:Object,Object,ii]),St("design:returntype",Promise)],oi.prototype,"raw",null),Et([_t(),St("design:type",Function),St("design:paramtypes",[String,String,Object,ii]),St("design:returntype",Promise)],oi.prototype,"view",null),oi.decoration(),mt.setCurrent(ze);class ci extends Ct{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,Y.SHUTDOWN,!0)).for(this.close);try{await super.close(...r)}catch(t){e.error("Failed to close Fabric proxies event listener",t)}if(this.listeningStack)try{await this.listeningStack.close()}catch(t){e.error("Failed to close Fabric event listener",t)}finally{this.listeningStack=void 0}}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof oi))throw new z("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(e,r,i,...n){const{log:s,ctxArgs:a}=mt.logCtx(this.updateObservers,r,!1,...n);if(this.adapter)try{await this.adapter.refresh(e,r,i,...a)}catch(t){throw new c("Failed to refresh dispatch: "+t)}else s.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(h.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:n,event:s,owner:a}=Mr(e.eventName);if(this.adapter.config?.mspEventOnly&&a&&a!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(n?t.get(n):t.get(this.models[0].name))??(n||this.models[0]?.name),i=o.result?[o.result,r]:[r];await this.updateObservers(e,s,o.id,...i)}catch(t){i.error(`Failed update observables for table ${n} event ${s} 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(r)}}async initialize(){if(!this.adapter)throw new c("No adapter or config observed for dispatch");const e=!1!==this.adapter.config.syntheticEvents;if(!e){const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t),{ctx:r}=this.logCtx([e],this.initialize),i=(await oi.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)}[h.CREATE,h.UPDATE,h.DELETE,I.CREATE_ALL,I.UPDATE_ALL,I.DELETE_ALL].forEach(r=>{if(!this.adapter)throw new c("No adapter provided for the fallback of fully segregated models");if(!this.adapter[r])throw new c(`Method ${r} not found in ${this.adapter.alias} adapter to bind Observables Dispatch`);let i=Object.getOwnPropertyDescriptor(this.adapter,r),n=this.adapter;for(;!i&&n!==Object.prototype;)n=Object.getPrototypeOf(n),i=Object.getOwnPropertyDescriptor(n,r);function s(t){switch(t){case I.CREATE_ALL:return h.CREATE;case I.UPDATE_ALL:return h.UPDATE;case I.DELETE_ALL:return h.DELETE;default:return t}}i&&i.writable?this.adapter[r]=new Proxy(this.adapter[r],{apply:async(i,n,a)=>{const o=await i.apply(n,a),c=a[0];if(!e&&!t.isTransient(c))return o;const{log:l,ctxArgs:d,ctx:h}=n.logCtx(a.slice(a.length-1),i),u=a[1],g=[c,s(r),u];return h.getOrUndefined("observeFullResult")&&g.push(o),this.updateObservers(g[0],g[1],g[2],...g.slice(3),...d).catch(t=>l.error(`Failed to dispatch observer refresh for ${r} on ${c.name||c} for ${u}: ${t}`)),o}}):this.log.error(`Could not find method ${r} to bind Observables Dispatch`)})}}oi&&(oi._baseDispatch=ci);const li="##VERSION##",di="##COMMIT##",hi="##FULL_VERSION##",ui="##PACKAGE##";Ot.registerLibrary(ui,li);export{be as AllowanceError,Ye as BASE_ALPHABET,we as BalanceError,Ze as BaseEncoder,Kr as CA_ROLE,di as COMMIT,We as CRYPTO,je as ClientSerializer,Ke as CoreUtils,tr as CryptoUtils,sr as DefaultContractResolver,qr as DefaultFabricClientFlags,jr as DeterministicSerializer,Xe as ERC20Events,Oe as EndorsementError,Te as EndorsementPolicyError,hi as FULL_VERSION,ir as FabricBaseModel,oi as FabricClientAdapter,ii as FabricClientContext,ci as FabricClientDispatch,De as FabricClientRepository,Be as FabricERC20ClientRepository,er as FabricEnrollmentService,ze as FabricFlavour,nr as FabricIdentifiedBaseModel,Gr as FabricIdentityService,Ue as FabricModelKeys,Qe as HFCAIdentityAttributes,Je as HFCAIdentityType,Ge as Identity,_e as IdentityCredentials,He as IdentityType,Sr as ImplicitPrivateCollection,Ae as MissingContextError,Se as MissingPKCSS11Lib,Cr as ModelCollection,xe as MvccReadConflictError,Er as NamespaceCollection,Ee as NotInitializedError,ye as OverflowError,dr as Owner,ui as PACKAGE_NAME,Ne as PhantomReadConflictError,Fe as QueryResultTooLargeError,ve as RegistrationError,rr as RegistrationRequestBuilder,Or as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,zr as SimpleDeterministicSerializer,$e as TransactionBufferSizeError,Ie as TransactionLimitsError,Re as TransactionTimeoutError,Ce as UnauthorizedPrivateDataAccess,li as VERSION,_r as add,Nr as applyMirrorFlags,xr as applySegregationFlags,or as chaincode,cr as channel,de as collectionFor,Yr as contentOfLoadFile,ar as contract,mr as createMirrorHandler,wr as deleteMirrorHandler,pr as evalMirrorMetadata,ge as extractCollections,Me as extractIds,lr as extractMspId,ei as extractPrivateKey,Tr as extractSegregatedCollections,Br as generateFabricEventName,se as generateModelDesignDocs,ne as generateModelIndexes,qe as getAkiAndSerialFromCert,Jr as getCAUser,Xr as getFirstDirFileName,Zr as getFirstDirFileNameContent,Qr as getIdentity,ti as getSigner,Ar as mirror,br as mirrorWriteGuard,ur as ownedBy,hr as ownedByOnCreate,Mr as parseEventName,he as privateCollectionFor,kr as privateData,Wr as readFile,vr as readMirrorHandler,ae as readModelFile,oe as readModelFolders,Hr as safeParseInt,Ir as segregatedDataOnCreate,Fr as segregatedDataOnDelete,Rr as segregatedDataOnRead,$r as segregatedDataOnUpdate,ue as sharedCollectionFor,Pr as sharedData,Lr as sortKeysOnlyRecursive,Ur as sub,fr as transactionId,gr as transactionIdOnCreate,yr as updateMirrorHandler,pe as writeCollectionDesignDocs,fe as writeCollections,le as writeDesignDocs,ce as writeIndexes};
2
2
  //# sourceMappingURL=for-fabric.js.map