@decaf-ts/for-fabric 0.3.11 → 0.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/for-fabric.cjs +1 -1
- package/dist/for-fabric.cjs.map +1 -1
- package/dist/for-fabric.js +1 -1
- package/dist/for-fabric.js.map +1 -1
- package/lib/client/FabricClientAdapter.cjs +30 -19
- package/lib/client/FabricClientAdapter.js.map +1 -1
- package/lib/client/collections/generation.d.ts +0 -11
- package/lib/client/collections/generation.js.map +1 -1
- package/lib/client/ids/id-extraction.cjs +30 -0
- package/lib/client/ids/id-extraction.d.ts +4 -0
- package/lib/client/ids/id-extraction.js.map +1 -0
- package/lib/client/ids/index.cjs +18 -0
- package/lib/client/ids/index.d.ts +1 -0
- package/lib/client/ids/index.js.map +1 -0
- package/lib/client/index.cjs +2 -0
- package/lib/client/index.d.ts +2 -0
- package/lib/client/index.js.map +1 -1
- package/lib/contract/OtherBatchContract.cjs +30 -0
- package/lib/contract/OtherBatchContract.d.ts +5 -0
- package/lib/contract/OtherBatchContract.js.map +1 -0
- package/lib/contract/models/OtherBatchShared.cjs +122 -0
- package/lib/contract/models/OtherBatchShared.d.ts +18 -0
- package/lib/contract/models/OtherBatchShared.js.map +1 -0
- package/lib/contracts/ContractAdapter.cjs +54 -39
- package/lib/contracts/ContractAdapter.js.map +1 -1
- package/lib/contracts/FabricContractPaginator.cjs +1 -1
- package/lib/contracts/FabricContractPaginator.js.map +1 -1
- package/lib/esm/client/FabricClientAdapter.js +30 -19
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/client/collections/generation.d.ts +0 -11
- package/lib/esm/client/collections/generation.js.map +1 -1
- package/lib/esm/client/ids/id-extraction.d.ts +4 -0
- package/lib/esm/client/ids/id-extraction.js +27 -0
- package/lib/esm/client/ids/id-extraction.js.map +1 -0
- package/lib/esm/client/ids/index.d.ts +1 -0
- package/lib/esm/client/ids/index.js +2 -0
- package/lib/esm/client/ids/index.js.map +1 -0
- package/lib/esm/client/index.d.ts +2 -0
- package/lib/esm/client/index.js +2 -0
- package/lib/esm/client/index.js.map +1 -1
- package/lib/esm/contract/OtherBatchContract.d.ts +5 -0
- package/lib/esm/contract/OtherBatchContract.js +27 -0
- package/lib/esm/contract/OtherBatchContract.js.map +1 -0
- package/lib/esm/contract/models/OtherBatchShared.d.ts +18 -0
- package/lib/esm/contract/models/OtherBatchShared.js +119 -0
- package/lib/esm/contract/models/OtherBatchShared.js.map +1 -0
- package/lib/esm/contracts/ContractAdapter.js +54 -39
- package/lib/esm/contracts/ContractAdapter.js.map +1 -1
- package/lib/esm/contracts/FabricContractPaginator.js +1 -1
- package/lib/esm/contracts/FabricContractPaginator.js.map +1 -1
- package/lib/esm/shared/decorators.js +5 -0
- package/lib/esm/shared/decorators.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/shared/decorators.cjs +5 -0
- package/lib/shared/decorators.js.map +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/for-fabric.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Repository as t,PreparedStatementKeys as e,OrderDirection as r,PersistenceKeys as i,Paginator as s,pk as n,column as a,table as o,BaseModel as c,Sequence as l,Context as d,oneToOne as h,Cascade as u,index as g,normalizeImport as f,AuthorizationError as p,createdAt as m,updatedAt as y,createdBy as w,updatedBy as b,UnsupportedError as A,ClientBasedService as v,Statement as C,QueryClause as S,Condition as E,Operator as O,QueryError as x,GroupOperator as N,Adapter as T,PagingError as I,MigrationError as $,ObserverError as R,ForbiddenError as F,ConnectionError as k,Dispatch as B}from"@decaf-ts/core";import{Model as P,required as _,model as j,JSONSerializer as L,ModelKeys as M,stringFormat as z,minlength as U,min as H}from"@decaf-ts/decorator-validation";import{OperationKeys as K,enforceDBDecorators as G,reduceErrorsToPrint as Y,ValidationError as V,SerializationError as W,InternalError as q,BaseError as J,ConflictError as Q,NotFoundError as X,version as Z,DBKeys as tt,generated as et,readonly as rt,onCreate as it,onUpdate as st,onRead as nt,onDelete as at,afterCreate as ot,afterUpdate as ct,afterDelete as lt,transient as dt,on as ht,DBOperations as ut,BulkCrudOperationKeys as gt,BadRequestError as ft}from"@decaf-ts/db-decorators";import{CouchDBKeys as pt,generateIndexes as mt,generateViews as yt,CouchDBGroupOperator as wt,CouchDBOperator as bt,CouchDBQueryLimit as At,translateOperators as vt,findViewMetadata as Ct,generateViewName as St,generateDesignDocName as Et}from"@decaf-ts/for-couchdb";import{__decorate as Ot,__metadata as xt}from"tslib";import{Metadata as Nt,description as Tt,uses as It,Decoration as $t,apply as Rt,propMetadata as Dt,metadata as Ft,prop as kt}from"@decaf-ts/decoration";import Bt from"fabric-ca-client";import{MiniLogger as Pt,isBrowser as _t,LoggedClass as jt,Logging as Lt,toPascalCase as Mt,toCamelCase as zt,debug as Ut,final as Ht}from"@decaf-ts/logging";import{signers as Kt,connect as Gt,GatewayError as Yt}from"@hyperledger/fabric-gateway";import{User as Vt}from"fabric-common";import Wt,{X509Certificate as qt}from"crypto";import*as Jt from"@peculiar/x509";import{X509Certificate as Qt}from"@peculiar/x509";import{Crypto as Xt}from"@peculiar/webcrypto";import*as Zt from"@grpc/grpc-js";import{Client as te}from"@grpc/grpc-js";import ee from"fs";class re extends t{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(t){return super.override(Object.assign({},t,this._overrides)).for(t)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(t,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,e.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${P.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,t,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${P.tableName(this.class)} by ${t} ${r}`),await this.statement(this.listBy.name,t,r,...n)}async findBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${P.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findBy.name,t,r,...n)}async findOneBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${P.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async find(t,i=r.ASC,...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,e.FIND,!0)).for(this.find);return n.verbose(`finding ${P.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,t,i,...a)}async page(t,i=r.ASC,s={offset:1,limit:10},...n){const{log:a,ctxArgs:o}=(await this.logCtx(n,e.PAGE,!0)).for(this.page);return a.verbose(`paging ${P.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,t,i,s,...o)}async statement(t,...e){const{log:r,ctx:n,ctxArgs:a}=(await this.logCtx(e,i.STATEMENT,!0)).for(this.statement);r.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,i.STATEMENT,[t,JSON.stringify(o)],void 0,void 0,this.class.name)));return Array.isArray(c)?c.map(t=>t[pt.TABLE]&&t[pt.TABLE]===P.tableName(this.class)?new this.class(t):t):c[pt.TABLE]&&c[pt.TABLE]===P.tableName(this.class)?new this.class(c):s.isSerializedPage(c)?Object.assign(c,{data:c.data.map(t=>new this.class(t))}):c}async countOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${P.tableName(this.class)}${t?" by "+t:""}`);const n=t?[t,...s]:s;return this.statement(e.COUNT_OF,...n)}async maxOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${t} in ${P.tableName(this.class)}`),this.statement(e.MAX_OF,t,...s)}async minOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${t} in ${P.tableName(this.class)}`),this.statement(e.MIN_OF,t,...s)}async avgOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${t} in ${P.tableName(this.class)}`),this.statement(e.AVG_OF,t,...s)}async sumOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${t} in ${P.tableName(this.class)}`),this.statement(e.SUM_OF,t,...s)}async distinctOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${t} in ${P.tableName(this.class)}`),this.statement(e.DISTINCT_OF,t,...s)}async groupOf(t,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,e.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${P.tableName(this.class)} by ${t}`),this.statement(e.GROUP_OF,t,...s)}async healthcheck(...t){const{ctxArgs:e}=this.logCtx(t,this.healthcheck);return await this.adapter.healthcheck(this.class,...e)}async create(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.create);i.debug(`Creating new ${this.class.name} in table ${P.tableName(this.class)}`),this.ensureLegacyMirrorFlag(r,t);const n=this.adapter.prepare(t,r),{record:a,id:o,transient:c}=n,l=await this.adapter.create(this.class,o,a,c,...s);return this.adapter.revert(l,this.class,o,c,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);this.ensureLegacyMirrorFlag(s,t);const n=this.adapter.prepare(t,s),{id:a,transient:o}=n;let c=n.record;return i.debug(`updating ${this.class.name} in table ${P.tableName(this.class)} with id ${a}`),c=await this.adapter.update(this.class,a,c,o,...r),this.adapter.revert(c,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,K.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 G(this,r,t,K.CREATE,K.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=Y(i);if(s)throw new V(s)}return[t,...i]}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.createAll);i.debug(`Creating ${t.length} new ${this.class.name} in table ${P.tableName(this.class)}`),t.forEach(t=>this.ensureLegacyMirrorFlag(r,t));const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id),o=n.map(t=>t.record),c=n.map(t=>t.transient),l=await this.adapter.createAll(this.class,a,o,c,...s);return Promise.all(l.map(async(t,e)=>{const i=a[e];if(this.shouldRefreshAfterWrite(n[e],r)&&null!=i){const t=await this.adapter.read(this.class,i,r);return this.adapter.revert(t,this.class,i,r.get("rebuildWithTransient")?n[e].transient:void 0,r)}return this.adapter.revert(t,this.class,i,c[e],r)}))}async updateAll(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.updateAll);i.debug(`Updating ${t.length} new ${this.class.name} in table ${P.tableName(this.class)}`),t.forEach(t=>this.ensureLegacyMirrorFlag(r,t));const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id),o=await this.adapter.updateAll(this.class,a,n.map(t=>t.record),n.map(t=>t.transient),...s);return Promise.all(o.map(async(t,e)=>{const i=a[e];if(this.shouldRefreshAfterWrite(n[e],r)&&null!=i){const t=await this.adapter.read(this.class,i,r);return this.adapter.revert(t,this.class,i,r.get("rebuildWithTransient")?n[e].transient:void 0,r)}return this.adapter.revert(t,this.class,i,n[e].transient,r)}))}shouldRefreshAfterWrite(t,e){const r=t.privates&&Object.keys(t.privates).length>0,i=t.shared&&Object.keys(t.shared).length>0;return r||i||!!e.getOrUndefined("segregated")||!!e.getOrUndefined("mirror")}ensureLegacyMirrorFlag(t,e){P.mirroredAt(e)&&t.accumulate({legacy:!0})}}let ie=class extends c{constructor(t){super(t)}};Ot([n({type:String}),xt("design:type",String)],ie.prototype,"name",void 0),Ot([a(),_(),xt("design:type",String)],ie.prototype,"owner",void 0),Ot([a(),_(),xt("design:type",String)],ie.prototype,"symbol",void 0),Ot([a(),_(),xt("design:type",Number)],ie.prototype,"decimals",void 0),ie=Ot([o("erc20_tokens"),j(),xt("design:paramtypes",[Object])],ie);let se=class extends c{constructor(t){super(t)}};Ot([n({type:String}),xt("design:type",String)],se.prototype,"id",void 0),Ot([a(),_(),xt("design:type",String)],se.prototype,"token",void 0),Ot([a(),_(),xt("design:type",Number)],se.prototype,"balance",void 0),Ot([a(),xt("design:type",String)],se.prototype,"captive",void 0),se=Ot([o("erc20_wallets"),j(),xt("design:paramtypes",[Object])],se);let ne=class extends c{constructor(t){super(t)}};Ot([n({type:String}),a(),_(),xt("design:type",String)],ne.prototype,"owner",void 0),Ot([a(),_(),xt("design:type",String)],ne.prototype,"spender",void 0),Ot([a(),_(),xt("design:type",Number)],ne.prototype,"value",void 0),ne=Ot([o("erc20_allowances"),j(),xt("design:paramtypes",[Object])],ne);class ae extends L{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=Nt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new W("Could not find metadata for "+t.constructor.name);i=e}return r[M.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[M.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return P.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class oe extends re{static{this.serializer=new ae}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new q("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:n}=this.logCtx(i,this.updateObservers);let a;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),t="string"==typeof t?P.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>l.parseValue(P.sequenceFor(t).type,e)):l.parseValue(P.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return oe.decoder.decode(t)}constructor(t){super(t,se),this.serializer=oe.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 d.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 d.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 d.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 d.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[oe.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await d.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 d.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 d.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 d.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 d.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 d.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 ce(t){const e=require("fs"),r=require("path").dirname(t);if(e.existsSync(r))return!0;ce(r),e.mkdirSync(r)}function le(t){return mt([t])}function de(t,e){const r=yt([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function he(t){const e=require("path"),r=require(e.join(process.cwd(),t.parentPath,t.name));return Object.values(r).filter(t=>{try{return new t instanceof P}catch(t){return!1}})}async function ue(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...he(e))}return r}function ge(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`));ce(n),i.writeFileSync(n,JSON.stringify(t,void 0,2))})}function fe(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`));ce(a);const o={...t};delete o._rev,i.writeFileSync(a,JSON.stringify(o,void 0,2))})}let pe=class extends c{constructor(t){super(t)}};var me,ye;Ot([Tt("Unique identifier of the credentials record"),a(),n(),xt("design:type",String)],pe.prototype,"id",void 0),Ot([Tt("PEM-encoded X.509 certificate for the identity"),a(),_(),xt("design:type",String)],pe.prototype,"certificate",void 0),Ot([Tt("PEM-encoded root or intermediate certificate"),a(),_(),xt("design:type",String)],pe.prototype,"rootCertificate",void 0),Ot([Tt("PEM-encoded private key"),a(),_(),xt("design:type",String)],pe.prototype,"privateKey",void 0),pe=Ot([j(),xt("design:paramtypes",[Object])],pe),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(me||(me={})),(t=>{t.X509="X.509"})(ye||(ye={}));const we="hlf-fabric";let be=class extends c{constructor(t){super(t),this.type=ye.X509}};Ot([Tt("Unique identifier of the identity"),n(),xt("design:type",String)],be.prototype,"id",void 0),Ot([h(pe,{update:u.CASCADE,delete:u.CASCADE}),xt("design:type",pe)],be.prototype,"credentials",void 0),Ot([a(),_(),g(),xt("design:type",String)],be.prototype,"mspId",void 0),Ot([a(),_(),xt("design:type",String)],be.prototype,"type",void 0),be=Ot([j(),xt("design:paramtypes",[Object])],be);class Ae{static{this.logger=new Pt(Ae.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 f(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(z("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Vt(t),a=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,o=this.getCryptoSuite(a);n.setCryptoSuite(o);const c=s?.hsm?await this.getHSMEnrollmentKey(o,r,s.hsm):this.getSoftwareEnrollmentKey(o,e);return await n.setEnrollment(c,r,i),n}static getCryptoSuite(t){return t?(Ae.cryptoSuite||(Ae.cryptoSuite=Vt.newCryptoSuite(t)),Ae.cryptoSuite):Vt.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 qt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Wt.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 f(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})}}static async getFirstDirFileName(t){const{promises:e}=await f(import("fs")),{join:r}=await f(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await f(import("fs")),{join:r}=await f(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await f(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await f(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Kt.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await f(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 ve(t){const e=new Qt(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 Ce=new Xt;var Se,Ee,Oe,xe,Ne;Jt.cryptoProvider.set(Ce),(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-_.!~"})(Se||(Se={})),(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"})(Ee||(Ee={}));class Te{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 Ie{static{this.b58encoder=new Te(Se.BASE58)}static{this.logger=new Pt(Ie.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(z("Parsing certificate: {0}",t));const e=new Jt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(z("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=Ce.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 Ce.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 Jt.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,Ce.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Jt.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 _t()?globalThis.window.crypto.subtle:Ce.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=Ce.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Ee.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:Ee.KEY_ALGORYTHM,hash:Ee.HASH,salt:i,iterations:Ee.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Ee.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:Ee.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Ee.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Ee.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class $e extends q{constructor(t){super(t,$e.name)}}class Re extends q{constructor(t){super(t,Re.name)}}class De extends q{constructor(t){super(t,De.name)}}class Fe extends p{constructor(t){super(t,Fe.name)}}class ke extends q{constructor(t){super(t,ke.name,500)}}class Be extends J{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(Be.name,t,403)}}class Pe extends J{constructor(t){super(Pe.name,t,409)}}class _e extends q{constructor(t){super(t,_e.name,500)}}class je extends q{constructor(t){super(t,je.name,500)}}class Le extends q{constructor(t){super(t,Le.name,500)}}class Me extends q{constructor(t){super(t,Me.name,500)}}class ze extends q{constructor(t){super(t,ze.name,500)}}class Ue extends q{constructor(t,e=Ue.name,r=590){super(t,e,r)}}class He extends q{constructor(t){super(t,He.name,591)}}class Ke extends q{constructor(t){super(t,Ke.name,592)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Oe||(Oe={})),(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"})(xe||(xe={}));class Ge extends jt{constructor(t){Ae.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 Ae.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new q(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await Ae.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await Ae.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 Ae.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Bt(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 Fe(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new p(i);default:return new Fe(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 X(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new X(`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=Lt.for(Ge,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=Ie.fabricIdFromCertificate(r),o=Ie.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new be({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=Ge.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 X("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 q(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new q(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ye extends P{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new V(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}}Ot([_(),xt("design:type",String)],Ye.prototype,"affiliation",void 0),Ot([U(1),xt("design:type",Array)],Ye.prototype,"attrs",void 0),Ot([_(),xt("design:type",String)],Ye.prototype,"enrollmentID",void 0),Ot([_(),xt("design:type",String)],Ye.prototype,"enrollmentSecret",void 0),Ot([H(0),xt("design:type",Number)],Ye.prototype,"maxEnrollments",void 0),Ot([_(),xt("design:type",String)],Ye.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Ne||(Ne={}));let Ve=class extends P{constructor(t){super(t)}};Ot([Tt("Stores the original timestamp of creation"),a(),m(),xt("design:type",Date)],Ve.prototype,"createdAt",void 0),Ot([Tt("Stores the timestamp of the last update"),a(),y(),xt("design:type",Date)],Ve.prototype,"updatedAt",void 0),Ot([Tt("Stores the version of the model"),a(),Z(),xt("design:type",Number)],Ve.prototype,"version",void 0),Ve=Ot([It(we),xt("design:paramtypes",[Object])],Ve);let We=class extends Ve{constructor(t){super(t)}};function qe(t){if(t)return"string"==typeof t?t:t.getMSPID()}function Je(){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 X("No tokens avaialble");if(a.length>1)throw new X("To many token available : "+a.length);if(a[0].owner!=s)throw new p(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Qe(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function Xe(){return $t.for(me.OWNED_BY).define({decorator:()=>(t,e)=>Rt(_(),et(),rt(),it(Qe),Dt(Nt.key(me.FABRIC,me.OWNED_BY),e))(t,e),args:[]}).apply()}async function Ze(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function tr(){return $t.for(me.TRANSACTION_ID).define({decorator:()=>(t,e)=>Rt(_(),rt(),it(Ze),st(Ze),Dt(Nt.key(me.FABRIC,e,me.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function er(t,e,r){let i=e;if("string"!=typeof i)try{const s=P.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new q("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new q("No collection found model "+t.constructor.name);return i}async function rr(t,e,r,i){const s=await er(i,e.resolver,t),n=t;n.put("mirror",!0),n.put("mirrorCollection",s);try{const e=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0})),r=await e.create(i,t);t.logger.info(`Mirror for ${P.tableName(this.class)} created with ${P.pk(i)}: ${r[P.pk(i)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function ir(t,e,r,i){const s=await er(i,e.resolver,t),n=t;n.put("mirror",!0),n.put("mirrorCollection",s);try{const e=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:s,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await e.update(i,t),t.logger.info(`Mirror for ${P.tableName(this.class)} updated: ${i[P.pk(i)]}`)}finally{n.put("mirror",void 0),n.put("mirrorCollection",void 0)}}async function sr(t,e,r,i){const s=await er(i,e.resolver,t),n=t;n.put("mirror",!0),n.put("segregated",s);try{const e=i[P.pk(i)],r=this.override(Object.assign({},this._overrides,{segregated:s,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await r.delete(e,t)}catch{}t.logger.info(`Mirror for ${P.tableName(this.class)} deleted: ${e+""}`)}finally{n.put("mirror",void 0),n.put("segregated",void 0)}}async function nr(t,e,r,i){const s=qe(t.get("identity"));if(s&&(s===e.mspId||e.condition&&e.condition(s)))throw new p(`Organization ${s} is not authorized to modify mirrored data`)}async function ar(t,e,r,i){const s=qe(t.get("identity"));if(!s)return;const n=await er(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("fullySegregated",!0),a.readFrom(n))}function or(t,e,r){const i="string"!=typeof e&&!!e,s=i?void 0:e,n=i?e:r;return $t.for(me.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Rt(Ft(Nt.key(me.FABRIC,me.MIRROR),i),nt(ar,i,{priority:30}),it(nr,i,{priority:20}),st(nr,i,{priority:20}),at(nr,i,{priority:20}),ot(rr,i,{priority:95}),ct(ir,i,{priority:95}),lt(sr,i,{priority:95}))},args:[t,s,n]}).apply()}Ot([Tt("Stores the creator"),a(),w(),xt("design:type",String)],We.prototype,"createdBy",void 0),Ot([Tt("Stores the user that last updated the model"),a(),b(),xt("design:type",String)],We.prototype,"updatedBy",void 0),We=Ot([It(we),xt("design:paramtypes",[Object])],We),P.prototype.isShared=function(){return P.isShared(this.constructor)},P.prototype.isPrivate=function(){return P.isPrivate(this.constructor)},P.prototype.segregate=function(){return P.segregate(this)},P.segregate=(t=>{if(!P.isTransient(t))return{model:t};const e=Nt.getAttributes(t.constructor)||[],r=Nt.get(t.constructor,tt.TRANSIENT),i=Nt.get(t.constructor,me.PRIVATE),s=Nt.get(t.constructor,me.SHARED),n={model:{},public:{},transient:{},privates:{},shared:{}},a=Object.keys(r||{}),o=Object.keys(i||{}),c=Object.keys(s||{});for(const r of e){const e=t[r],i=a.includes(r),s=!i,l=o.includes(r),d=c.includes(r);(i||l||d)&&(n.transient=n.transient||{},n.transient[r]=e),l&&(n.privates=n.privates||{},n.privates[r]=e),d&&(n.shared=n.shared||{},n.shared[r]=e),s&&(n.public=n.public||{},n.public[r]=e)}return n.model=P.build(n.public,t.constructor.name),n}).bind(P),P.isPrivate=(t=>!!Nt.get("function"!=typeof t?t.constructor:t,me.PRIVATE)).bind(P),P.isShared=(t=>!!Nt.get("function"!=typeof t?t.constructor:t,me.SHARED)).bind(P),P.mirrored=(t=>Nt.get("function"!=typeof t?t.constructor:t,Nt.key(me.FABRIC,me.MIRROR))).bind(P),P.ownerOf=(t=>{const e=Nt.get(t.constructor,Nt.key(me.FABRIC,me.OWNED_BY));if(e)return t[e]}).bind(P),P.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Nt.get(t,Nt.key(me.FABRIC,me.MIRROR)))).bind(P),P.collectionsFor=(t=>{const e=[me.PRIVATE],r=[me.SHARED],i=Nt.key(...e),s=Nt.key(...r),n="function"==typeof t?t:t.constructor,a=Nt.get(n,i),o=Nt.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(P);const cr=(t,e)=>{const r=e||("function"!=typeof t?P.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new q(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Mt(i.name)}${r?Mt(r):""}`};function lr(t){return(e,r)=>{const i=r||("function"!=typeof e?P.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!i)throw new q(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${t}${i?Mt(i):""}`}}const dr=(t,e)=>{const r=e||("function"!=typeof t?P.ownerOf(t):void 0);if(!r)throw new q(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Mt(r)}PrivateCollection`},hr=35;function ur(t,e,r){e.length>0&&r.readFrom(e),!r.isFullySegregated&&e.length&&((t=>{const e=Nt.getAttributes(t)||[],r=P.pk(t),i=Nt.get(t,tt.TRANSIENT)||{},s=Nt.get(t,Nt.key(me.PRIVATE))||{},n=Nt.get(t,Nt.key(me.SHARED))||{};return e.some(t=>t!==r&&!(t in i)&&!(t in s)&&!(t in n))})(t.constructor)||r.markFullySegregated())}async function gr(t,e,r){if(!e)return;const i=P.mirroredAt(t);if(!i)return;if(!(e===i.mspId||i.condition&&i.condition(e)))return;const s=await er(new t,i.resolver,r);r.put("fullySegregated",!0),r.readFrom(s)}async function fr(t,e,r,i){const s=Array.isArray(e)?e:[e],n=P.ownerOf(i)||qe(t.get("identity"));if(!n)return;const a=[];for(const e of s){const r=e.collections,s="string"==typeof r?r:r(i,n,t);s&&!a.includes(s)&&a.push(s)}ur(i,a,t);const o=P.sequenceName(i,"pk");t.setSequenceSegregation(o,t.isFullySegregated,a)}async function pr(t,e,r,i){const s=Array.isArray(e)?e:[e],n=Array.isArray(r)?r:[r];if(n.length!==s.length)throw new q("Segregated data keys and metadata length mismatch");const a=P.ownerOf(i)||qe(t.get("identity"));if(!a)throw new V("There's no assigned organization for model "+i.constructor.name);const o=s[0].collections,c="string"==typeof o?o:o(i,a,t);n.forEach((e,r)=>{const n="string"==typeof s[r].collections?s[r].collections:s[r].collections(i,a,t);if(n!==c)throw new A(`Segregated data collection mismatch: ${n} vs ${c}`)});const l=n.map(t=>t+"");t.writeTo(c,l)}async function mr(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new q("Segregated data keys and metadata length mismatch");const n=P.ownerOf(i)||qe(t.get("identity"));if(!n)throw new V("There's no assigned organization for model "+i.constructor.name);const a=s[0].collections,o="string"==typeof a?a:await a(i,n,t);t.readFrom(o)}async function yr(t,e,r,i,s){const n=Array.isArray(e)?e:[e],a=Array.isArray(r)?r:[r];if(a.length!==n.length)throw new q("Segregated data keys and metadata length mismatch");const o=P.ownerOf(i)||qe(t.get("identity"));if(!o)throw new V("There's no assigned organization for model "+i.constructor.name);const c=n[0].collections,l="string"==typeof c?c:c(i,o,t);a.forEach((e,r)=>{const s="string"==typeof n[r].collections?n[r].collections:n[r].collections(i,o,t);if(s!==l)throw new A(`Segregated data collection mismatch: ${s} vs ${l}`)});const d=a.map(t=>t+"");t.writeTo(l,d)}async function wr(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new q("Segregated data keys and metadata length mismatch");const n=P.ownerOf(i)||qe(t.get("identity"));if(!n)throw new V("There's no assigned organization for model "+i.constructor.name);const a=s[0].collections,o="string"==typeof a?a:a(i,n,t);t.readFrom(o)}function br(t,e,r){return(r,i)=>{const s=[];if(!i){const i=Nt.getAttributes(r);return i?.forEach(i=>{br(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(kt(),dt(),(r,i)=>{const s=Nt.key(e,i),n=r.constructor,a=Nt.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],Nt.set(n,s,a);const c=Nt.get(n,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],Nt.set(n,e,c);const d={...Nt.get(n,tt.TRANSIENT)||{},[i]:{}};Nt.set(n,tt.TRANSIENT,d)},ht(ut.ALL,fr,n,a),it(pr,{collections:t},{priority:95,group:i}),nt(mr,{collections:t},{priority:95,group:i}),st(yr,{collections:t},{priority:95,group:i}),at(wr,{collections:t},{priority:95,group:i}))}return Rt(...s)(r,i)}}function Ar(t=dr){return $t.for(me.PRIVATE).define({decorator:t=>br(t,me.PRIVATE),args:[t]}).apply()}function vr(t){return $t.for(me.SHARED).define({decorator:t=>br(t,me.SHARED),args:[t]}).apply()}function Cr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Cr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Cr(t[r]),e),{})}class Sr extends L{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=Nt.modelName(t.constructor)}catch(t){r=void 0}e[M.ANCHOR]=r||t.constructor.name;const i=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 P.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[M.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return P.build(e,r)}serialize(t){return require("json-stringify-deterministic")(Cr(this.preSerialize(t)))}}function Er(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Or(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 xr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new $e(`Addition overflow: ${t} + ${e}`);return r}function Nr(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new $e(`Subtraction overflow: ${t} - ${e}`);return r}function Tr(t){if(!/^\d+$/.test(t))throw new V(z("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new V(z("Failed to parse: {0}","string is not a parsable integer"));return e}class Ir extends L{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Cr(this.preSerialize(t,e)))}preSerialize(t,e=!0){const r=Object.assign({},t);let i;try{i=Nt.modelName(t.constructor)}catch(t){i=void 0}function s(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(s):this.preSerialize(t)}return e&&(r[M.ANCHOR]=i||t.constructor.name),P.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class $r extends v{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new q("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 c=await Ae.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new q(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await Ae.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await Ae.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,i.INITIALIZATION,!0)).for(this.initialize),[s]=t;if(!s)throw new q("Missing Fabric CA configuration");const{url:n,tls:a,caName:o}=s;e.info(`Initializing CA Client for CA ${s.caName} at ${s.url}`);const{trustedRoots:c,verify:l}=a,d=c[0];e.debug(`Retrieving CA certificate from ${d}. cwd: ${process.cwd()}`);const h=await Ae.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new Bt(n,{trustedRoots:Buffer.from(h),verify:l},o),g=await this.getUser(s,r);return e.debug("CA user loaded: "+g.getName()),{config:s,client:u}}async getCertificates(t,e=!0,...r){t instanceof d?(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,K.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 Fe(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new p(i);default:return new Fe(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,K.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 X(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new X(`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=Ie.fabricIdFromCertificate(s),c=Ie.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new be({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=$r.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=Vt.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=$r.identityFromEnrollment(d,this.config.caName,n);s.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=ve(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 X("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 q(`Could not revoke enrollment with id ${t}: ${e}`)}if(!n.success)throw new q(`Could not revoke enrollment with id ${t}: ${n.errors.join("\n")}`);return n}}var Rr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Rr||(Rr={}));const Dr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),Fr=new Pt("fabric-fs");async function kr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Br(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await f(import("fs"));return await e.readFile(t)})(t)}async function Pr(t,e,r,i){Fr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Vt(t),n=Vt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function _r(t,e){return{mspId:t,credentials:await kr(e,async t=>{const{promises:e}=await f(import("fs")),r=await jr(t);return await e.readFile(r)})}}async function jr(t){const{promises:e}=await f(import("fs")),{join:r}=await f(import("path"));return r(t,(await e.readdir(t))[0])}async function Lr(t){const{promises:e}=await f(import("fs")),{join:r}=await f(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function Mr(t){const e=await kr(t,async t=>{const{promises:e}=await f(import("fs")),r=await jr(t);return await e.readFile(r)}),r=await zr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Kt.newPrivateKeySigner(i)}async function zr(t){let e;if(_t())e=globalThis.crypto.subtle;else{const t=await f(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 q(t)}}function Ur(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 Hr extends C{constructor(t,e){super(t,e)}squash(t){const r=super.squash(t);if(!r)return r;const{method:i,params:s,args:n}=r,{direction:a,limit:o}=s;switch(i){case e.FIND:break;case e.PAGE:n.push(a,o);break;case e.FIND_BY:break;case e.LIST_BY:n.push(a);break;case e.PAGE_BY:n.push(a,o);break;case e.FIND_ONE_BY:break;default:throw new q("Unsupported method "+i)}return r}async executePrepared(...e){const r=t.forModel(this.fromSelector,this.adapter.alias),{method:i,args:s}=this.prepared;return r.statement(i,...s,...e)}async prepare(t){if(t=t||await this.adapter.context(i.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},n=[S.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(S.SELECT,this.selectSelector.join(` ${S.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(S.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),s.method=zt(n.join(" ")),s.params=r,this.prepared=s,this}processRecord(t,e,r,i){if(t[pt.ID]){const[,...e]=t[pt.ID].split(pt.SEPARATOR),s=e.join("_");return this.adapter.revert(t,this.fromSelector,l.parseValue(r,s),void 0,i)}return t}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),n=P.pk(this.fromSelector),a=Nt.get(this.fromSelector,Nt.key(tt.ID,n))?.type;return this.selectSelector?s:s.map(t=>this.processRecord(t,n,a,r))}build(){const t=this.log.for(this.build),e=this.buildAggregateQuery();if(e)return e;const r={};r[pt.TABLE]={},r[pt.TABLE]=P.tableName(this.fromSelector);const i={selector:r};if(this.selectSelector&&(i.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(E.and(this.whereCondition,E.attribute(pt.TABLE).eq(i.selector[pt.TABLE]))).selector,r=Object.keys(e);if(1===r.length&&-1!==Object.values(wt).indexOf(r[0]))switch(r[0]){case wt.AND:e[wt.AND]=[...Object.values(e[wt.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===wt.AND?t.push(...e[i]):t.push(e),t},[])],i.selector=e;break;case wt.OR:{const t={};t[wt.AND]=[e,...Object.entries(i.selector).map(([t,e])=>{const r={};return r[t]=e,r})],i.selector=t;break}default:throw Error("This should be impossible")}else Object.entries(e).forEach(([e,r])=>{i.selector[e]&&t.warn(`A ${e} query param is about to be overridden: ${i.selector[e]} by ${r}`),i.selector[e]=r})}if(this.orderBySelectors?.length){i.sort=i.sort||[],i.selector=i.selector||{};for(const[t,e]of this.orderBySelectors){const r=t,s={};s[r]=e,i.sort.push(s),i.selector[r]||(i.selector[r]={},i.selector[r][bt.BIGGER]=null)}}return this.limitSelector?i.limit=this.limitSelector:(t.warn("No limit selector defined. Using default couchdb limit of "+At),i.limit=At),this.offsetSelector&&(i.skip=this.offsetSelector),i}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===O.STARTS_WITH){if("string"!=typeof e)throw new x("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new x("STARTS_WITH requires a string comparison");const t={start:s=i,end:Ur(s)},r={};return r[e]={},r[e][bt.BIGGER_EQ]=t.start,r[e][bt.SMALLER]=t.end,{selector:r}}var s,n;if(r===O.ENDS_WITH){if("string"!=typeof e)throw new x("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new x("ENDS_WITH requires a string comparison");const t={};return t[e]={[bt.REGEXP]:(n=i,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===O.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new x("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][vt(O.BIGGER_EQ)]=r,n[t][vt(O.SMALLER_EQ)]=s,{selector:n}}let a={};if(-1===[N.AND,N.OR,O.NOT].indexOf(r))a[e]={},a[e][vt(r)]=i;else if(r===O.NOT)a=this.parseCondition(e).selector,a[vt(O.NOT)]={},a[vt(O.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})(vt(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 x("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 t=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),e=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[t,r]of e){const e=r?r+"":void 0,i=this.createAggregateDescriptor(t,e);if(i)return this.createAggregateQuery(i)}if(t)throw new x(`No CouchDB view metadata found for table ${P.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(t,e){if(!this.fromSelector)return;const r=Ct(this.fromSelector,t,e);if(!r.length)return;const i=r[0],s=P.tableName(this.fromSelector),n=St(s,i.attribute,t,i),a=i.ddoc||Et(s,n),o={reduce:void 0!==i.reduce||!i.returnDocs};return"distinct"!==t&&"groupBy"!==t||(o.group=!0),{kind:t,meta:i,descriptor:{ddoc:a,view:n,options:o}}}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 x("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 x("Average results should be handled before processing rows");const r=e.rows||[],i=t,s=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(t=>t.key??t.value):s.returnDocs?r.map(t=>t.value??t.doc??t):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(t){return"avg"!==t.kind}}class Kr extends s{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new A("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var Gr;class Yr extends T{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new ae}static{this.log=Lt.for(Yr)}constructor(t,e){super(Object.assign({},Dr,t),we,e),this.serializer=Yr.serializer}Statement(t){return new Hr(this,t)}Paginator(t,e,r){return new Kr(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(t,e,r,...i){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>P.tableName(t)):P.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let s=i.pop();void 0===s||s instanceof d||(i.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...i,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...n,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}const e=s.getOrUndefined("operation"),i=s.getOrUndefined("affectedTables");if(!e||e!==t||r&&r!==i){const t=(new this.Context).accumulate({...s.cache,...n,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(n)}return(new this.Context).accumulate({...n})}decode(t){return Yr.decoder.decode(t)}repository(){return re}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=P.tableName(t),a={};return a[pt.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=P.tableName(t);if(e.length!==r.length)throw new q("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.createAllPrefix),a=e.map((t,e)=>{const i={};return i[pt.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=P.tableName(t);if(e.length!==r.length)throw new q("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[pt.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new q("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=P.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=n&&Object.keys(n).length>0,d=l?{[c]:n}:{},h=await this.submitTransaction(o,gt.CREATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],d,this.getEndorsingOrganizations(o),t.name);if(this.shouldRefreshAfterWrite(o,l,e[0]))return this.readAll(t,e,o);try{return JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new W(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=P.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,gt.READ_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new W(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new q("Ids and models must have the same length");const s=[...i];let n=s.shift();const{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=P.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e),n=n&&(Array.isArray(n)?n:Object.keys(n)).length?{[c]:n}:{};const l=await this.submitTransaction(o,gt.UPDATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,this.getEndorsingOrganizations(o),t.name),d=n&&Object.keys(n).length>0;if(this.shouldRefreshAfterWrite(o,d,e[0]))return this.readAll(t,e,o);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new W(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s,ctxArgs:n}=this.logCtx(r,this.deleteAll),a=P.tableName(t),o=P.isTransient(t);let c;this.shouldRefreshAfterWrite(s,o,e[0])&&(c=await this.readAll(t,e,...n)),i.info(`deleting ${e.length} entries to ${a} table`),i.verbose("pks: "+e);const l=await this.submitTransaction(s,gt.DELETE_ALL,[JSON.stringify(e)],void 0,this.getEndorsingOrganizations(s),t.name);try{return o?c:JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new W(t)}}prepare(t,...e){const{log:r,ctx:s}=this.logCtx(e,this.prepare),n=P.segregate(t);t[i.METADATA]&&(r.silly("Passing along persistence metadata for "+t[i.METADATA]),Object.defineProperty(n.model,i.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[i.METADATA]}));const a=P.mirroredAt(t);if(a){const t=a.mspId;if(!t)throw new q("No mirror MSP could be found");const e=this.getEndorsingOrganizations(s)||[],r=[...new Set([...e,t])];s.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:n.model,model:n.model,id:t[P.pk(t.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(t,e,r){return!!e&&null!=r&&!t.getOrUndefined("mirror")}getEndorsingOrganizations(t){const e=t.getOrUndefined("endorsingOrgs")||t.getOrUndefined("endorsingOrgs");return e&&e.length?e:t.getFromChildren("endorsingOrgs")||t.getFromChildren("endorsingOrgs")}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=P.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=i&&Object.keys(i).length>0,d=l?{[c]:i}:{},h=await this.submitTransaction(o,K.CREATE,[this.serializer.serialize(r,t.name)],d,this.getEndorsingOrganizations(o),t.name),u=this.serializer.deserialize(this.decode(h));return this.shouldRefreshAfterWrite(o,l,e)?this.read(t,e,o):u}async healthcheck(t,...e){const{log:r,ctx:i}=this.logCtx(e,this.healthcheck),s=P.tableName(t);r.verbose(`reading entry from ${s} table`);const n=await this.evaluateTransaction(i,"healthcheck",[],void 0,void 0,t.name);return JSON.parse(this.decode(n))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.read),n=P.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,K.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=P.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[pt.TABLE]=s,Object.assign(a,r),[t,e,a,...n]}async update(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.update);a.info("CLIENT UPDATE class : "+typeof t);const c=P.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=i&&Object.keys(i).length>0,d=l?{[c]:i}:{},h=await this.submitTransaction(o,K.UPDATE,[this.serializer.serialize(r,t.name||t)],d,this.getEndorsingOrganizations(o),t.name),u=this.serializer.deserialize(this.decode(h));return this.shouldRefreshAfterWrite(o,l,e)?this.read(t,e,o):u}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=P.tableName(t),a=P.isTransient(t);let o;this.shouldRefreshAfterWrite(s,a,e)&&(o=await this.read(t,e,s)),i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const c=await this.submitTransaction(s,K.DELETE,[e.toString()],void 0,this.getEndorsingOrganizations(s),t.name);return a?o:this.serializer.deserialize(this.decode(c))}async raw(t,e=!0,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.raw),a=r.name;let o,c;s.info("Performing raw statement on table "+P.tableName(r));try{o=await this.evaluateTransaction(n,"raw",[JSON.stringify(t),e],void 0,void 0,a)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new W("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return P.isModel(t)?c.map(t=>P.build(t)):c}return l=c,P.isModel(l)?P.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 W("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=Yr.getClient(this.config)),this._client}async Gateway(t){return Yr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return Yr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s={},n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:Object.entries(s).reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}),endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,e,d)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(t){return!!t.getOrUndefined("legacy")&&!!t.getOrUndefined("allowGatewayOverride")}prepareLegacyArgs(t){return(t||[]).map(t=>"string"==typeof t?t:JSON.stringify(t))}buildLegacyTransient(t){if(!t)return;const e=Object.entries(t);if(!e.length)return;const r={};for(const[t,i]of e)r[t]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(){return[{peerEndpoint:this.config.peerEndpoint,tlsCert:this.config.tlsCert,peerHostAlias:this.config.peerHostAlias}]}async submitLegacyWithExplicitEndorsers(t,e,r,i,s,n){const a=this.log.for(this.submitLegacyWithExplicitEndorsers),o=await this.Gateway(t);try{const c=Yr.getContract(o,this.config,this.getContractName(n));a.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${e}`),a.debug("Explicit peers: "+s.map(t=>t.peerEndpoint));const l=new Set;this.config.mspId&&l.add(this.config.mspId),(this.getEndorsingOrganizations(t)||[]).forEach(t=>l.add(t));const d={arguments:r,transientData:i,endorsingOrganizations:l.size>0?Array.from(l):void 0},h=c.newProposal(e,d),u=await h.endorse(),g=await u.submit(),f=await g.getStatus();if(!f.successful)throw Error(`Legacy endorsement failed for ${u.getTransactionId()}: ${f.code}`);return u.getResult()}catch(t){throw this.parseError(t)}finally{o.close()}}parseError(t){return Yr.parseError(t)}async submitTransaction(t,e,r,i,s,n){if(this.shouldUseLegacyGateway(t)){const s=this.prepareLegacyArgs(r),a=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs();return this.submitLegacyWithExplicitEndorsers(t,e,s,a,o,n)}return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=Lt.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(ee.readFileSync(r,"utf8"))}catch(t){throw new q(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Zt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new te(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=Lt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await _r(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+Ie.fabricIdFromCertificate(s.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let n;if(e.hsm)throw new A("HSM NOT IMPLEMENTED");n=await Mr(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=Gt(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new Yr._baseDispatch}static parseError(t){let e="string"==typeof t?t:t.message;return t instanceof Yt&&t.details.length&&10===t.code&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new Le(t):e.includes("DEADLINE_EXCEEDED")?new He(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new ze(t):e.includes("PHANTOM_READ_CONFLICT")?new Me(t):t instanceof Error&&t.code&&9===t.code?new je(t):e.includes(V.name)?new V(t):e.includes(X.name)?new X(t):e.includes(Q.name)?new Q(t):e.includes(ft.name)?new ft(t):e.includes(x.name)?new x(t):e.includes(I.name)?new I(t):e.includes(A.name)?new A(t):e.includes($.name)?new $(t):e.includes(R.name)?new R(t):e.includes(p.name)?new p(t):e.includes(F.name)?new F(t):e.includes(k.name)?new k(t):e.includes(W.name)?new W(t):new q(t)}}Ot([Ut(),Ht(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,Object,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"create",null),Ot([Ut(),Ht(),xt("design:type",Function),xt("design:paramtypes",[Object,d]),xt("design:returntype",Promise)],Yr.prototype,"healthcheck",null),Ot([Ut(),Ht(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"read",null),Ot([Ut(),Ht(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,Object,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"update",null),Ot([Ut(),Ht(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"delete",null),Ot([Ut(),xt("design:type",Function),xt("design:paramtypes",[Object,"function"==typeof(Gr="undefined"!=typeof D&&D)?Gr:Object,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"raw",null),Ot([Ut(),xt("design:type",Function),xt("design:paramtypes",[String,String,Object,d]),xt("design:returntype",Promise)],Yr.prototype,"view",null),Yr.decoration(),T.setCurrent(we);class Vr extends B{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof Yr))throw new A("Only FabricClientAdapter can be observed by dispatch");return super.observe(t),()=>this.unObserve(t)}async updateObservers(t,e,r,...i){const{log:s,ctxArgs:n}=T.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new q("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:P.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new q('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new q("No adapter found. should be impossible");const e=t||await this.adapter.context(K.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||P),r=this.log.for(this.handleEvents);r.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const t of this.listeningStack){const{table:i,event:s,owner:n}=Or(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?P.get(i):P.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(t,s,a.id,e)}catch(t){r.error(`Failed update observables for table ${i} event ${s} id: ${a.id}: ${t}`)}}}catch(t){r.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new q("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},P),{ctx:e}=this.logCtx([t],this.initialize),r=(await Yr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new q("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}Yr&&(Yr._baseDispatch=Vr);const Wr="##VERSION##",qr="##PACKAGE##";Nt.registerLibrary(qr,Wr);export{De as AllowanceError,Se as BASE_ALPHABET,Re as BalanceError,Te as BaseEncoder,Rr as CA_ROLE,Ee as CRYPTO,ae as ClientSerializer,Ae as CoreUtils,Ie as CryptoUtils,Dr as DefaultFabricClientFlags,Sr as DeterministicSerializer,Ne as ERC20Events,je as EndorsementError,ze as EndorsementPolicyError,Ve as FabricBaseModel,Yr as FabricClientAdapter,Vr as FabricClientDispatch,re as FabricClientRepository,oe as FabricERC20ClientRepository,Ge as FabricEnrollmentService,we as FabricFlavour,We as FabricIdentifiedBaseModel,$r as FabricIdentityService,me as FabricModelKeys,xe as HFCAIdentityAttributes,Oe as HFCAIdentityType,be as Identity,pe as IdentityCredentials,ye as IdentityType,dr as ImplicitPrivateCollection,ke as MissingContextError,_e as MissingPKCSS11Lib,cr as ModelCollection,Le as MvccReadConflictError,lr as NamespaceCollection,Pe as NotInitializedError,$e as OverflowError,Je as Owner,qr as PACKAGE_NAME,Me as PhantomReadConflictError,Fe as RegistrationError,Ye as RegistrationRequestBuilder,hr as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,Ir as SimpleDeterministicSerializer,Ke as TransactionBufferSizeError,Ue as TransactionLimitsError,He as TransactionTimeoutError,Be as UnauthorizedPrivateDataAccess,Wr as VERSION,xr as add,gr as applyMirrorFlags,ur as applySegregationFlags,kr as contentOfLoadFile,rr as createMirrorHandler,sr as deleteMirrorHandler,er as evalMirrorMetadata,qe as extractMspId,zr as extractPrivateKey,fr as extractSegregatedCollections,Er as generateFabricEventName,de as generateModelDesignDocs,le as generateModelIndexes,ve as getAkiAndSerialFromCert,Pr as getCAUser,jr as getFirstDirFileName,Lr as getFirstDirFileNameContent,_r as getIdentity,Mr as getSigner,or as mirror,nr as mirrorWriteGuard,Xe as ownedBy,Qe as ownedByOnCreate,Or as parseEventName,Ar as privateData,Br as readFile,ar as readMirrorHandler,he as readModelFile,ue as readModelFolders,Tr as safeParseInt,pr as segregatedDataOnCreate,wr as segregatedDataOnDelete,mr as segregatedDataOnRead,yr as segregatedDataOnUpdate,vr as sharedData,Cr as sortKeysOnlyRecursive,Nr as sub,tr as transactionId,Ze as transactionIdOnCreate,ir as updateMirrorHandler,fe as writeDesignDocs,ge as writeIndexes};
|
|
1
|
+
import{Model as t,required as e,model as r,JSONSerializer as i,ModelKeys as s,stringFormat as n,minlength as a,min as o}from"@decaf-ts/decorator-validation";import{InternalError as c,OperationKeys as l,enforceDBDecorators as d,reduceErrorsToPrint as h,ValidationError as u,SerializationError as g,composeAttributeValue as f,BaseError as p,ConflictError as m,NotFoundError as y,version as w,DBKeys as b,generated as A,readonly as v,onCreate as C,onUpdate as S,onRead as E,onDelete as O,afterCreate as x,afterUpdate as N,afterDelete as T,transient as I,on as R,DBOperations as $,BulkCrudOperationKeys as F,BadRequestError as k}from"@decaf-ts/db-decorators";import{generateIndexes as P,generateViews as B,CouchDBKeys as _,CouchDBGroupOperator as j,CouchDBOperator as L,CouchDBQueryLimit as M,translateOperators as z,findViewMetadata as U,generateViewName as H,generateDesignDocName as K}from"@decaf-ts/for-couchdb";import{Repository as G,PreparedStatementKeys as q,OrderDirection as Y,PersistenceKeys as V,Paginator as W,pk as J,column as Q,table as X,BaseModel as Z,Sequence as tt,Context as et,oneToOne as rt,Cascade as it,index as st,normalizeImport as nt,AuthorizationError as at,createdAt as ot,updatedAt as ct,createdBy as lt,updatedBy as dt,UnsupportedError as ht,ClientBasedService as ut,Statement as gt,QueryClause as ft,Condition as pt,Operator as mt,QueryError as yt,GroupOperator as wt,Adapter as bt,PagingError as At,MigrationError as vt,ObserverError as Ct,ForbiddenError as St,ConnectionError as Et,Dispatch as Ot}from"@decaf-ts/core";import{__decorate as xt,__metadata as Nt}from"tslib";import{Metadata as Tt,description as It,uses as Rt,Decoration as $t,apply as Ft,propMetadata as Dt,metadata as kt,prop as Pt}from"@decaf-ts/decoration";import Bt from"fabric-ca-client";import{MiniLogger as _t,isBrowser as jt,LoggedClass as Lt,Logging as Mt,toPascalCase as zt,toCamelCase as Ut,debug as Ht,final as Kt}from"@decaf-ts/logging";import{signers as Gt,connect as qt,GatewayError as Yt}from"@hyperledger/fabric-gateway";import{User as Vt}from"fabric-common";import Wt,{X509Certificate as Jt}from"crypto";import*as Qt from"@peculiar/x509";import{X509Certificate as Xt}from"@peculiar/x509";import{Crypto as Zt}from"@peculiar/webcrypto";import*as te from"@grpc/grpc-js";import{Client as ee}from"@grpc/grpc-js";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(t){return P([t])}function ne(t,e){const r=B([t]),i=e||{};return r.forEach(t=>{i[t._id]=t}),r}function ae(e){const r=require("path"),i=require(r.join(process.cwd(),e.parentPath,e.name));return Object.values(i).filter(e=>{try{return new e instanceof t}catch(e){return!1}})}async function oe(...t){const e=require("fs"),r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...ae(e))}return r}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){return de(e,`OR('${t}.member')`,r,i,s,n,a)}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;return{privates:r.map(t=>n.filter(r=>!h||("string"==typeof h.resolver?h.resolver:h.resolver(e,t))===r&&(!h.condition||h.condition(t))).map(e=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:s,memberOnlyRead:n}=l;return he(t,e,r,i,s,n,!1)})).flat(),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 G{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(t){return super.override(Object.assign({},t,this._overrides)).for(t)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,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);return s.verbose(`listing ${t.tableName(this.class)} by ${e} ${r}`),await this.statement(this.listBy.name,e,r,...n)}async findBy(e,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,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=Y.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=Y.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,V.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,V.STATEMENT,[e,JSON.stringify(a)],void 0,void 0,this.class.name)));return Array.isArray(o)?o.map(e=>e[_.TABLE]&&e[_.TABLE]===t.tableName(this.class)?new this.class(e):e):o[_.TABLE]&&o[_.TABLE]===t.tableName(this.class)?new this.class(o):W.isSerializedPage(o)?Object.assign(o,{data:o.data.map(t=>new this.class(t))}):o}async countOf(e,...r){const{log:i,ctxArgs:s}=(await this.logCtx(r,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,l.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await d(this,r,t,l.CREATE,l.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=h(i);if(s)throw new u(s)}return[t,...i]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=a.map(t=>t.record),l=a.map(t=>t.transient),d=await this.adapter.createAll(this.class,o,c,l,...n);return Promise.all(d.map(async(t,e)=>{const r=o[e];if(this.shouldRefreshAfterWrite(a[e],i)&&null!=r){const t=await this.adapter.read(this.class,r,i);return this.adapter.revert(t,this.class,r,i.get("rebuildWithTransient")?a[e].transient:void 0,i)}return this.adapter.revert(t,this.class,r,l[e],i)}))}async updateAll(e,...r){const{ctx:i,log:s,ctxArgs:n}=this.logCtx(r,this.updateAll);s.debug(`Updating ${e.length} new ${this.class.name} in table ${t.tableName(this.class)}`),e.forEach(t=>this.ensureLegacyMirrorFlag(i,t));const a=e.map(t=>this.adapter.prepare(t,i)),o=a.map(t=>t.id),c=await this.adapter.updateAll(this.class,o,a.map(t=>t.record),a.map(t=>t.transient),...n);return Promise.all(c.map(async(t,e)=>{const r=o[e];if(this.shouldRefreshAfterWrite(a[e],i)&&null!=r){const t=await this.adapter.read(this.class,r,i);return this.adapter.revert(t,this.class,r,i.get("rebuildWithTransient")?a[e].transient:void 0,i)}return this.adapter.revert(t,this.class,r,a[e].transient,i)}))}shouldRefreshAfterWrite(t,e){const r=t.privates&&Object.keys(t.privates).length>0,i=t.shared&&Object.keys(t.shared).length>0;return r||i||!!e.getOrUndefined("segregated")||!!e.getOrUndefined("mirror")}ensureLegacyMirrorFlag(e,r){t.mirroredAt(r)&&e.accumulate({legacy:!0})}}let ye=class extends Z{constructor(t){super(t)}};xt([J({type:String}),Nt("design:type",String)],ye.prototype,"name",void 0),xt([Q(),e(),Nt("design:type",String)],ye.prototype,"owner",void 0),xt([Q(),e(),Nt("design:type",String)],ye.prototype,"symbol",void 0),xt([Q(),e(),Nt("design:type",Number)],ye.prototype,"decimals",void 0),ye=xt([X("erc20_tokens"),r(),Nt("design:paramtypes",[Object])],ye);let we=class extends Z{constructor(t){super(t)}};xt([J({type:String}),Nt("design:type",String)],we.prototype,"id",void 0),xt([Q(),e(),Nt("design:type",String)],we.prototype,"token",void 0),xt([Q(),e(),Nt("design:type",Number)],we.prototype,"balance",void 0),xt([Q(),Nt("design:type",String)],we.prototype,"captive",void 0),we=xt([X("erc20_wallets"),r(),Nt("design:paramtypes",[Object])],we);let be=class extends Z{constructor(t){super(t)}};xt([J({type:String}),Q(),e(),Nt("design:type",String)],be.prototype,"owner",void 0),xt([Q(),e(),Nt("design:type",String)],be.prototype,"spender",void 0),xt([Q(),e(),Nt("design:type",Number)],be.prototype,"value",void 0),be=xt([X("erc20_allowances"),r(),Nt("design:paramtypes",[Object])],be);class Ae extends i{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=Tt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new g("Could not find metadata for "+t.constructor.name);i=e}return r[s.ANCHOR]=i,r}deserialize(e){const r=JSON.parse(e),i=r[s.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.build(r,i)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class ve extends me{static{this.serializer=new Ae}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=>tt.parseValue(t.sequenceFor(e).type,r)):tt.parseValue(t.sequenceFor(e).type,i),await this.observerHandler.updateObservers(e,r,o,...a)}decode(t){return ve.decoder.decode(t)}constructor(t){super(t,we),this.serializer=ve.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 et.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 et.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 et.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 et.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[ve.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await et.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 et.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 et.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 et.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 et.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 et.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 Ce(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 f(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 Se=class extends Z{constructor(t){super(t)}};var Ee,Oe;xt([It("Unique identifier of the credentials record"),Q(),J(),Nt("design:type",String)],Se.prototype,"id",void 0),xt([It("PEM-encoded X.509 certificate for the identity"),Q(),e(),Nt("design:type",String)],Se.prototype,"certificate",void 0),xt([It("PEM-encoded root or intermediate certificate"),Q(),e(),Nt("design:type",String)],Se.prototype,"rootCertificate",void 0),xt([It("PEM-encoded private key"),Q(),e(),Nt("design:type",String)],Se.prototype,"privateKey",void 0),Se=xt([r(),Nt("design:paramtypes",[Object])],Se),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(Ee||(Ee={})),(t=>{t.X509="X.509"})(Oe||(Oe={}));const xe="hlf-fabric";let Ne=class extends Z{constructor(t){super(t),this.type=Oe.X509}};xt([It("Unique identifier of the identity"),J(),Nt("design:type",String)],Ne.prototype,"id",void 0),xt([rt(Se,{update:it.CASCADE,delete:it.CASCADE}),Nt("design:type",Se)],Ne.prototype,"credentials",void 0),xt([Q(),e(),st(),Nt("design:type",String)],Ne.prototype,"mspId",void 0),xt([Q(),e(),Nt("design:type",String)],Ne.prototype,"type",void 0),Ne=xt([r(),Nt("design:paramtypes",[Object])],Ne);class Te{static{this.logger=new _t(Te.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,s){this.logger.debug(n("Creating CA {0} user {1} with certificate {2}",i,t,r));const a=new Vt(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?(Te.cryptoSuite||(Te.cryptoSuite=Vt.newCryptoSuite(t)),Te.cryptoSuite):Vt.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 Jt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Wt.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 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 Gt.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 Ie(t){const e=new Xt(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 Re=new Zt;var $e,Fe,De,ke,Pe;Qt.cryptoProvider.set(Re),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})($e||($e={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(Fe||(Fe={}));class Be{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 _e{static{this.b58encoder=new Be($e.BASE58)}static{this.logger=new _t(_e.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(n("Parsing certificate: {0}",t));const e=new Qt.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=Re.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 Re.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 Qt.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,Re.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Qt.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 jt()?globalThis.window.crypto.subtle:Re.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=Re.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Fe.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:Fe.KEY_ALGORYTHM,hash:Fe.HASH,salt:i,iterations:Fe.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Fe.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:Fe.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Fe.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Fe.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class je extends c{constructor(t){super(t,je.name)}}class Le extends c{constructor(t){super(t,Le.name)}}class Me extends c{constructor(t){super(t,Me.name)}}class ze extends at{constructor(t){super(t,ze.name)}}class Ue extends c{constructor(t){super(t,Ue.name,500)}}class He extends p{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(He.name,t,403)}}class Ke extends p{constructor(t){super(Ke.name,t,409)}}class Ge extends c{constructor(t){super(t,Ge.name,500)}}class qe extends c{constructor(t){super(t,qe.name,500)}}class Ye extends c{constructor(t){super(t,Ye.name,500)}}class Ve extends c{constructor(t){super(t,Ve.name,500)}}class We extends c{constructor(t){super(t,We.name,500)}}class Je extends c{constructor(t,e=Je.name,r=590){super(t,e,r)}}class Qe extends c{constructor(t){super(t,Qe.name,591)}}class Xe extends c{constructor(t){super(t,Xe.name,592)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(De||(De={})),(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"})(ke||(ke={}));class Ze extends Lt{constructor(t){Te.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 Te.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 Te.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await Te.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 Te.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Bt(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 ze(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new at(i);default:return new ze(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=Mt.for(Ze,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=_e.fabricIdFromCertificate(r),o=_e.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new Ne({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=Ze.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 tr extends t{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new u(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}xt([e(),Nt("design:type",String)],tr.prototype,"affiliation",void 0),xt([a(1),Nt("design:type",Array)],tr.prototype,"attrs",void 0),xt([e(),Nt("design:type",String)],tr.prototype,"enrollmentID",void 0),xt([e(),Nt("design:type",String)],tr.prototype,"enrollmentSecret",void 0),xt([o(0),Nt("design:type",Number)],tr.prototype,"maxEnrollments",void 0),xt([e(),Nt("design:type",String)],tr.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Pe||(Pe={}));let er=class extends t{constructor(t){super(t)}};xt([It("Stores the original timestamp of creation"),Q(),ot(),Nt("design:type",Date)],er.prototype,"createdAt",void 0),xt([It("Stores the timestamp of the last update"),Q(),ct(),Nt("design:type",Date)],er.prototype,"updatedAt",void 0),xt([It("Stores the version of the model"),Q(),w(),Nt("design:type",Number)],er.prototype,"version",void 0),er=xt([Rt(xe),Nt("design:paramtypes",[Object])],er);let rr=class extends er{constructor(t){super(t)}};function ir(t){if(t)return"string"==typeof t?t:t.getMSPID()}function sr(){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 at(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function nr(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function ar(){return $t.for(Ee.OWNED_BY).define({decorator:()=>(t,r)=>Ft(e(),A(),v(),C(nr),Dt(Tt.key(Ee.FABRIC,Ee.OWNED_BY),r))(t,r),args:[]}).apply()}async function or(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function cr(){return $t.for(Ee.TRANSACTION_ID).define({decorator:()=>(t,r)=>Ft(e(),v(),C(or),S(or),Dt(Tt.key(Ee.FABRIC,r,Ee.TRANSACTION_ID),r))(t,r),args:[]}).apply()}async function lr(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 dr(e,r,i,s){const n=await lr(s,r.resolver,e),a=e;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(s,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 hr(e,r,i,s){const n=await lr(s,r.resolver,e),a=e;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(s,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 ur(e,r,i,s){const n=await lr(s,r.resolver,e),a=e;a.put("mirror",!0),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("segregated",void 0)}}async function gr(t,e,r,i){const s=ir(t.get("identity"));if(s&&(s===e.mspId||e.condition&&e.condition(s)))throw new at(`Organization ${s} is not authorized to modify mirrored data`)}async function fr(t,e,r,i){const s=ir(t.get("identity"));if(!s)return;const n=await lr(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("fullySegregated",!0),a.readFrom(n))}function pr(t,e,r){const i="string"!=typeof e&&!!e,s=i?void 0:e,n=i?e:r;return $t.for(Ee.MIRROR).define({decorator:(t,e,r)=>{const i={condition:r,mspId:e,resolver:t};return Ft(kt(Tt.key(Ee.FABRIC,Ee.MIRROR),i),E(fr,i,{priority:30}),C(gr,i,{priority:20}),S(gr,i,{priority:20}),O(gr,i,{priority:20}),x(dr,i,{priority:95}),N(hr,i,{priority:95}),T(ur,i,{priority:95}))},args:[t,s,n]}).apply()}xt([It("Stores the creator"),Q(),lt(),Nt("design:type",String)],rr.prototype,"createdBy",void 0),xt([It("Stores the user that last updated the model"),Q(),dt(),Nt("design:type",String)],rr.prototype,"updatedBy",void 0),rr=xt([Rt(xe),Nt("design:paramtypes",[Object])],rr),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=Tt.getAttributes(e.constructor)||[],i=Tt.get(e.constructor,b.TRANSIENT),s=Tt.get(e.constructor,Ee.PRIVATE),n=Tt.get(e.constructor,Ee.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=>!!Tt.get("function"!=typeof t?t.constructor:t,Ee.PRIVATE)).bind(t),t.isShared=(t=>!!Tt.get("function"!=typeof t?t.constructor:t,Ee.SHARED)).bind(t),t.mirrored=(t=>Tt.get("function"!=typeof t?t.constructor:t,Tt.key(Ee.FABRIC,Ee.MIRROR))).bind(t),t.ownerOf=(t=>{const e=Tt.get(t.constructor,Tt.key(Ee.FABRIC,Ee.OWNED_BY));if(e)return t[e]}).bind(t),t.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Tt.get(t,Tt.key(Ee.FABRIC,Ee.MIRROR)))).bind(t),t.collectionsFor=(t=>{const e=[Ee.PRIVATE],r=[Ee.SHARED],i=Tt.key(...e),s=Tt.key(...r),n="function"==typeof t?t:t.constructor,a=Tt.get(n,i),o=Tt.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(t);const mr=(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`${zt(s.name)}${i?zt(i):""}`};function yr(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?zt(s):""}`}}const wr=(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`__${zt(i)}PrivateCollection`},br=35;function Ar(e,r,i){r.length>0&&i.readFrom(r),!i.isFullySegregated&&r.length&&((e=>{const r=Tt.getAttributes(e)||[],i=t.pk(e),s=Tt.get(e,b.TRANSIENT)||{},n=Tt.get(e,Tt.key(Ee.PRIVATE))||{},a=Tt.get(e,Tt.key(Ee.SHARED))||{};return r.some(t=>t!==i&&!(t in s)&&!(t in n)&&!(t in a))})(e.constructor)||i.markFullySegregated())}async function vr(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 lr(new e,s.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.readFrom(n)}async function Cr(e,r,i,s){const n=Array.isArray(r)?r:[r],a=t.ownerOf(s)||ir(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)}Ar(s,o,e);const c=t.sequenceName(s,"pk");e.setSequenceSegregation(c,e.isFullySegregated,o)}async function Sr(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)||ir(e.get("identity"));if(!o)throw new u("There's no assigned organization for model "+s.constructor.name);const l=n[0].collections,d="string"==typeof l?l:l(s,o,e);a.forEach((t,r)=>{const i="string"==typeof n[r].collections?n[r].collections:n[r].collections(s,o,e);if(i!==d)throw new ht(`Segregated data collection mismatch: ${i} vs ${d}`)});const h=a.map(t=>t+"");e.writeTo(d,h)}async function Er(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||ir(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:await o(s,a,e);e.readFrom(l)}async function Or(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)||ir(e.get("identity"));if(!l)throw new u("There's no assigned organization for model "+s.constructor.name);const d=a[0].collections,h="string"==typeof d?d:d(s,l,e);o.forEach((t,r)=>{const i="string"==typeof a[r].collections?a[r].collections:a[r].collections(s,l,e);if(i!==h)throw new ht(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=o.map(t=>t+"");e.writeTo(h,g)}async function xr(e,r,i,s){const n=Array.isArray(r)?r:[r];if((Array.isArray(i)?i:[i]).length!==n.length)throw new c("Segregated data keys and metadata length mismatch");const a=t.ownerOf(s)||ir(e.get("identity"));if(!a)throw new u("There's no assigned organization for model "+s.constructor.name);const o=n[0].collections,l="string"==typeof o?o:o(s,a,e);e.readFrom(l)}function Nr(t,e,r){return(r,i)=>{const s=[];if(!i){const i=Tt.getAttributes(r);return i?.forEach(i=>{Nr(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(Pt(),I(),(r,i)=>{const s=Tt.key(e,i),n=r.constructor,a=Tt.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],Tt.set(n,s,a);const c=Tt.get(n,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],Tt.set(n,e,c);const d={...Tt.get(n,b.TRANSIENT)||{},[i]:{}};Tt.set(n,b.TRANSIENT,d)},R($.ALL,Cr,n,a),C(Sr,{collections:t},{priority:95,group:i}),E(Er,{collections:t},{priority:95,group:i}),S(Or,{collections:t},{priority:95,group:i}),O(xr,{collections:t},{priority:95,group:i}))}return Ft(...s)(r,i)}}function Tr(t=wr){return $t.for(Ee.PRIVATE).define({decorator:t=>Nr(t,Ee.PRIVATE),args:[t]}).apply()}function Ir(t){return $t.for(Ee.SHARED).define({decorator:t=>Nr(t,Ee.SHARED),args:[t]}).apply()}function Rr(t){return null===t||"object"!=typeof t?t:Array.isArray(t)?t.map(Rr):t.constructor!==Object?t:Object.keys(t).sort().reduce((e,r)=>(e[r]=Rr(t[r]),e),{})}class $r extends i{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=Tt.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")(Rr(this.preSerialize(t)))}}function Fr(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Dr(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 kr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new je(`Addition overflow: ${t} + ${e}`);return r}function Pr(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new je(`Subtraction overflow: ${t} - ${e}`);return r}function Br(t){if(!/^\d+$/.test(t))throw new u(n("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new u(n("Failed to parse: {0}","string is not a parsable integer"));return e}class _r extends i{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(Rr(this.preSerialize(t,e)))}preSerialize(e,r=!0){const i=Object.assign({},e);let n;try{n=Tt.modelName(e.constructor)}catch(t){n=void 0}function a(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(a):this.preSerialize(t)}return r&&(i[s.ANCHOR]=n||e.constructor.name),t.relations(e).forEach(t=>{i[t]=a.call(this,i[t])}),i}}class jr extends ut{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 Te.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 Te.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await Te.getCAUser("admin",d,l,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=(await this.logCtx(t,V.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 Te.getFileContent(d);e.debug("CA Certificate: "+h.toString());const u=new Bt(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 et?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=(await this.logCtx(r,l.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new ze(t);const[,r,i]=e;switch(r){case"74":case"71":return new m(i);case"20":return new at(i);default:return new ze(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,l.READ,!0)).for(this.read);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new y(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new y(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=(await this.logCtx(a,"register",!0)).for(this.register);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=_e.fabricIdFromCertificate(s),c=_e.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new Ne({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=jr.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=(await this.logCtx(a,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async updateIdentity(t,e,r,...i){const{log:s,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{s.info("Renewing identity for "+t);const a=this.client.newIdentityService(),o=await a.getOne(t,this.user);await a.update(t,r,this.user);const c=Vt.createUser(t,"",this.user.getMspid(),e.certificate,e.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(o.result.attrs||[]).map(({name:t})=>({name:t,optional:!1})),d=await this.client.reenroll(c,l),h=jr.identityFromEnrollment(d,this.config.caName,n);s.debug("Revoking previous certificates for "+t);const{aki:u,serial:g}=Ie(e.certificate);return await this.revoke(t,{aki:u,serial:g},i),s.debug("Renew identity successful for "+t),h}catch(t){throw this.parseError(t)}}async revoke(t,e,...r){const{log:i}=(await this.logCtx(r,"revoke",!0)).for(this.revoke);i.verbose("Revoking identity with enrollment ID "+t);const s=await this.read(t);if(!s)throw new y("Could not find enrollment with id "+t);let n;try{const t={reason:e.serial||e.aki?"Revoke User Certificate":"User Deletion",...e,enrollmentID:s.id};n=await this.client.revoke(t,this.user)}catch(e){throw new c(`Could not revoke enrollment with id ${t}: ${e}`)}if(!n.success)throw new c(`Could not revoke enrollment with id ${t}: ${n.errors.join("\n")}`);return n}}var Lr;(t=>{t.ADMIN="admin",t.USER="user",t.CLIENT="client"})(Lr||(Lr={}));const Mr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,rebuildWithTransient:!0,encryptTransient:!1}),zr=new _t("fabric-fs");async function Ur(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Hr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await nt(import("fs"));return await e.readFile(t)})(t)}async function Kr(t,e,r,i){zr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Vt(t),n=Vt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Gr(t,e){return{mspId:t,credentials:await Ur(e,async t=>{const{promises:e}=await nt(import("fs")),r=await qr(t);return await e.readFile(r)})}}async function qr(t){const{promises:e}=await nt(import("fs")),{join:r}=await nt(import("path"));return r(t,(await e.readdir(t))[0])}async function Yr(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 Vr(t){const e=await Ur(t,async t=>{const{promises:e}=await nt(import("fs")),r=await qr(t);return await e.readFile(r)}),r=await Wr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Gt.newPrivateKeySigner(i)}async function Wr(t){let e;if(jt())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)}}function Jr(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 Qr extends gt{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=G.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(V.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},i={class:this.fromSelector,args:e,params:r},s=[ft.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(ft.SELECT,this.selectSelector.join(` ${ft.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(s.push(ft.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),i.method=Ut(s.join(" ")),i.params=r,this.prepared=i,this}processRecord(t,e,r,i){if(t[_.ID]){const[,...e]=t[_.ID].split(_.SEPARATOR),s=e.join("_");return this.adapter.revert(t,this.fromSelector,tt.parseValue(r,s),void 0,i)}return t}async raw(e,...r){const{ctx:i}=this.logCtx(r,this.raw),s=e?.aggregateInfo;if(e?.aggregate&&s)return this.executeAggregate(s,i);const n=await this.adapter.raw(e,!0,this.fromSelector,i),a=t.pk(this.fromSelector),o=Tt.get(this.fromSelector,Tt.key(b.ID,a))?.type;return this.selectSelector?n:n.map(t=>this.processRecord(t,a,o,i))}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const i={};i[_.TABLE]={},i[_.TABLE]=t.tableName(this.fromSelector);const s={selector:i};if(this.selectSelector&&(s.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(pt.and(this.whereCondition,pt.attribute(_.TABLE).eq(s.selector[_.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(j).indexOf(r[0]))switch(r[0]){case j.AND:t[j.AND]=[...Object.values(t[j.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===j.AND?t.push(...e[i]):t.push(e),t},[])],s.selector=t;break;case j.OR:{const e={};e[j.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 "+M),s.limit=M),this.offsetSelector&&(s.skip=this.offsetSelector),s}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===mt.STARTS_WITH){if("string"!=typeof e)throw new yt("STARTS_WITH requires an attribute name");if("string"!=typeof i)throw new yt("STARTS_WITH requires a string comparison");const t={start:s=i,end:Jr(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===mt.ENDS_WITH){if("string"!=typeof e)throw new yt("ENDS_WITH requires an attribute name");if("string"!=typeof i)throw new yt("ENDS_WITH requires a string comparison");const t={};return t[e]={[L.REGEXP]:(n=i,n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:t}}if(r===mt.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new yt("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][z(mt.BIGGER_EQ)]=r,n[t][z(mt.SMALLER_EQ)]=s,{selector:n}}let a={};if(-1===[wt.AND,wt.OR,mt.NOT].indexOf(r))a[e]={},a[e][z(r)]=i;else if(r===mt.NOT)a=this.parseCondition(e).selector,a[z(mt.NOT)]={},a[z(mt.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})(z(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 yt("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 yt(`No CouchDB view metadata found for table ${t.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const i=U(this.fromSelector,e,r);if(!i.length)return;const s=i[0],n=t.tableName(this.fromSelector),a=H(n,s.attribute,e,s),o=s.ddoc||K(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 yt("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 yt("Average results should be handled before processing rows");const r=e.rows||[],i=t,s=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(t=>t.key??t.value):s.returnDocs?r.map(t=>t.value??t.doc??t):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(t){return"avg"!==t.kind}}class Xr extends W{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new ht("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var Zr;class ti extends bt{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Ae}static{this.log=Mt.for(ti)}constructor(t,e){super(Object.assign({},Mr,t),xe,e),this.serializer=ti.serializer}Statement(t){return new Qr(this,t)}Paginator(t,e,r){return new Xr(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 et||(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 ti.decoder.decode(t)}repository(){return me}createPrefix(e,r,i,...s){const{ctxArgs:n}=this.logCtx(s,this.createPrefix),a=t.tableName(e),o={};return o[_.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[_.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[_.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?{[d]:a}:{},f=await this.submitTransaction(l,F.CREATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],u,this.getEndorsingOrganizations(l),e.name);let p;try{p=JSON.parse(this.decode(f)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,h,p[0][t.pk(e)]||r[0])?this.readAll(e,r,l):p}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,F.READ_ALL,[JSON.stringify(r)],void 0,void 0,e.name);try{return JSON.parse(this.decode(o)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}async updateAll(e,r,i,...s){if(r.length!==i.length)throw new c("Ids and models must have the same length");const n=[...s];let a=n.shift();const{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),a=a&&(Array.isArray(a)?a:Object.keys(a)).length?{[d]:a}:{};const h=await this.submitTransaction(l,F.UPDATE_ALL,[JSON.stringify(i.map(t=>this.serializer.serialize(t,e.name)))],a,this.getEndorsingOrganizations(l),e.name),u=a&&Object.keys(a).length>0;let f;try{f=JSON.parse(this.decode(h)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}return this.shouldRefreshAfterWrite(e,l,u,r[0])?this.readAll(e,Ce(e,f,r),l):f}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);let l;this.shouldRefreshAfterWrite(e,n,c,r[0])&&(l=await this.readAll(e,r,...a)),s.info(`deleting ${r.length} entries to ${o} table`),s.verbose("pks: "+r);const d=await this.submitTransaction(n,F.DELETE_ALL,[JSON.stringify(r)],void 0,this.getEndorsingOrganizations(n),e.name);try{return c?l:JSON.parse(this.decode(d)).map(t=>JSON.parse(t))}catch(t){throw new g(t)}}prepare(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.prepare),n=t.segregate(e);e[V.METADATA]&&(i.silly("Passing along persistence metadata for "+e[V.METADATA]),Object.defineProperty(n.model,V.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[V.METADATA]}));const a=t.mirroredAt(e);if(a){const t=a.mspId;if(!t)throw new c("No mirror MSP could be found");const e=this.getEndorsingOrganizations(s)||[],r=[...new Set([...e,t])];s.accumulate({endorsingOrgs:r,endorsingOrganizations:r,legacy:!0})}return{record:n.model,model:n.model,id:e[t.pk(e.constructor)],transient:n.transient,privates:n.privates,shared:n.shared}}revert(t,e,r,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.revert);return i&&this.shouldRebuildWithTransient(a,a.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,t])=>void 0!==t).forEach(([e,r])=>{e in t&&void 0!==t[e]&&n.warn(`overwriting existing ${e}. if this is not a default value, this may pose a problem`),t[e]=r})),new e(t)}shouldRebuildWithTransient(t,e){if(!t)return!1;if(t.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof t.getFromChildren?t.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(t,e);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(t,e){return e||("function"==typeof t.getFromChildren?t.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,s){if(!i)return!1;const n=t.pk(e),a=t.composed(e,n),o=t.generated(e,n),c=null!=s;return!(c||!a)||(!c&&o?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}getEndorsingOrganizations(t){const e=t.getOrUndefined("endorsingOrgs")||t.getOrUndefined("endorsingOrgs");return e&&e.length?e:t.getFromChildren("endorsingOrgs")||t.getFromChildren("endorsingOrgs")}async create(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.create),d=t.tableName(e);o.verbose(`adding entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h?{[d]:s}:{},g=await this.submitTransaction(c,l.CREATE,[this.serializer.serialize(i,e.name)],u,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,h,r)?this.read(e,Ce(e,f,r),c):f}async healthcheck(e,...r){const{log:i,ctx:s}=this.logCtx(r,this.healthcheck),n=t.tableName(e);i.verbose(`reading entry from ${n} table`);const a=await this.evaluateTransaction(s,"healthcheck",[],void 0,void 0,e.name);return JSON.parse(this.decode(a))}async read(e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.read),a=t.tableName(e);s.verbose(`reading entry from ${a} table`),s.debug("pk: "+r);const o=await this.evaluateTransaction(n,l.READ,[r.toString()],void 0,void 0,e.name);return this.serializer.deserialize(this.decode(o))}updatePrefix(e,r,i,...s){const n=t.tableName(e),{ctxArgs:a}=this.logCtx(s,this.updatePrefix),o={};return o[_.TABLE]=n,Object.assign(o,i),[e,r,o,...a]}async update(e,r,i,s={},...n){const a=[...n],{log:o,ctx:c}=this.logCtx(a,this.update);o.info("CLIENT UPDATE class : "+typeof e);const d=t.tableName(e);o.verbose(`updating entry to ${d} table`),o.debug("pk: "+r);const h=s&&Object.keys(s).length>0,u=h?{[d]:s}:{},g=await this.submitTransaction(c,l.UPDATE,[this.serializer.serialize(i,e.name||e)],u,this.getEndorsingOrganizations(c),e.name),f=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,c,h,r)?this.read(e,Ce(e,f,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);let c;this.shouldRefreshAfterWrite(e,n,o,r)&&(c=await this.read(e,r,n)),s.verbose(`deleting entry from ${a} table`),s.debug("pk: "+r);const d=await this.submitTransaction(n,l.DELETE,[r.toString()],void 0,this.getEndorsingOrganizations(n),e.name);return o?c:this.serializer.deserialize(this.decode(d))}async raw(e,r=!0,i,...s){const{log:n,ctx:a}=this.logCtx(s,this.raw),o=i.name;let c,l;n.info("Performing raw statement on table "+t.tableName(i));try{c=await this.evaluateTransaction(a,"raw",[JSON.stringify(e),r],void 0,void 0,o)}catch(t){throw this.parseError(t)}try{l=JSON.parse(this.decode(c))}catch(t){throw new g("Failed to process result: "+t)}if(Array.isArray(l)){if(!l.length)return l;const e=l[0];return t.isModel(e)?l.map(e=>t.build(e)):l}return d=l,t.isModel(d)?t.build(d):d;var d}async view(t,e,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.view);let a,o;s.info(`Querying view ${t}/${e}`);try{a=await this.evaluateTransaction(n,"view",[t,e,JSON.stringify(r)],void 0,void 0,void 0)}catch(t){throw this.parseError(t)}try{o=JSON.parse(this.decode(a))}catch(t){throw new g("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=ti.getClient(this.config)),this._client}async Gateway(t){return ti.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return ti.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s={},n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:Object.entries(s).reduce((t,[e,r])=>(t[e]=JSON.stringify(r),t),{}),endorsingOrganizations:t.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,e,d)}catch(t){throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}shouldUseLegacyGateway(t){return!!t.getOrUndefined("legacy")&&!!t.getOrUndefined("allowGatewayOverride")}prepareLegacyArgs(t){return(t||[]).map(t=>"string"==typeof t?t:JSON.stringify(t))}buildLegacyTransient(t){if(!t)return;const e=Object.entries(t);if(!e.length)return;const r={};for(const[t,i]of e)r[t]=Buffer.from(JSON.stringify(i));return r}buildLegacyPeerConfigs(){return[{peerEndpoint:this.config.peerEndpoint,tlsCert:this.config.tlsCert,peerHostAlias:this.config.peerHostAlias}]}async submitLegacyWithExplicitEndorsers(t,e,r,i,s,n){const a=this.log.for(this.submitLegacyWithExplicitEndorsers),o=await this.Gateway(t);try{const c=ti.getContract(o,this.config,this.getContractName(n));a.verbose(`Legacy submitting ${this.getContractName(n)||this.config.contractName}.${e}`),a.debug("Explicit peers: "+s.map(t=>t.peerEndpoint));const l=new Set;this.config.mspId&&l.add(this.config.mspId),(this.getEndorsingOrganizations(t)||[]).forEach(t=>l.add(t));const d={arguments:r,transientData:i,endorsingOrganizations:l.size>0?Array.from(l):void 0},h=c.newProposal(e,d),u=await h.endorse(),g=await u.submit(),f=await g.getStatus();if(!f.successful)throw Error(`Legacy endorsement failed for ${u.getTransactionId()}: ${f.code}`);return u.getResult()}catch(t){throw this.parseError(t)}finally{o.close()}}parseError(t){return ti.parseError(t)}async submitTransaction(t,e,r,i,s,n){if(this.shouldUseLegacyGateway(t)){const s=this.prepareLegacyArgs(r),a=this.buildLegacyTransient(i),o=this.buildLegacyPeerConfigs();return this.submitLegacyWithExplicitEndorsers(t,e,s,a,o,n)}return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=Mt.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=te.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new ee(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=Mt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Gr(e.mspId,e.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+_e.fabricIdFromCertificate(s.credentials.toString()))}catch(t){i.error("Failed to extract Fabric ID from certificate",t)}let n;if(e.hsm)throw new ht("HSM NOT IMPLEMENTED");n=await Vr(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=qt(a);return e.hsm&&(o.close=new Proxy(o.close,{apply(t,e,r){Reflect.apply(t,e,r)}})),o}Dispatch(){return new ti._baseDispatch}static parseError(t){let e="string"==typeof t?t:t.message;return t instanceof Yt&&t.details.length&&10===t.code&&(e=""+t.details[0].message),e.includes("MVCC_READ_CONFLICT")?new Ye(t):e.includes("DEADLINE_EXCEEDED")?new Qe(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new We(t):e.includes("PHANTOM_READ_CONFLICT")?new Ve(t):t instanceof Error&&t.code&&9===t.code?new qe(t):e.includes(u.name)?new u(t):e.includes(y.name)?new y(t):e.includes(m.name)?new m(t):e.includes(k.name)?new k(t):e.includes(yt.name)?new yt(t):e.includes(At.name)?new At(t):e.includes(ht.name)?new ht(t):e.includes(vt.name)?new vt(t):e.includes(Ct.name)?new Ct(t):e.includes(at.name)?new at(t):e.includes(St.name)?new St(t):e.includes(Et.name)?new Et(t):e.includes(g.name)?new g(t):new c(t)}}xt([Ht(),Kt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,Object,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"create",null),xt([Ht(),Kt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,et]),Nt("design:returntype",Promise)],ti.prototype,"healthcheck",null),xt([Ht(),Kt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"read",null),xt([Ht(),Kt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,Object,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"update",null),xt([Ht(),Kt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"delete",null),xt([Ht(),Nt("design:type",Function),Nt("design:paramtypes",[Object,"function"==typeof(Zr="undefined"!=typeof D&&D)?Zr:Object,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"raw",null),xt([Ht(),Nt("design:type",Function),Nt("design:paramtypes",[String,String,Object,et]),Nt("design:returntype",Promise)],ti.prototype,"view",null),ti.decoration(),bt.setCurrent(xe);class ei extends Ot{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof ti))throw new ht("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}=bt.logCtx(this.updateObservers,r,!1,...s);if(this.adapter)try{await this.adapter.refresh(e,r,i,...a)}catch(t){throw new c("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.tableName(e)}:${r}`)}async handleEvents(e){if(!this.listeningStack)throw new c('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new c("No adapter found. should be impossible");const r=e||await this.adapter.context(l.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t),i=this.log.for(this.handleEvents);i.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:s,event:n,owner:a}=Dr(e.eventName);if(a&&a!==this.adapter.config?.mspId)continue;const o=this.parsePayload(e.payload);try{const e=(s?t.get(s):t.get(this.models[0].name))??(s||this.models[0]?.name);await this.updateObservers(e,n,o.id,r)}catch(t){i.error(`Failed update observables for table ${s} event ${n} id: ${o.id}: ${t}`)}}}catch(t){i.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new c("No adapter or config observed for dispatch");const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t),{ctx:r}=this.logCtx([e],this.initialize),i=(await ti.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)}}ti&&(ti._baseDispatch=ei);const ri="##VERSION##",ii="##PACKAGE##";Tt.registerLibrary(ii,ri);export{Me as AllowanceError,$e as BASE_ALPHABET,Le as BalanceError,Be as BaseEncoder,Lr as CA_ROLE,Fe as CRYPTO,Ae as ClientSerializer,Te as CoreUtils,_e as CryptoUtils,Mr as DefaultFabricClientFlags,$r as DeterministicSerializer,Pe as ERC20Events,qe as EndorsementError,We as EndorsementPolicyError,er as FabricBaseModel,ti as FabricClientAdapter,ei as FabricClientDispatch,me as FabricClientRepository,ve as FabricERC20ClientRepository,Ze as FabricEnrollmentService,xe as FabricFlavour,rr as FabricIdentifiedBaseModel,jr as FabricIdentityService,Ee as FabricModelKeys,ke as HFCAIdentityAttributes,De as HFCAIdentityType,Ne as Identity,Se as IdentityCredentials,Oe as IdentityType,wr as ImplicitPrivateCollection,Ue as MissingContextError,Ge as MissingPKCSS11Lib,mr as ModelCollection,Ye as MvccReadConflictError,yr as NamespaceCollection,Ke as NotInitializedError,je as OverflowError,sr as Owner,ii as PACKAGE_NAME,Ve as PhantomReadConflictError,ze as RegistrationError,tr as RegistrationRequestBuilder,br as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,_r as SimpleDeterministicSerializer,Xe as TransactionBufferSizeError,Je as TransactionLimitsError,Qe as TransactionTimeoutError,He as UnauthorizedPrivateDataAccess,ri as VERSION,kr as add,vr as applyMirrorFlags,Ar as applySegregationFlags,de as collectionFor,Ur as contentOfLoadFile,dr as createMirrorHandler,ur as deleteMirrorHandler,lr as evalMirrorMetadata,ge as extractCollections,Ce as extractIds,ir as extractMspId,Wr as extractPrivateKey,Cr as extractSegregatedCollections,Fr as generateFabricEventName,ne as generateModelDesignDocs,se as generateModelIndexes,Ie as getAkiAndSerialFromCert,Kr as getCAUser,qr as getFirstDirFileName,Yr as getFirstDirFileNameContent,Gr as getIdentity,Vr as getSigner,pr as mirror,gr as mirrorWriteGuard,ar as ownedBy,nr as ownedByOnCreate,Dr as parseEventName,he as privateCollectionFor,Tr as privateData,Hr as readFile,fr as readMirrorHandler,ae as readModelFile,oe as readModelFolders,Br as safeParseInt,Sr as segregatedDataOnCreate,xr as segregatedDataOnDelete,Er as segregatedDataOnRead,Or as segregatedDataOnUpdate,ue as sharedCollectionFor,Ir as sharedData,Rr as sortKeysOnlyRecursive,Pr as sub,cr as transactionId,or as transactionIdOnCreate,hr as updateMirrorHandler,pe as writeCollectionDesignDocs,fe as writeCollections,le as writeDesignDocs,ce as writeIndexes};
|
|
2
2
|
//# sourceMappingURL=for-fabric.js.map
|