@decaf-ts/for-fabric 0.1.78 → 0.1.80
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/cli-module.cjs +76 -67
- package/lib/cli-module.js.map +1 -1
- package/lib/client/FabricClientAdapter.cjs +53 -1
- package/lib/client/FabricClientAdapter.d.ts +2 -1
- package/lib/client/FabricClientAdapter.js.map +1 -1
- package/lib/contracts/ContractAdapter.cjs +14 -3
- package/lib/contracts/ContractAdapter.js.map +1 -1
- package/lib/contracts/ContractContext.cjs +3 -0
- package/lib/contracts/ContractContext.d.ts +1 -0
- package/lib/contracts/ContractContext.js.map +1 -1
- package/lib/esm/cli-module.js +76 -67
- package/lib/esm/cli-module.js.map +1 -1
- package/lib/esm/client/FabricClientAdapter.d.ts +2 -1
- package/lib/esm/client/FabricClientAdapter.js +53 -1
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/contracts/ContractAdapter.js +14 -3
- package/lib/esm/contracts/ContractAdapter.js.map +1 -1
- package/lib/esm/contracts/ContractContext.d.ts +1 -0
- package/lib/esm/contracts/ContractContext.js +3 -0
- package/lib/esm/contracts/ContractContext.js.map +1 -1
- package/lib/esm/shared/decorators.d.ts +1 -0
- package/lib/esm/shared/decorators.js +40 -7
- 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 +41 -7
- package/lib/shared/decorators.d.ts +1 -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 +2 -2
package/dist/for-fabric.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Repository as t,PreparedStatementKeys as e,PersistenceKeys as r,Paginator as i,pk as s,column as n,table as a,BaseModel as o,Sequence as c,Context as l,oneToOne as d,Cascade as h,index as u,normalizeImport as g,AuthorizationError as p,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as A,Statement as v,QueryClause as C,Condition as S,Operator as E,QueryError as N,GroupOperator as x,Adapter as O,PagingError as T,MigrationError as I,ObserverError as $,ForbiddenError as R,ConnectionError as F,Dispatch as k}from"@decaf-ts/core";import{Model as _,required as B,model as P,JSONSerializer as j,ModelKeys as K,stringFormat as L,minlength as M,min as z}from"@decaf-ts/decorator-validation";import{OperationKeys as H,enforceDBDecorators as U,reduceErrorsToPrint as G,ValidationError as Y,SerializationError as V,InternalError as J,BaseError as q,ConflictError as Q,NotFoundError as W,version as X,DBKeys as Z,generated as tt,readonly as et,onCreate as rt,onUpdate as it,afterCreate as st,afterUpdate as nt,afterDelete as at,transient as ot,on as ct,DBOperations as lt,onRead as dt,onDelete as ht,BulkCrudOperationKeys as ut,BadRequestError as gt}from"@decaf-ts/db-decorators";import{CouchDBKeys as pt,generateIndexes as ft,generateViews as mt,CouchDBGroupOperator as yt,CouchDBOperator as wt,CouchDBQueryLimit as bt,translateOperators as At,findViewMetadata as vt,generateViewName as Ct,generateDesignDocName as St}from"@decaf-ts/for-couchdb";import{__decorate as Et,__metadata as Nt}from"tslib";import{Metadata as xt,description as Ot,uses as Tt,Decoration as It,apply as $t,propMetadata as Rt,metadata as Dt,prop as Ft}from"@decaf-ts/decoration";import kt from"fabric-ca-client";import{MiniLogger as _t,isBrowser as Bt,LoggedClass as Pt,Logging as jt,toPascalCase as Kt,toCamelCase as Lt,debug as Mt,final as zt}from"@decaf-ts/logging";import{signers as Ht,connect as Ut}from"@hyperledger/fabric-gateway";import{User as Gt}from"fabric-common";import Yt,{X509Certificate as Vt}from"crypto";import*as Jt from"@peculiar/x509";import{Crypto as qt}from"@peculiar/webcrypto";import*as Qt from"@grpc/grpc-js";import{Client as Wt}from"@grpc/grpc-js";import Xt from"pkcs11js";import Zt from"fs";import te from"path";import{p256 as ee}from"@noble/curves/nist";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})}override(t){return super.override(t).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 ${_.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 ${_.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 ${_.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 ${_.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async statement(t,...e){const{log:s,ctx:n,ctxArgs:a}=(await this.logCtx(e,r.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,r.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]===_.tableName(this.class)?new this.class(t):t)):c[pt.TABLE]&&c[pt.TABLE]===_.tableName(this.class)?new this.class(c):i.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.tableName(this.class)} by ${t}`),this.statement(e.GROUP_OF,t,...s)}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 ${_.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,o,...s),this.adapter.revert(n,this.class,a,o,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,s);return i.debug(`updating ${this.class.name} in table ${_.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,o,...r),this.adapter.revert(n,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,H.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map((async t=>(t=new this.class(t),s||await U(this,r,t,H.CREATE,H.ON),t)))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),s=G(i);if(s)throw new Y(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 ${_.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r))),a=n.map((t=>t.id));let o=n.map((t=>t.record));const c=n.map((t=>t.transient));return o=await this.adapter.createAll(this.class,a,o,c,...s),o.map(((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,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 ${_.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,n.map((t=>t.id)),n.map((t=>t.record)),n.map((t=>t.transient)),...s)).map(((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}}let ie=class extends o{constructor(t){super(t)}};Et([s({type:String}),Nt("design:type",String)],ie.prototype,"name",void 0),Et([n(),B(),Nt("design:type",String)],ie.prototype,"owner",void 0),Et([n(),B(),Nt("design:type",String)],ie.prototype,"symbol",void 0),Et([n(),B(),Nt("design:type",Number)],ie.prototype,"decimals",void 0),ie=Et([a("erc20_tokens"),P(),Nt("design:paramtypes",[Object])],ie);let se=class extends o{constructor(t){super(t)}};Et([s({type:String}),Nt("design:type",String)],se.prototype,"id",void 0),Et([n(),B(),Nt("design:type",String)],se.prototype,"token",void 0),Et([n(),B(),Nt("design:type",Number)],se.prototype,"balance",void 0),Et([n(),Nt("design:type",String)],se.prototype,"captive",void 0),se=Et([a("erc20_wallets"),P(),Nt("design:paramtypes",[Object])],se);let ne=class extends o{constructor(t){super(t)}};Et([s({type:String}),n(),B(),Nt("design:type",String)],ne.prototype,"owner",void 0),Et([n(),B(),Nt("design:type",String)],ne.prototype,"spender",void 0),Et([n(),B(),Nt("design:type",Number)],ne.prototype,"value",void 0),ne=Et([a("erc20_allowances"),P(),Nt("design:paramtypes",[Object])],ne);class ae extends j{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=xt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new V("Could not find metadata for "+t.constructor.name);i=e}return r[K.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[K.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return _.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 J("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?_.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map((e=>c.parseValue(_.sequenceFor(t).type,e))):c.parseValue(_.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 ft([t])}function de(t,e){const r=mt([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 _}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 pe(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 fe=class extends o{constructor(t){super(t)}};var me,ye;Et([Ot("Unique identifier of the credentials record"),n(),s(),Nt("design:type",String)],fe.prototype,"id",void 0),Et([Ot("PEM-encoded X.509 certificate for the identity"),n(),B(),Nt("design:type",String)],fe.prototype,"certificate",void 0),Et([Ot("PEM-encoded root or intermediate certificate"),n(),B(),Nt("design:type",String)],fe.prototype,"rootCertificate",void 0),Et([Ot("PEM-encoded private key"),n(),B(),Nt("design:type",String)],fe.prototype,"privateKey",void 0),fe=Et([P(),Nt("design:paramtypes",[Object])],fe),(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 o{constructor(t){super(t),this.type=ye.X509}};Et([Ot("Unique identifier of the identity"),s(),Nt("design:type",String)],be.prototype,"id",void 0),Et([d(fe,{update:h.CASCADE,delete:h.CASCADE}),Nt("design:type",fe)],be.prototype,"credentials",void 0),Et([n(),B(),u(),Nt("design:type",String)],be.prototype,"mspId",void 0),Et([n(),B(),Nt("design:type",String)],be.prototype,"type",void 0),be=Et([P(),Nt("design:paramtypes",[Object])],be);class Ae{static{this.logger=new _t(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 g(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(L("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Gt(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=Gt.newCryptoSuite(t)),Ae.cryptoSuite):Gt.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 Vt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Yt.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){const r=await this.contentOfLoadFile(e,(async t=>{const{promises:e}=await g(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}));return{mspId:t,credentials:r}}static async getFirstDirFileName(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await g(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,(async t=>{const{promises:e}=await g(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await g(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"])}}const ve=new qt;var Ce,Se,Ee,Ne,xe;Jt.cryptoProvider.set(ve),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(Ce||(Ce={})),(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"})(Se||(Se={}));class Oe{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 Te{static{this.b58encoder=new Oe(Ce.BASE58)}static{this.logger=new _t(Te.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(L("Parsing certificate: {0}",t));const e=new Jt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(L("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=ve.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await ve.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map((t=>t.toString(16).padStart(2,"0"))).join("")}static async verify(t,e,r){const i=new 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,ve.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 Bt()?globalThis.window.crypto.subtle:ve.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=ve.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Se.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:Se.KEY_ALGORYTHM,hash:Se.HASH,salt:i,iterations:Se.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Se.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:Se.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Se.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Se.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class Ie extends J{constructor(t){super(t,Ie.name)}}class $e extends J{constructor(t){super(t,$e.name)}}class Re extends J{constructor(t){super(t,Re.name)}}class De extends p{constructor(t){super(t,De.name)}}class Fe extends J{constructor(t){super(t,Fe.name,500)}}class ke extends q{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ke.name,t,403)}}class _e extends q{constructor(t){super(_e.name,t,409)}}class Be extends J{constructor(t){super(t,Be.name,500)}}class Pe extends J{constructor(t){super(t,Pe.name,500)}}class je extends J{constructor(t){super(t,je.name,500)}}class Ke extends J{constructor(t){super(t,Ke.name,500)}}class Le extends J{constructor(t){super(t,Le.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Ee||(Ee={})),(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"})(Ne||(Ne={}));class Me extends Pt{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 J(`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 kt(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 De(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new p(i);default:return new De(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 W(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new W(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=jt.for(Me,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=Te.fabricIdFromCertificate(r),o=Te.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=Me.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 W("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 J(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new J(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class ze extends _{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new Y(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}Et([B(),Nt("design:type",String)],ze.prototype,"affiliation",void 0),Et([M(1),Nt("design:type",Array)],ze.prototype,"attrs",void 0),Et([B(),Nt("design:type",String)],ze.prototype,"enrollmentID",void 0),Et([B(),Nt("design:type",String)],ze.prototype,"enrollmentSecret",void 0),Et([z(0),Nt("design:type",Number)],ze.prototype,"maxEnrollments",void 0),Et([B(),Nt("design:type",String)],ze.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(xe||(xe={}));let He=class extends _{constructor(t){super(t)}};Et([Ot("Stores the original timestamp of creation"),n(),f(),Nt("design:type",Date)],He.prototype,"createdAt",void 0),Et([Ot("Stores the timestamp of the last update"),n(),m(),Nt("design:type",Date)],He.prototype,"updatedAt",void 0),Et([Ot("Stores the version of the model"),n(),X(),Nt("design:type",Number)],He.prototype,"version",void 0),He=Et([Tt(we),Nt("design:paramtypes",[Object])],He);let Ue=class extends He{constructor(t){super(t)}};function Ge(t){if(t)return"string"==typeof t?t:t.getMSPID()}function Ye(){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 W("No tokens avaialble");if(a.length>1)throw new W("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 Ve(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 Je(){return It.for(me.OWNED_BY).define({decorator:()=>(t,e)=>$t(B(),tt(),et(),rt(Ve),Rt(xt.key(me.FABRIC,me.OWNED_BY),e))(t,e),args:[]}).apply()}async function qe(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Qe(){return It.for(me.TRANSACTION_ID).define({decorator:()=>(t,e)=>$t(B(),et(),rt(qe),it(qe),Rt(xt.key(me.FABRIC,e,me.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function We(t,e,r){let i=e;if("string"!=typeof i)try{const s=_.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new J("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new J("No collection found model "+t.constructor.name);return i}async function Xe(t,e,r,i){const s=await We(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.create(i,t);t.logger.info(`Mirror for ${_.tableName(this.class)} created with ${_.pk(i)}: ${a[_.pk(i)]}`)}async function Ze(t,e,r,i){const s=await We(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.update(i,t);t.logger.info(`Mirror for ${_.tableName(this.class)} updated with ${_.pk(i)}: ${a[_.pk(i)]}`)}async function tr(t,e,r,i){const s=await We(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete(_.pk(i),t);t.logger.info(`Mirror for ${_.tableName(this.class)} deleted with ${_.pk(i)}: ${a[_.pk(i)]}`)}function er(t,e){return It.for(me.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return $t(Dt(xt.key(me.FABRIC,me.MIRROR),i),ur(t),st(Xe,i,{priority:95}),nt(Ze,i,{priority:95}),at(tr,i,{priority:95}))},args:[t,e]}).apply()}Et([Ot("Stores the creator"),n(),y(),Nt("design:type",String)],Ue.prototype,"createdBy",void 0),Et([Ot("Stores the user that last updated the model"),n(),w(),Nt("design:type",String)],Ue.prototype,"updatedBy",void 0),Ue=Et([Tt(we),Nt("design:paramtypes",[Object])],Ue),_.prototype.isShared=function(){return _.isShared(this.constructor)},_.prototype.isPrivate=function(){return _.isPrivate(this.constructor)},_.prototype.segregate=function(){return _.segregate(this)},_.segregate=(t=>{if(!_.isTransient(t))return{model:t};const e=xt.validatableProperties(t.constructor),r=xt.get(t.constructor,Z.TRANSIENT),i=xt.get(t.constructor,me.PRIVATE),s=xt.get(t.constructor,me.SHARED),n={model:{},transient:{},privates:{},shared:{}},a=Object.keys(r||{}),o=Object.keys(i||{}),c=Object.keys(s||{}),l=_.pk(t.constructor);for(const r of e){const e=t[r],i=a.includes(r),s=o.includes(r),d=c.includes(r),h=r!==l||"string"!=typeof e||e.endsWith(",")?e:e+",";(i||s||d)&&(n.transient=n.transient||{},n.transient[r]=h),s&&(n.privates=n.privates||{},n.privates[r]=h),d&&(n.shared=n.shared||{},n.shared[r]=h),!i&&!s&&!d&&(n.model=n.model||{},n.model[r]=e)}return n.model=_.build(n.model,t.constructor.name),n}).bind(_),_.isPrivate=(t=>!!xt.get("function"!=typeof t?t.constructor:t,me.PRIVATE)).bind(_),_.isShared=(t=>!!xt.get("function"!=typeof t?t.constructor:t,me.SHARED)).bind(_),_.mirrored=(t=>xt.get("function"!=typeof t?t.constructor:t,xt.key(me.FABRIC,me.MIRROR))).bind(_),_.ownerOf=(t=>{const e=xt.get(t.constructor,xt.key(me.FABRIC,me.OWNED_BY));if(e)return t[e]}).bind(_),_.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,xt.get(t,xt.key(me.FABRIC,me.MIRROR)))).bind(_),_.collectionsFor=(t=>{const e=[me.PRIVATE],r=[me.SHARED],i=xt.key(...e),s=xt.key(...r),n="function"==typeof t?t:t.constructor,a=xt.get(n,i),o=xt.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(_);const rr=(t,e)=>{const r=e||("function"!=typeof t?_.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new J(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Kt(i.name)}${r?Kt(r):""}`};function ir(t){return(e,r)=>{const i=r||("function"!=typeof e?_.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!i)throw new J(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${t}${i?Kt(i):""}`}}const sr=(t,e)=>{const r=e||("function"!=typeof t?_.ownerOf(t):void 0);if(!r)throw new J(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Kt(r)}PrivateCollection`},nr=35;async function ar(t,e,r,i){const s=Array.isArray(e)?e:[e],n=_.ownerOf(i)||Ge(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)}a.length>0&&t.readFrom(a)}async function or(t,e,r,i){const s=Array.isArray(e)?e:[e],n=Array.isArray(r)?r:[r];if(n.length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const a=_.ownerOf(i)||Ge(t.get("identity"));if(!a)throw new Y("There's no assigned organization for model "+i.constructor.name);const o=s[0].collections,c="string"==typeof o?o:o(i,a,t),l=n.reduce(((e,r,n)=>{const o="string"==typeof s[n].collections?s[n].collections:s[n].collections(i,a,t);if(o!==c)throw new b(`Segregated data collection mismatch: ${o} vs ${c}`);return e[r]=i[r],e}),{});new this.class(l);const d=_.segregate(i);t.writeTo(c,d)}async function cr(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const n=_.ownerOf(i)||Ge(t.get("identity"));if(!n)throw new Y("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 lr(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 J("Segregated data keys and metadata length mismatch");const o=_.ownerOf(i)||Ge(t.get("identity"));if(!o)throw new Y("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 b(`Segregated data collection mismatch: ${s} vs ${l}`)}));const d=_.segregate(i);t.writeTo(l,d)}async function dr(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const n=_.ownerOf(i)||Ge(t.get("identity"));if(!n)throw new Y("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 hr(t,e,r){return(i,s)=>{const n=[];if(s){const r="string"==typeof t?t:t.toString(),i={collections:t},s={priority:nr,group:r};n.push(Ft(),ot(),((r,i)=>{const s=xt.key(e,i),n=r.constructor,a=xt.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],xt.set(n,s,a);const c=xt.get(n,e)||{},l=new Set(c.collections||[]);l.add(t),c.collections=[...l],xt.set(n,e,c);const d={...xt.get(n,Z.TRANSIENT)||{},[i]:{}};xt.set(n,Z.TRANSIENT,d)}),ct(lt.ALL,ar,i,s),rt(or,{collections:t},{priority:95,group:r}),dt(cr,{collections:t},{priority:95,group:r}),it(lr,{collections:t},{priority:95,group:r}),ht(dr,{collections:t},{priority:95,group:r}))}else{const s=xt.validatableProperties(i);s?.forEach((s=>{r&&!r(s)||hr(t,e)(i.prototype,s)}))}return $t(...n)(i,s)}}function ur(t=sr){return It.for(me.PRIVATE).define({decorator:t=>hr(t,me.PRIVATE),args:[t]}).apply()}function gr(t){return It.for(me.SHARED).define({decorator:t=>hr(t,me.SHARED),args:[t]}).apply()}class pr extends j{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=xt.modelName(t.constructor)}catch(t){r=void 0}e[K.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 _.relations(t).forEach((t=>{e[t]=i(e[t])})),e}deserialize(t){const e=JSON.parse(t),r=e[K.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return _.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function fr(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function mr(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function yr(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new Ie(`Addition overflow: ${t} + ${e}`);return r}function wr(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new Ie(`Subtraction overflow: ${t} - ${e}`);return r}function br(t){if(!/^\d+$/.test(t))throw new Y(L("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new Y(L("Failed to parse: {0}","string is not a parsable integer"));return e}class Ar extends j{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t,e)))}preSerialize(t,e=!0){const r=Object.assign({},t);let i;try{i=xt.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[K.ANCHOR]=i||t.constructor.name),_.relations(t).forEach((t=>{r[t]=s.call(this,r[t])})),r}}class vr extends A{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new J("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 J(`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:i}=(await this.logCtx(t,r.INITIALIZATION,!0)).for(this.initialize),[s]=t;if(!s)throw new J("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 kt(n,{trustedRoots:Buffer.from(h),verify:l},o),g=await this.getUser(s,i);return e.debug("CA user loaded: "+g.getName()),{config:s,client:u}}async getCertificates(t,e=!0,...r){t instanceof l?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=(await this.logCtx(r,H.READ,!0)).for(this.getCertificates);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map((t=>t.PEM)):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new De(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new p(i);default:return new De(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,H.READ,!0)).for(this.read);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new W(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new W(`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=Te.fabricIdFromCertificate(s),c=Te.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=vr.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 revoke(t,...e){const{log:r}=(await this.logCtx(e,"revoke",!0)).for(this.revoke);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new W("Could not find enrollment with id "+t);let s;try{s=await this.client.revoke({enrollmentID:i.id,reason:"User Deletion"},this.user)}catch(e){throw new J(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new J(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const Cr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),Sr=new _t("fabric-fs");async function Er(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Nr(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await g(import("fs"));return await e.readFile(t)})(t)}async function xr(t,e,r,i){Sr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Gt(t),n=Gt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Or(t,e){const r=await Er(e,(async t=>{const{promises:e}=await g(import("fs")),r=await Tr(t);return await e.readFile(r)}));return{mspId:t,credentials:r}}async function Tr(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path"));return r(t,(await e.readdir(t))[0])}async function Ir(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function $r(t){const e=await Er(t,(async t=>{const{promises:e}=await g(import("fs")),r=await Tr(t);return await e.readFile(r)})),r=await Rr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ht.newPrivateKeySigner(i)}async function Rr(t){let e;if(Bt())e=globalThis.crypto.subtle;else{const t=await g(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 J(t)}}class Dr{static#t=null;static#e=!1;constructor(t){if(Dr.#t||(Dr.#t=new Xt.PKCS11,Dr.#t.load(this.findHSMPKCS11Lib(t))),!Dr.#e){try{Dr.#t.C_Initialize()}catch(t){if(t.code!==Xt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}Dr.#e=!0}}findHSMPKCS11Lib(t){const e=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];t&&e.push(t);for(const t of e)if(Zt.existsSync(t))return t;throw new Be("Unable to find PKCS11 library")}dispose(){Dr.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Xt.CKU_USER},t);return this.assertNotEmpty(e.label,"label"),this.assertNotEmpty(e.pin,"pin"),this.assertNotEmpty(e.identifier,"identifier"),e}assertNotEmpty(t,e){if(!t||0===t.toString().trim().length)throw Error(e+" property must be provided")}findSlotForLabel(t){const e=Dr.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find((e=>Dr.#t.C_GetTokenInfo(e).label.trim()===t));if(!r)throw Error(`label ${t} cannot be found in the pkcs11 slot list`);return r}login(t,e,r){try{Dr.#t.C_Login(t,e,r)}catch(t){if(t.code!==Xt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Xt.CKA_ID,value:r},{type:Xt.CKA_CLASS,value:e},{type:Xt.CKA_KEY_TYPE,value:Xt.CKK_EC}];Dr.#t.C_FindObjectsInit(t,i);const s=Dr.#t.C_FindObjects(t,1)[0];if(!s)throw Dr.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return Dr.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=Dr.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Xt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Xt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw Dr.#t.C_CloseSession(s),t}return{signer:async t=>{Dr.#t.C_SignInit(s,{mechanism:Xt.CKM_ECDSA},n);const e=await Dr.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*ee.Point.Fn.BYTES));return ee.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{Dr.#t.C_CloseSession(s)}}}assertDefined(t){if(void 0===t)throw Error("required value was undefined");return t}getUncompressedPointOnCurve(t){const e=t.export({format:"jwk"}),r=Buffer.from(this.assertDefined(e.x),"base64url"),i=Buffer.from(this.assertDefined(e.y),"base64url"),s=Buffer.from("04","hex");return Buffer.concat([s,r,i])}getSKIFromCertificatePath(t){const e=t.endsWith(".pem")?t:te.join(t,"cert.pem"),r=Zt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new Yt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return Yt.createHash("sha256").update(r).digest()}}class Fr extends v{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_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 J("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(r.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],i={},s={class:this.fromSelector,args:e,params:i},n=[C.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(C.SELECT,this.selectSelector.join(` ${C.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(C.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),s.method=Lt(n.join(" ")),s.params=i,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,c.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=_.pk(this.fromSelector),a=xt.get(this.fromSelector,xt.key(Z.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]=_.tableName(this.fromSelector);const i={selector:r};if(this.selectSelector&&(i.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(S.and(this.whereCondition,S.attribute(pt.TABLE).eq(i.selector[pt.TABLE]))).selector,r=Object.keys(e);if(1===r.length&&-1!==Object.values(yt).indexOf(r[0]))switch(r[0]){case yt.AND:e[yt.AND]=[...Object.values(e[yt.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===yt.AND?t.push(...e[i]):t.push(e),t}),[])],i.selector=e;break;case yt.OR:{const t={};t[yt.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][wt.BIGGER]=null)}}return this.limitSelector?i.limit=this.limitSelector:(t.warn("No limit selector defined. Using default couchdb limit of "+bt),i.limit=bt),this.offsetSelector&&(i.skip=this.offsetSelector),i}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===E.BETWEEN){const t=e;if(!Array.isArray(i)||2!==i.length)throw new N("BETWEEN operator requires [min, max] comparison");const[r,s]=i,n={};return n[t]={},n[t][At(E.BIGGER_EQ)]=r,n[t][At(E.SMALLER_EQ)]=s,{selector:n}}let s={};if(-1===[x.AND,x.OR,E.NOT].indexOf(r))s[e]={},s[e][At(r)]=i;else if(r===E.NOT)s=this.parseCondition(e).selector,s[At(E.NOT)]={},s[At(E.NOT)][e.attr1]=i;else{const t=this.parseCondition(e).selector,n=this.parseCondition(i).selector;s=((t,e,r)=>{const i={selector:{}};return i.selector[t]=[e,r],i})(At(r),t,n).selector}return{selector:s}}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 N("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 N(`No CouchDB view metadata found for table ${_.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(t,e){if(!this.fromSelector)return;const r=vt(this.fromSelector,t,e);if(!r.length)return;const i=r[0],s=_.tableName(this.fromSelector),n=Ct(s,i.attribute,t,i),a=i.ddoc||St(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 N("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 N("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 i{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new b("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 _r;class Br extends O{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new ae}static{this.log=jt.for(Br)}constructor(t,e){super(Object.assign({},t,{evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),we,e),this.serializer=Br.serializer}Statement(t){return new Fr(this,t)}Paginator(t,e,r){return new kr(this,t,e,r)}async flags(t,e,r,...i){return Object.assign(await super.flags(t,e,Object.assign({},this.config,r),...i))}decode(t){return Br.decoder.decode(t)}repository(){return re}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=_.tableName(t),a={};return a[pt.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=_.tableName(t);if(e.length!==r.length)throw new J("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=_.tableName(t);if(e.length!==r.length)throw new J("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 J("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=_.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ut.CREATE_ALL,[JSON.stringify(r.map((e=>this.serializer.serialize(e,t.name))))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map((t=>JSON.parse(t)))}catch(t){throw new V(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=_.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,ut.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 V(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new J("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=_.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ut.UPDATE_ALL,[JSON.stringify(r.map((e=>this.serializer.serialize(e,t.name))))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map((t=>JSON.parse(t)))}catch(t){throw new V(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=_.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,ut.DELETE_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 V(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=_.segregate(t);return t[r.METADATA]&&(i.silly("Passing along persistence metadata for "+t[r.METADATA]),Object.defineProperty(s.model,r.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[r.METADATA]})),{record:s.model,model:s.model,id:t[_.pk(t.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(t,e,r,i,...s){const{log:n}=this.logCtx(s,this.revert);return i&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach((([r,i])=>{if(r in t&&void 0!==t[r])throw new J(`Transient property ${r} already exists on model ${"string"==typeof e?e:e.name}. should be impossible`);t[r]=i}))),new e(t)}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=_.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,H.CREATE,[this.serializer.serialize(r,t.name)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=_.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,H.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=_.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.updateAll);a.info("CLIENT UPDATE class : "+typeof t);const c=_.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,H.UPDATE,[this.serializer.serialize(r,t.name||t)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=_.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,H.DELETE,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}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 "+_.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 V("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return _.isModel(t)?c.map((t=>_.build(t))):c}return l=c,_.isModel(l)?_.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 V("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=Br.getClient(this.config)),this._client}async Gateway(t){return Br.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return Br.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:s};return await l.call(c,e,d)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(t){return Br.parseError(t)}async submitTransaction(t,e,r,i,s,n){return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=jt.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(Zt.readFileSync(r,"utf8"))}catch(t){throw new J(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Qt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Wt(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=jt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Or(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new Dr(e.hsm.library),r=t.getSKIFromCertificatePath(e.certCertOrDirectoryPath),i=t.newSigner({label:e.hsm.tokenLabel,pin:e.hsm.pin+"",identifier:r});n=i.signer,a=i.close}else n=await $r(e.keyCertOrDirectoryPath);const o={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 c=Ut(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new Br._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new je(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Le(t):e.includes("PHANTOM_READ_CONFLICT")?new Ke(t):t instanceof Error&&t.code&&9===t.code?new Pe(t):e.includes(W.name)?new W(t):e.includes(Q.name)?new Q(t):e.includes(gt.name)?new gt(t):e.includes(N.name)?new N(t):e.includes(T.name)?new T(t):e.includes(b.name)?new b(t):e.includes(I.name)?new I(t):e.includes($.name)?new $(t):e.includes(p.name)?new p(t):e.includes(R.name)?new R(t):e.includes(F.name)?new F(t):e.includes(V.name)?new V(t):new J(t)}}Et([Mt(),zt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,Object,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"create",null),Et([Mt(),zt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"read",null),Et([Mt(),zt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,Object,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"update",null),Et([Mt(),zt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"delete",null),Et([Mt(),Nt("design:type",Function),Nt("design:paramtypes",[Object,"function"==typeof(_r="undefined"!=typeof D&&D)?_r:Object,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"raw",null),Et([Mt(),Nt("design:type",Function),Nt("design:paramtypes",[String,String,Object,l]),Nt("design:returntype",Promise)],Br.prototype,"view",null),Br.decoration(),O.setCurrent(we);class Pr extends k{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 Br))throw new b("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}=O.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new J("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:_.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new J('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new J("No adapter found. should be impossible");const e=t||await this.adapter.context(H.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||_),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}=mr(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?_.get(i):_.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 J("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},_),{ctx:e}=this.logCtx([t],this.initialize),r=(await Br.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new J("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}Br&&(Br._baseDispatch=Pr);const jr="##VERSION##",Kr="##PACKAGE##";xt.registerLibrary(Kr,jr);export{Re as AllowanceError,Ce as BASE_ALPHABET,$e as BalanceError,Oe as BaseEncoder,Se as CRYPTO,ae as ClientSerializer,Ae as CoreUtils,Te as CryptoUtils,Cr as DefaultFabricClientFlags,pr as DeterministicSerializer,xe as ERC20Events,Pe as EndorsementError,Le as EndorsementPolicyError,He as FabricBaseModel,Br as FabricClientAdapter,Pr as FabricClientDispatch,re as FabricClientRepository,oe as FabricERC20ClientRepository,Me as FabricEnrollmentService,we as FabricFlavour,Ue as FabricIdentifiedBaseModel,vr as FabricIdentityService,me as FabricModelKeys,Ne as HFCAIdentityAttributes,Ee as HFCAIdentityType,be as Identity,fe as IdentityCredentials,ye as IdentityType,sr as ImplicitPrivateCollection,Fe as MissingContextError,Be as MissingPKCSS11Lib,rr as ModelCollection,je as MvccReadConflictError,ir as NamespaceCollection,_e as NotInitializedError,Ie as OverflowError,Ye as Owner,Kr as PACKAGE_NAME,Ke as PhantomReadConflictError,De as RegistrationError,ze as RegistrationRequestBuilder,nr as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,Ar as SimpleDeterministicSerializer,ke as UnauthorizedPrivateDataAccess,jr as VERSION,yr as add,Er as contentOfLoadFile,Xe as createMirrorHandler,tr as deleteMirrorHandler,We as evalMirrorMetadata,Rr as extractPrivateKey,ar as extractSegregatedCollections,fr as generateFabricEventName,de as generateModelDesignDocs,le as generateModelIndexes,xr as getCAUser,Tr as getFirstDirFileName,Ir as getFirstDirFileNameContent,Or as getIdentity,$r as getSigner,er as mirror,Je as ownedBy,Ve as ownedByOnCreate,mr as parseEventName,ur as privateData,Nr as readFile,he as readModelFile,ue as readModelFolders,br as safeParseInt,or as segregatedDataOnCreate,dr as segregatedDataOnDelete,cr as segregatedDataOnRead,lr as segregatedDataOnUpdate,gr as sharedData,wr as sub,Qe as transactionId,qe as transactionIdOnCreate,Ze as updateMirrorHandler,pe as writeDesignDocs,ge as writeIndexes};
|
|
1
|
+
import{Repository as t,PreparedStatementKeys as e,PersistenceKeys as r,Paginator as i,pk as s,column as n,table as a,BaseModel as o,Sequence as c,Context as l,oneToOne as d,Cascade as h,index as u,normalizeImport as g,AuthorizationError as f,createdAt as p,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as A,Statement as v,QueryClause as C,Condition as S,Operator as E,QueryError as x,GroupOperator as N,Adapter as O,PagingError as T,MigrationError as I,ObserverError as $,ForbiddenError as R,ConnectionError as F,Dispatch as k}from"@decaf-ts/core";import{Model as _,required as B,model as P,JSONSerializer as j,ModelKeys as L,stringFormat as M,minlength as K,min as z}from"@decaf-ts/decorator-validation";import{OperationKeys as U,enforceDBDecorators as H,reduceErrorsToPrint as G,ValidationError as Y,SerializationError as V,InternalError as J,BaseError as q,ConflictError as Q,NotFoundError as W,version as X,DBKeys as Z,generated as tt,readonly as et,onCreate as rt,onUpdate as it,onRead as st,afterCreate as nt,afterUpdate as at,afterDelete as ot,transient as ct,on as lt,DBOperations as dt,onDelete as ht,BulkCrudOperationKeys as ut,BadRequestError as gt}from"@decaf-ts/db-decorators";import{CouchDBKeys as ft,generateIndexes as pt,generateViews as mt,CouchDBGroupOperator as yt,CouchDBOperator as wt,CouchDBQueryLimit as bt,translateOperators as At,findViewMetadata as vt,generateViewName as Ct,generateDesignDocName as St}from"@decaf-ts/for-couchdb";import{__decorate as Et,__metadata as xt}from"tslib";import{Metadata as Nt,description as Ot,uses as Tt,Decoration as It,apply as $t,propMetadata as Rt,metadata as Dt,prop as Ft}from"@decaf-ts/decoration";import kt from"fabric-ca-client";import{MiniLogger as _t,isBrowser as Bt,LoggedClass as Pt,Logging as jt,toPascalCase as Lt,toCamelCase as Mt,debug as Kt,final as zt}from"@decaf-ts/logging";import{signers as Ut,connect as Ht}from"@hyperledger/fabric-gateway";import{User as Gt}from"fabric-common";import Yt,{X509Certificate as Vt}from"crypto";import*as Jt from"@peculiar/x509";import{Crypto as qt}from"@peculiar/webcrypto";import*as Qt from"@grpc/grpc-js";import{Client as Wt}from"@grpc/grpc-js";import Xt from"pkcs11js";import Zt from"fs";import te from"path";import{p256 as ee}from"@noble/curves/nist";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})}override(t){return super.override(t).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 ${_.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 ${_.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 ${_.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 ${_.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async statement(t,...e){const{log:s,ctx:n,ctxArgs:a}=(await this.logCtx(e,r.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,r.STATEMENT,[t,JSON.stringify(o)],void 0,void 0,this.class.name)));return Array.isArray(c)?c.map((t=>t[ft.TABLE]&&t[ft.TABLE]===_.tableName(this.class)?new this.class(t):t)):c[ft.TABLE]&&c[ft.TABLE]===_.tableName(this.class)?new this.class(c):i.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.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 ${_.tableName(this.class)} by ${t}`),this.statement(e.GROUP_OF,t,...s)}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 ${_.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,o,...s),this.adapter.revert(n,this.class,a,o,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,s);return i.debug(`updating ${this.class.name} in table ${_.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,o,...r),this.adapter.revert(n,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,U.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 H(this,r,t,U.CREATE,U.ON),t)))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),s=G(i);if(s)throw new Y(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 ${_.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r))),a=n.map((t=>t.id));let o=n.map((t=>t.record));const c=n.map((t=>t.transient));return o=await this.adapter.createAll(this.class,a,o,c,...s),o.map(((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,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 ${_.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,n.map((t=>t.id)),n.map((t=>t.record)),n.map((t=>t.transient)),...s)).map(((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}}let ie=class extends o{constructor(t){super(t)}};Et([s({type:String}),xt("design:type",String)],ie.prototype,"name",void 0),Et([n(),B(),xt("design:type",String)],ie.prototype,"owner",void 0),Et([n(),B(),xt("design:type",String)],ie.prototype,"symbol",void 0),Et([n(),B(),xt("design:type",Number)],ie.prototype,"decimals",void 0),ie=Et([a("erc20_tokens"),P(),xt("design:paramtypes",[Object])],ie);let se=class extends o{constructor(t){super(t)}};Et([s({type:String}),xt("design:type",String)],se.prototype,"id",void 0),Et([n(),B(),xt("design:type",String)],se.prototype,"token",void 0),Et([n(),B(),xt("design:type",Number)],se.prototype,"balance",void 0),Et([n(),xt("design:type",String)],se.prototype,"captive",void 0),se=Et([a("erc20_wallets"),P(),xt("design:paramtypes",[Object])],se);let ne=class extends o{constructor(t){super(t)}};Et([s({type:String}),n(),B(),xt("design:type",String)],ne.prototype,"owner",void 0),Et([n(),B(),xt("design:type",String)],ne.prototype,"spender",void 0),Et([n(),B(),xt("design:type",Number)],ne.prototype,"value",void 0),ne=Et([a("erc20_allowances"),P(),xt("design:paramtypes",[Object])],ne);class ae extends j{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=Nt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new V("Could not find metadata for "+t.constructor.name);i=e}return r[L.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[L.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return _.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 J("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?_.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map((e=>c.parseValue(_.sequenceFor(t).type,e))):c.parseValue(_.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 l.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 pt([t])}function de(t,e){const r=mt([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 _}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 o{constructor(t){super(t)}};var me,ye;Et([Ot("Unique identifier of the credentials record"),n(),s(),xt("design:type",String)],pe.prototype,"id",void 0),Et([Ot("PEM-encoded X.509 certificate for the identity"),n(),B(),xt("design:type",String)],pe.prototype,"certificate",void 0),Et([Ot("PEM-encoded root or intermediate certificate"),n(),B(),xt("design:type",String)],pe.prototype,"rootCertificate",void 0),Et([Ot("PEM-encoded private key"),n(),B(),xt("design:type",String)],pe.prototype,"privateKey",void 0),pe=Et([P(),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 o{constructor(t){super(t),this.type=ye.X509}};Et([Ot("Unique identifier of the identity"),s(),xt("design:type",String)],be.prototype,"id",void 0),Et([d(pe,{update:h.CASCADE,delete:h.CASCADE}),xt("design:type",pe)],be.prototype,"credentials",void 0),Et([n(),B(),u(),xt("design:type",String)],be.prototype,"mspId",void 0),Et([n(),B(),xt("design:type",String)],be.prototype,"type",void 0),be=Et([P(),xt("design:paramtypes",[Object])],be);class Ae{static{this.logger=new _t(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 g(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(M("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Gt(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=Gt.newCryptoSuite(t)),Ae.cryptoSuite):Gt.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 Vt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Yt.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){const r=await this.contentOfLoadFile(e,(async t=>{const{promises:e}=await g(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}));return{mspId:t,credentials:r}}static async getFirstDirFileName(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await g(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,(async t=>{const{promises:e}=await g(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)})),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ut.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await g(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"])}}const ve=new qt;var Ce,Se,Ee,xe,Ne;Jt.cryptoProvider.set(ve),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(Ce||(Ce={})),(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"})(Se||(Se={}));class Oe{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 Te{static{this.b58encoder=new Oe(Ce.BASE58)}static{this.logger=new _t(Te.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(M("Parsing certificate: {0}",t));const e=new Jt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(M("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=ve.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await ve.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map((t=>t.toString(16).padStart(2,"0"))).join("")}static async verify(t,e,r){const i=new 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,ve.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 Bt()?globalThis.window.crypto.subtle:ve.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=ve.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,Se.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:Se.KEY_ALGORYTHM,hash:Se.HASH,salt:i,iterations:Se.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*Se.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:Se.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:Se.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:Se.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class Ie extends J{constructor(t){super(t,Ie.name)}}class $e extends J{constructor(t){super(t,$e.name)}}class Re extends J{constructor(t){super(t,Re.name)}}class De extends f{constructor(t){super(t,De.name)}}class Fe extends J{constructor(t){super(t,Fe.name,500)}}class ke extends q{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ke.name,t,403)}}class _e extends q{constructor(t){super(_e.name,t,409)}}class Be extends J{constructor(t){super(t,Be.name,500)}}class Pe extends J{constructor(t){super(t,Pe.name,500)}}class je extends J{constructor(t){super(t,je.name,500)}}class Le extends J{constructor(t){super(t,Le.name,500)}}class Me extends J{constructor(t){super(t,Me.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(Ee||(Ee={})),(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 Ke extends Pt{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 J(`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 kt(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 De(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new f(i);default:return new De(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 W(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new W(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=jt.for(Ke,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=Te.fabricIdFromCertificate(r),o=Te.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=Ke.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 W("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 J(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new J(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class ze extends _{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new Y(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}Et([B(),xt("design:type",String)],ze.prototype,"affiliation",void 0),Et([K(1),xt("design:type",Array)],ze.prototype,"attrs",void 0),Et([B(),xt("design:type",String)],ze.prototype,"enrollmentID",void 0),Et([B(),xt("design:type",String)],ze.prototype,"enrollmentSecret",void 0),Et([z(0),xt("design:type",Number)],ze.prototype,"maxEnrollments",void 0),Et([B(),xt("design:type",String)],ze.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Ne||(Ne={}));let Ue=class extends _{constructor(t){super(t)}};Et([Ot("Stores the original timestamp of creation"),n(),p(),xt("design:type",Date)],Ue.prototype,"createdAt",void 0),Et([Ot("Stores the timestamp of the last update"),n(),m(),xt("design:type",Date)],Ue.prototype,"updatedAt",void 0),Et([Ot("Stores the version of the model"),n(),X(),xt("design:type",Number)],Ue.prototype,"version",void 0),Ue=Et([Tt(we),xt("design:paramtypes",[Object])],Ue);let He=class extends Ue{constructor(t){super(t)}};Et([Ot("Stores the creator"),n(),y(),xt("design:type",String)],He.prototype,"createdBy",void 0),Et([Ot("Stores the user that last updated the model"),n(),w(),xt("design:type",String)],He.prototype,"updatedBy",void 0),He=Et([Tt(we),xt("design:paramtypes",[Object])],He),_.prototype.isShared=function(){return _.isShared(this.constructor)},_.prototype.isPrivate=function(){return _.isPrivate(this.constructor)},_.prototype.segregate=function(){return _.segregate(this)},_.segregate=(t=>{if(!_.isTransient(t))return{model:t};const e=Nt.validatableProperties(t.constructor),r=Nt.get(t.constructor,Z.TRANSIENT),i=Nt.get(t.constructor,me.PRIVATE),s=Nt.get(t.constructor,me.SHARED),n={model:{},transient:{},privates:{},shared:{}},a=Object.keys(r||{}),o=Object.keys(i||{}),c=Object.keys(s||{}),l=_.pk(t.constructor);for(const r of e){const e=t[r],i=a.includes(r),s=o.includes(r),d=c.includes(r),h=r!==l||"string"!=typeof e||e.endsWith(",")?e:e+",";(i||s||d)&&(n.transient=n.transient||{},n.transient[r]=h),s&&(n.privates=n.privates||{},n.privates[r]=h),d&&(n.shared=n.shared||{},n.shared[r]=h),!i&&!s&&!d&&(n.model=n.model||{},n.model[r]=e)}return n.model=_.build(n.model,t.constructor.name),n}).bind(_),_.isPrivate=(t=>!!Nt.get("function"!=typeof t?t.constructor:t,me.PRIVATE)).bind(_),_.isShared=(t=>!!Nt.get("function"!=typeof t?t.constructor:t,me.SHARED)).bind(_),_.mirrored=(t=>Nt.get("function"!=typeof t?t.constructor:t,Nt.key(me.FABRIC,me.MIRROR))).bind(_),_.ownerOf=(t=>{const e=Nt.get(t.constructor,Nt.key(me.FABRIC,me.OWNED_BY));if(e)return t[e]}).bind(_),_.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,Nt.get(t,Nt.key(me.FABRIC,me.MIRROR)))).bind(_),_.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(_);const Ge="mirror:skip:";function Ye(t){if(t)return"string"==typeof t?t:t.getMSPID()}function Ve(){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 W("No tokens avaialble");if(a.length>1)throw new W("To many token available : "+a.length);if(a[0].owner!=s)throw new f(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Je(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 qe(){return It.for(me.OWNED_BY).define({decorator:()=>(t,e)=>$t(B(),tt(),et(),rt(Je),Rt(Nt.key(me.FABRIC,me.OWNED_BY),e))(t,e),args:[]}).apply()}async function Qe(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function We(){return It.for(me.TRANSACTION_ID).define({decorator:()=>(t,e)=>$t(B(),et(),rt(Qe),it(Qe),Rt(Nt.key(me.FABRIC,e,me.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function Xe(t,e,r){let i=e;if("string"!=typeof i)try{const s=_.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new J("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new J("No collection found model "+t.constructor.name);return i}async function Ze(t,e,r,i){const s=await Xe(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.create(i,t);t.logger.info(`Mirror for ${_.tableName(this.class)} created with ${_.pk(i)}: ${a[_.pk(i)]}`)}async function tr(t,e,r,i){const s=await Xe(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.update(i,t);t.logger.info(`Mirror for ${_.tableName(this.class)} updated with ${_.pk(i)}: ${a[_.pk(i)]}`)}async function er(t,e,r,i){const s=await Xe(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete(_.pk(i),t);t.logger.info(`Mirror for ${_.tableName(this.class)} deleted with ${_.pk(i)}: ${a[_.pk(i)]}`)}async function rr(t,e,r,i){const s=Ye(t.get("identity"));if(!s)return void t.logger.debug("Mirror read: No MSP ID available, using default read behavior");const n=await Xe(i,e.resolver,t),a=`${Ge}${n}`,o=t;!e.condition||e.condition(s)?(t.logger.info(`Mirror read: MSP ${s} matches condition, routing ALL reads exclusively to collection ${n}`),o.put("segregated",n),o.readFrom(n),o.put(a,!1)):o.put(a,!0)}function ir(t,e){return It.for(me.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return $t(Dt(Nt.key(me.FABRIC,me.MIRROR),i),fr(t),st(rr,i,{priority:30}),nt(Ze,i,{priority:95}),at(tr,i,{priority:95}),ot(er,i,{priority:95}))},args:[t,e]}).apply()}const sr=(t,e)=>{const r=e||("function"!=typeof t?_.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new J(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Lt(i.name)}${r?Lt(r):""}`};function nr(t){return(e,r)=>{const i=r||("function"!=typeof e?_.ownerOf(e):void 0),s="function"==typeof e?e:e.constructor;if(!i)throw new J(`Model ${s.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${t}${i?Lt(i):""}`}}const ar=(t,e)=>{const r=e||("function"!=typeof t?_.ownerOf(t):void 0);if(!r)throw new J(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Lt(r)}PrivateCollection`},or=35;async function cr(t,e,r,i){const s=Array.isArray(e)?e:[e],n=_.ownerOf(i)||Ye(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)}a.length>0&&t.readFrom(a)}async function lr(t,e,r,i){const s=Array.isArray(e)?e:[e],n=Array.isArray(r)?r:[r];if(n.length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const a=_.ownerOf(i)||Ye(t.get("identity"));if(!a)throw new Y("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.reduce(((e,r,n)=>{const o="string"==typeof s[n].collections?s[n].collections:s[n].collections(i,a,t);if(o!==c)throw new b(`Segregated data collection mismatch: ${o} vs ${c}`);return e[r]=i[r],e}),{});const l=_.segregate(i);t.writeTo(c,l)}async function dr(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const n=_.ownerOf(i)||Ye(t.get("identity"));if(!n)throw new Y("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),c=`${Ge}${o}`;t.getOrUndefined(c)||t.readFrom(o)}async function hr(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 J("Segregated data keys and metadata length mismatch");const o=_.ownerOf(i)||Ye(t.get("identity"));if(!o)throw new Y("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 b(`Segregated data collection mismatch: ${s} vs ${l}`)}));const d=_.segregate(i);t.writeTo(l,d)}async function ur(t,e,r,i){const s=Array.isArray(e)?e:[e];if((Array.isArray(r)?r:[r]).length!==s.length)throw new J("Segregated data keys and metadata length mismatch");const n=_.ownerOf(i)||Ye(t.get("identity"));if(!n)throw new Y("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 gr(t,e,r){return(i,s)=>{const n=[];if(s){const r="string"==typeof t?t:t.toString(),i=r+":data",s={collections:t},a={priority:or,group:r+":extract"};n.push(Ft(),ct(),((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,Z.TRANSIENT)||{},[i]:{}};Nt.set(n,Z.TRANSIENT,d)}),lt(dt.ALL,cr,s,a),rt(lr,{collections:t},{priority:95,group:i}),st(dr,{collections:t},{priority:95,group:i}),it(hr,{collections:t},{priority:95,group:i}),ht(ur,{collections:t},{priority:95,group:i}))}else{const s=Nt.validatableProperties(i);s?.forEach((s=>{r&&!r(s)||gr(t,e)(i.prototype,s)}))}return $t(...n)(i,s)}}function fr(t=ar){return It.for(me.PRIVATE).define({decorator:t=>gr(t,me.PRIVATE),args:[t]}).apply()}function pr(t){return It.for(me.SHARED).define({decorator:t=>gr(t,me.SHARED),args:[t]}).apply()}class mr extends j{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=Nt.modelName(t.constructor)}catch(t){r=void 0}e[L.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 _.relations(t).forEach((t=>{e[t]=i(e[t])})),e}deserialize(t){const e=JSON.parse(t),r=e[L.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return _.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function yr(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function wr(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 br(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new Ie(`Addition overflow: ${t} + ${e}`);return r}function Ar(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new Ie(`Subtraction overflow: ${t} - ${e}`);return r}function vr(t){if(!/^\d+$/.test(t))throw new Y(M("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new Y(M("Failed to parse: {0}","string is not a parsable integer"));return e}class Cr extends j{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(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[L.ANCHOR]=i||t.constructor.name),_.relations(t).forEach((t=>{r[t]=s.call(this,r[t])})),r}}class Sr extends A{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new J("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 J(`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:i}=(await this.logCtx(t,r.INITIALIZATION,!0)).for(this.initialize),[s]=t;if(!s)throw new J("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 kt(n,{trustedRoots:Buffer.from(h),verify:l},o),g=await this.getUser(s,i);return e.debug("CA user loaded: "+g.getName()),{config:s,client:u}}async getCertificates(t,e=!0,...r){t instanceof l?(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,U.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 De(t);const[,r,i]=e;switch(r){case"74":case"71":return new Q(i);case"20":return new f(i);default:return new De(i)}}async read(t,...e){const{log:r}=(await this.logCtx(e,U.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 W(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new W(`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=Te.fabricIdFromCertificate(s),c=Te.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=Sr.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 revoke(t,...e){const{log:r}=(await this.logCtx(e,"revoke",!0)).for(this.revoke);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new W("Could not find enrollment with id "+t);let s;try{s=await this.client.revoke({enrollmentID:i.id,reason:"User Deletion"},this.user)}catch(e){throw new J(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new J(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const Er=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),xr=new _t("fabric-fs");async function Nr(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Or(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await g(import("fs"));return await e.readFile(t)})(t)}async function Tr(t,e,r,i){xr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Gt(t),n=Gt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Ir(t,e){const r=await Nr(e,(async t=>{const{promises:e}=await g(import("fs")),r=await $r(t);return await e.readFile(r)}));return{mspId:t,credentials:r}}async function $r(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path"));return r(t,(await e.readdir(t))[0])}async function Rr(t){const{promises:e}=await g(import("fs")),{join:r}=await g(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function Dr(t){const e=await Nr(t,(async t=>{const{promises:e}=await g(import("fs")),r=await $r(t);return await e.readFile(r)})),r=await Fr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ut.newPrivateKeySigner(i)}async function Fr(t){let e;if(Bt())e=globalThis.crypto.subtle;else{const t=await g(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 J(t)}}class kr{static#t=null;static#e=!1;constructor(t){if(kr.#t||(kr.#t=new Xt.PKCS11,kr.#t.load(this.findHSMPKCS11Lib(t))),!kr.#e){try{kr.#t.C_Initialize()}catch(t){if(t.code!==Xt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}kr.#e=!0}}findHSMPKCS11Lib(t){const e=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];t&&e.push(t);for(const t of e)if(Zt.existsSync(t))return t;throw new Be("Unable to find PKCS11 library")}dispose(){kr.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Xt.CKU_USER},t);return this.assertNotEmpty(e.label,"label"),this.assertNotEmpty(e.pin,"pin"),this.assertNotEmpty(e.identifier,"identifier"),e}assertNotEmpty(t,e){if(!t||0===t.toString().trim().length)throw Error(e+" property must be provided")}findSlotForLabel(t){const e=kr.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find((e=>kr.#t.C_GetTokenInfo(e).label.trim()===t));if(!r)throw Error(`label ${t} cannot be found in the pkcs11 slot list`);return r}login(t,e,r){try{kr.#t.C_Login(t,e,r)}catch(t){if(t.code!==Xt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Xt.CKA_ID,value:r},{type:Xt.CKA_CLASS,value:e},{type:Xt.CKA_KEY_TYPE,value:Xt.CKK_EC}];kr.#t.C_FindObjectsInit(t,i);const s=kr.#t.C_FindObjects(t,1)[0];if(!s)throw kr.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return kr.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=kr.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Xt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Xt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw kr.#t.C_CloseSession(s),t}return{signer:async t=>{kr.#t.C_SignInit(s,{mechanism:Xt.CKM_ECDSA},n);const e=await kr.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*ee.Point.Fn.BYTES));return ee.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{kr.#t.C_CloseSession(s)}}}assertDefined(t){if(void 0===t)throw Error("required value was undefined");return t}getUncompressedPointOnCurve(t){const e=t.export({format:"jwk"}),r=Buffer.from(this.assertDefined(e.x),"base64url"),i=Buffer.from(this.assertDefined(e.y),"base64url"),s=Buffer.from("04","hex");return Buffer.concat([s,r,i])}getSKIFromCertificatePath(t){const e=t.endsWith(".pem")?t:te.join(t,"cert.pem"),r=Zt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new Yt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return Yt.createHash("sha256").update(r).digest()}}class _r extends v{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_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 J("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(r.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],i={},s={class:this.fromSelector,args:e,params:i},n=[C.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(C.SELECT,this.selectSelector.join(` ${C.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(n.push(C.ORDER_BY,this.orderBySelectors[0][0]),e.push(this.orderBySelectors[0][1])),s.method=Mt(n.join(" ")),s.params=i,this.prepared=s,this}processRecord(t,e,r,i){if(t[ft.ID]){const[,...e]=t[ft.ID].split(ft.SEPARATOR),s=e.join("_");return this.adapter.revert(t,this.fromSelector,c.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=_.pk(this.fromSelector),a=Nt.get(this.fromSelector,Nt.key(Z.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[ft.TABLE]={},r[ft.TABLE]=_.tableName(this.fromSelector);const i={selector:r};if(this.selectSelector&&(i.fields=this.selectSelector),this.whereCondition){const e=this.parseCondition(S.and(this.whereCondition,S.attribute(ft.TABLE).eq(i.selector[ft.TABLE]))).selector,r=Object.keys(e);if(1===r.length&&-1!==Object.values(yt).indexOf(r[0]))switch(r[0]){case yt.AND:e[yt.AND]=[...Object.values(e[yt.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===yt.AND?t.push(...e[i]):t.push(e),t}),[])],i.selector=e;break;case yt.OR:{const t={};t[yt.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][wt.BIGGER]=null)}}return this.limitSelector?i.limit=this.limitSelector:(t.warn("No limit selector defined. Using default couchdb limit of "+bt),i.limit=bt),this.offsetSelector&&(i.skip=this.offsetSelector),i}parseCondition(t){const{attr1:e,operator:r,comparison:i}=t;if(r===E.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][At(E.BIGGER_EQ)]=r,n[t][At(E.SMALLER_EQ)]=s,{selector:n}}let s={};if(-1===[N.AND,N.OR,E.NOT].indexOf(r))s[e]={},s[e][At(r)]=i;else if(r===E.NOT)s=this.parseCondition(e).selector,s[At(E.NOT)]={},s[At(E.NOT)][e.attr1]=i;else{const t=this.parseCondition(e).selector,n=this.parseCondition(i).selector;s=((t,e,r)=>{const i={selector:{}};return i.selector[t]=[e,r],i})(At(r),t,n).selector}return{selector:s}}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 ${_.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(t,e){if(!this.fromSelector)return;const r=vt(this.fromSelector,t,e);if(!r.length)return;const i=r[0],s=_.tableName(this.fromSelector),n=Ct(s,i.attribute,t,i),a=i.ddoc||St(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 Br extends i{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new b("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 Pr;class jr extends O{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new ae}static{this.log=jt.for(jr)}constructor(t,e){super(Object.assign({},t,{evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),we,e),this.serializer=jr.serializer}Statement(t){return new _r(this,t)}Paginator(t,e,r){return new Br(this,t,e,r)}async flags(t,e,r,...i){return Object.assign(await super.flags(t,e,Object.assign({},this.config,r),...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=>_.tableName(t))):_.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 l||(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 jr.decoder.decode(t)}repository(){return re}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=_.tableName(t),a={};return a[ft.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=_.tableName(t);if(e.length!==r.length)throw new J("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[ft.TABLE]=s,Object.assign(i,r[e]),i}));return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=_.tableName(t);if(e.length!==r.length)throw new J("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map((()=>{const t={};return t[ft.TABLE]=s,t}));return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new J("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=_.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ut.CREATE_ALL,[JSON.stringify(r.map((e=>this.serializer.serialize(e,t.name))))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map((t=>JSON.parse(t)))}catch(t){throw new V(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=_.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,ut.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 V(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new J("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=_.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ut.UPDATE_ALL,[JSON.stringify(r.map((e=>this.serializer.serialize(e,t.name))))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map((t=>JSON.parse(t)))}catch(t){throw new V(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=_.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,ut.DELETE_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 V(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=_.segregate(t);return t[r.METADATA]&&(i.silly("Passing along persistence metadata for "+t[r.METADATA]),Object.defineProperty(s.model,r.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[r.METADATA]})),{record:s.model,model:s.model,id:t[_.pk(t.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(t,e,r,i,...s){const{log:n}=this.logCtx(s,this.revert);return i&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach((([r,i])=>{if(r in t&&void 0!==t[r])throw new J(`Transient property ${r} already exists on model ${"string"==typeof e?e:e.name}. should be impossible`);t[r]=i}))),new e(t)}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=_.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,U.CREATE,[this.serializer.serialize(r,t.name)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=_.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,U.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=_.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[ft.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.updateAll);a.info("CLIENT UPDATE class : "+typeof t);const c=_.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,U.UPDATE,[this.serializer.serialize(r,t.name||t)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=_.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,U.DELETE,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}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 "+_.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 V("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return _.isModel(t)?c.map((t=>_.build(t))):c}return l=c,_.isModel(l)?_.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 V("Failed to process view result: "+t)}return o}getClient(){return this._client||(this._client=jr.getClient(this.config)),this._client}async Gateway(t){return jr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return jr.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:s};return await l.call(c,e,d)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(t){return jr.parseError(t)}async submitTransaction(t,e,r,i,s,n){return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=jt.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(Zt.readFileSync(r,"utf8"))}catch(t){throw new J(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Qt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Wt(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=jt.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Ir(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new kr(e.hsm.library),r=t.getSKIFromCertificatePath(e.certCertOrDirectoryPath),i=t.newSigner({label:e.hsm.tokenLabel,pin:e.hsm.pin+"",identifier:r});n=i.signer,a=i.close}else n=await Dr(e.keyCertOrDirectoryPath);const o={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 c=Ht(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new jr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new je(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Me(t):e.includes("PHANTOM_READ_CONFLICT")?new Le(t):t instanceof Error&&t.code&&9===t.code?new Pe(t):e.includes(W.name)?new W(t):e.includes(Q.name)?new Q(t):e.includes(gt.name)?new gt(t):e.includes(x.name)?new x(t):e.includes(T.name)?new T(t):e.includes(b.name)?new b(t):e.includes(I.name)?new I(t):e.includes($.name)?new $(t):e.includes(f.name)?new f(t):e.includes(R.name)?new R(t):e.includes(F.name)?new F(t):e.includes(V.name)?new V(t):new J(t)}}Et([Kt(),zt(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,Object,Object,l]),xt("design:returntype",Promise)],jr.prototype,"create",null),Et([Kt(),zt(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,l]),xt("design:returntype",Promise)],jr.prototype,"read",null),Et([Kt(),zt(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,Object,Object,l]),xt("design:returntype",Promise)],jr.prototype,"update",null),Et([Kt(),zt(),xt("design:type",Function),xt("design:paramtypes",[Object,Object,l]),xt("design:returntype",Promise)],jr.prototype,"delete",null),Et([Kt(),xt("design:type",Function),xt("design:paramtypes",[Object,"function"==typeof(Pr="undefined"!=typeof D&&D)?Pr:Object,Object,l]),xt("design:returntype",Promise)],jr.prototype,"raw",null),Et([Kt(),xt("design:type",Function),xt("design:paramtypes",[String,String,Object,l]),xt("design:returntype",Promise)],jr.prototype,"view",null),jr.decoration(),O.setCurrent(we);class Lr extends k{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 jr))throw new b("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}=O.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new J("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:_.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new J('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new J("No adapter found. should be impossible");const e=t||await this.adapter.context(U.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||_),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}=wr(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?_.get(i):_.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 J("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},_),{ctx:e}=this.logCtx([t],this.initialize),r=(await jr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new J("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}jr&&(jr._baseDispatch=Lr);const Mr="##VERSION##",Kr="##PACKAGE##";Nt.registerLibrary(Kr,Mr);export{Re as AllowanceError,Ce as BASE_ALPHABET,$e as BalanceError,Oe as BaseEncoder,Se as CRYPTO,ae as ClientSerializer,Ae as CoreUtils,Te as CryptoUtils,Er as DefaultFabricClientFlags,mr as DeterministicSerializer,Ne as ERC20Events,Pe as EndorsementError,Me as EndorsementPolicyError,Ue as FabricBaseModel,jr as FabricClientAdapter,Lr as FabricClientDispatch,re as FabricClientRepository,oe as FabricERC20ClientRepository,Ke as FabricEnrollmentService,we as FabricFlavour,He as FabricIdentifiedBaseModel,Sr as FabricIdentityService,me as FabricModelKeys,xe as HFCAIdentityAttributes,Ee as HFCAIdentityType,be as Identity,pe as IdentityCredentials,ye as IdentityType,ar as ImplicitPrivateCollection,Fe as MissingContextError,Be as MissingPKCSS11Lib,sr as ModelCollection,je as MvccReadConflictError,nr as NamespaceCollection,_e as NotInitializedError,Ie as OverflowError,Ve as Owner,Kr as PACKAGE_NAME,Le as PhantomReadConflictError,De as RegistrationError,ze as RegistrationRequestBuilder,or as SEGREGATED_COLLECTION_EXTRACTION_PRIORITY,Cr as SimpleDeterministicSerializer,ke as UnauthorizedPrivateDataAccess,Mr as VERSION,br as add,Nr as contentOfLoadFile,Ze as createMirrorHandler,er as deleteMirrorHandler,Xe as evalMirrorMetadata,Fr as extractPrivateKey,cr as extractSegregatedCollections,yr as generateFabricEventName,de as generateModelDesignDocs,le as generateModelIndexes,Tr as getCAUser,$r as getFirstDirFileName,Rr as getFirstDirFileNameContent,Ir as getIdentity,Dr as getSigner,ir as mirror,qe as ownedBy,Je as ownedByOnCreate,wr as parseEventName,fr as privateData,Or as readFile,rr as readMirrorHandler,he as readModelFile,ue as readModelFolders,vr as safeParseInt,lr as segregatedDataOnCreate,ur as segregatedDataOnDelete,dr as segregatedDataOnRead,hr as segregatedDataOnUpdate,pr as sharedData,Ar as sub,We as transactionId,Qe as transactionIdOnCreate,tr as updateMirrorHandler,fe as writeDesignDocs,ge as writeIndexes};
|
|
2
2
|
//# sourceMappingURL=for-fabric.js.map
|