@decaf-ts/for-fabric 0.1.62 → 0.1.64
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 +49 -28
- package/lib/cli-module.js.map +1 -1
- package/lib/cli-utils.cjs +63 -1
- package/lib/cli-utils.d.ts +2 -0
- package/lib/cli-utils.js.map +1 -1
- package/lib/client/FabricClientAdapter.cjs +2 -37
- package/lib/client/FabricClientAdapter.d.ts +1 -2
- package/lib/client/FabricClientAdapter.js.map +1 -1
- package/lib/client/constants.cjs +1 -2
- package/lib/client/constants.js.map +1 -1
- package/lib/esm/cli-module.js +50 -29
- package/lib/esm/cli-module.js.map +1 -1
- package/lib/esm/cli-utils.d.ts +2 -0
- package/lib/esm/cli-utils.js +59 -1
- package/lib/esm/cli-utils.js.map +1 -1
- package/lib/esm/client/FabricClientAdapter.d.ts +1 -2
- package/lib/esm/client/FabricClientAdapter.js +2 -37
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/client/constants.js +1 -2
- package/lib/esm/client/constants.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +3 -3
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 p,AuthorizationError as g,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as C,DefaultAdapterFlags as A,Statement as v,QueryClause as S,Adapter as E,QueryError as x,PagingError as N,MigrationError as T,ObserverError as I,ForbiddenError as O,ConnectionError as R,Dispatch as $}from"@decaf-ts/core";import{Model as k,required as F,model as B,JSONSerializer as _,ModelKeys as P,stringFormat as j,minlength as K,min as L}from"@decaf-ts/decorator-validation";import{OperationKeys as z,enforceDBDecorators as M,reduceErrorsToPrint as H,ValidationError as U,SerializationError as Y,InternalError as G,BaseError as V,ConflictError as J,NotFoundError as q,version as W,DBKeys as X,readonly as Q,onCreate as Z,onUpdate as tt,afterCreate as et,afterUpdate as rt,afterDelete as it,transient as st,onRead as nt,onDelete as at,BulkCrudOperationKeys as ot,BadRequestError as ct}from"@decaf-ts/db-decorators";import{CouchDBKeys as lt}from"@decaf-ts/for-couchdb";import{__decorate as dt,__metadata as ht}from"tslib";import{Metadata as ut,description as pt,uses as gt,Decoration as ft,apply as mt,propMetadata as yt,metadata as wt,prop as bt}from"@decaf-ts/decoration";import Ct from"fabric-ca-client";import{MiniLogger as At,isBrowser as vt,LoggedClass as St,Logging as Et,toPascalCase as xt,toCamelCase as Nt,debug as Tt,final as It}from"@decaf-ts/logging";import{signers as Ot,connect as Rt}from"@hyperledger/fabric-gateway";import{User as $t}from"fabric-common";import kt,{X509Certificate as Ft}from"crypto";import*as Dt from"@peculiar/x509";import{Crypto as Bt}from"@peculiar/webcrypto";import*as _t from"@grpc/grpc-js";import{Client as Pt}from"@grpc/grpc-js";import jt from"pkcs11js";import Kt from"fs";import Lt from"path";import{p256 as zt}from"@noble/curves/nist";class Mt 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})}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 ${k.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 ${k.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 ${k.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 ${k.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[lt.TABLE]&&t[lt.TABLE]===k.tableName(this.class)?new this.class(t):t):c[lt.TABLE]&&c[lt.TABLE]===k.tableName(this.class)?new this.class(c):i.isSerializedPage(c)?Object.assign(c,{data:c.data.map(t=>new this.class(t))}):c}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 ${k.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 ${k.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,z.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 M(this,r,t,z.CREATE,z.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=H(i);if(s)throw new U(s)}return[t,...i]}async createAll(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 ${k.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 ${k.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 Ht=class extends o{constructor(t){super(t)}};dt([s({type:String}),ht("design:type",String)],Ht.prototype,"name",void 0),dt([n(),F(),ht("design:type",String)],Ht.prototype,"owner",void 0),dt([n(),F(),ht("design:type",String)],Ht.prototype,"symbol",void 0),dt([n(),F(),ht("design:type",Number)],Ht.prototype,"decimals",void 0),Ht=dt([a("erc20_tokens"),B(),ht("design:paramtypes",[Object])],Ht);let Ut=class extends o{constructor(t){super(t)}};dt([s({type:String}),ht("design:type",String)],Ut.prototype,"id",void 0),dt([n(),F(),ht("design:type",String)],Ut.prototype,"token",void 0),dt([n(),F(),ht("design:type",Number)],Ut.prototype,"balance",void 0),dt([n(),ht("design:type",String)],Ut.prototype,"captive",void 0),Ut=dt([a("erc20_wallets"),B(),ht("design:paramtypes",[Object])],Ut);let Yt=class extends o{constructor(t){super(t)}};dt([s({type:String}),n(),F(),ht("design:type",String)],Yt.prototype,"owner",void 0),dt([n(),F(),ht("design:type",String)],Yt.prototype,"spender",void 0),dt([n(),F(),ht("design:type",Number)],Yt.prototype,"value",void 0),Yt=dt([a("erc20_allowances"),B(),ht("design:paramtypes",[Object])],Yt);class Gt extends _{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=ut.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new Y("Could not find metadata for "+t.constructor.name);i=e}return r[P.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[P.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return k.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Vt extends Mt{static{this.serializer=new Gt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new G("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?k.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue(k.sequenceFor(t).type,e)):c.parseValue(k.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Vt.decoder.decode(t)}constructor(t){super(t,Ut),this.serializer=Vt.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",[Vt.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 Jt(t,e,r){return[...t.map(t=>t===lt.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(ut.splitter)}function qt(t,e,r,i){const s=e.pop();s&&s!==lt.TABLE?e.push(s):s===lt.TABLE&&e.unshift(s);const n=Jt(e,r,i);let a=[...e,...i||[]];r&&(a=a.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const o={index:{fields:a},name:n,ddoc:n,type:"json"};t[n]=o}function Wt(t,e){const r=Jt([lt.TABLE]),i=e||{};i[r]={index:{fields:[lt.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=k.indexes(t);for(const t of Object.keys(n))for(const[,e]of Object.entries(n[t])){const r=e.directions,i=e.compositions,n=[t,lt.TABLE];qt(s,n),i&&i.length&&qt(s,n,void 0,i),r&&r.length&&r.forEach(t=>{qt(s,n,t),i&&i.length&&qt(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Xt(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 k}catch(t){return!1}})}async function Qt(...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(...Xt(e))}return r}function Zt(t,e=process.cwd(),r){const i=require("fs"),s=require("path");function n(t){const e=s.dirname(t);if(i.existsSync(e))return!0;n(e),i.mkdirSync(e)}t.forEach(t=>{const a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));n(a),i.writeFileSync(a,JSON.stringify(t,void 0,2))})}let te=class extends o{constructor(t){super(t)}};var ee,re;dt([pt("Unique identifier of the credentials record"),n(),s(),ht("design:type",String)],te.prototype,"id",void 0),dt([pt("PEM-encoded X.509 certificate for the identity"),n(),F(),ht("design:type",String)],te.prototype,"certificate",void 0),dt([pt("PEM-encoded root or intermediate certificate"),n(),F(),ht("design:type",String)],te.prototype,"rootCertificate",void 0),dt([pt("PEM-encoded private key"),n(),F(),ht("design:type",String)],te.prototype,"privateKey",void 0),te=dt([B(),ht("design:paramtypes",[Object])],te),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(ee||(ee={})),(t=>{t.X509="X.509"})(re||(re={}));const ie="hlf-fabric";let se=class extends o{constructor(t){super(t),this.type=re.X509}};dt([pt("Unique identifier of the identity"),s(),ht("design:type",String)],se.prototype,"id",void 0),dt([d(te,{update:h.CASCADE,delete:h.CASCADE}),ht("design:type",te)],se.prototype,"credentials",void 0),dt([n(),F(),u(),ht("design:type",String)],se.prototype,"mspId",void 0),dt([n(),F(),ht("design:type",String)],se.prototype,"type",void 0),se=dt([B(),ht("design:paramtypes",[Object])],se);class ne{static{this.logger=new At(ne.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(j("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new $t(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?(ne.cryptoSuite||(ne.cryptoSuite=$t.newCryptoSuite(t)),ne.cryptoSuite):$t.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 Ft(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return kt.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 p(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 p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await p(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ot.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await p(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 ae=new Bt;var oe,ce,le,de,he;Dt.cryptoProvider.set(ae),(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-_.!~"})(oe||(oe={})),(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"})(ce||(ce={}));class ue{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 pe{static{this.b58encoder=new ue(oe.BASE58)}static{this.logger=new At(pe.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(j("Parsing certificate: {0}",t));const e=new Dt.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(j("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=ae.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 ae.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 Dt.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,ae.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Dt.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 vt()?globalThis.window.crypto.subtle:ae.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=ae.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,ce.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:ce.KEY_ALGORYTHM,hash:ce.HASH,salt:i,iterations:ce.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*ce.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:ce.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:ce.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:ce.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class ge extends G{constructor(t){super(t,ge.name)}}class fe extends G{constructor(t){super(t,fe.name)}}class me extends G{constructor(t){super(t,me.name)}}class ye extends g{constructor(t){super(t,ye.name)}}class we extends G{constructor(t){super(t,we.name,500)}}class be extends V{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(be.name,t,403)}}class Ce extends V{constructor(t){super(Ce.name,t,409)}}class Ae extends G{constructor(t){super(t,Ae.name,500)}}class ve extends G{constructor(t){super(t,ve.name,500)}}class Se extends G{constructor(t){super(t,Se.name,500)}}class Ee extends G{constructor(t){super(t,Ee.name,500)}}class xe extends G{constructor(t){super(t,xe.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(le||(le={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(de||(de={}));class Ne extends St{constructor(t){ne.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await ne.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new G(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await ne.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await ne.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await ne.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new Ct(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 ye(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ye(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 q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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=Et.for(Ne,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=pe.fabricIdFromCertificate(r),o=pe.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new se({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=Ne.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 q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Te extends k{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new U(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}dt([F(),ht("design:type",String)],Te.prototype,"affiliation",void 0),dt([K(1),ht("design:type",Array)],Te.prototype,"attrs",void 0),dt([F(),ht("design:type",String)],Te.prototype,"enrollmentID",void 0),dt([F(),ht("design:type",String)],Te.prototype,"enrollmentSecret",void 0),dt([L(0),ht("design:type",Number)],Te.prototype,"maxEnrollments",void 0),dt([F(),ht("design:type",String)],Te.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(he||(he={}));let Ie=class extends k{constructor(t){super(t)}};dt([pt("Stores the original timestamp of creation"),n(),f(),ht("design:type",Date)],Ie.prototype,"createdAt",void 0),dt([pt("Stores the timestamp of the last update"),n(),m(),ht("design:type",Date)],Ie.prototype,"updatedAt",void 0),dt([pt("Stores the version of the model"),n(),W(),ht("design:type",Number)],Ie.prototype,"version",void 0),Ie=dt([gt(ie),ht("design:paramtypes",[Object])],Ie);let Oe=class extends Ie{constructor(t){super(t)}};function Re(){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 q("No tokens avaialble");if(a.length>1)throw new q("To many token available : "+a.length);if(a[0].owner!=s)throw new g(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function $e(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 ke(){return ft.for(ee.OWNED_BY).define({decorator:()=>(t,e)=>mt(F(),Q(),Z($e),yt(ut.key(ee.FABRIC,ee.OWNED_BY),e))(t,e),args:[]}).apply()}async function Fe(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function De(){return ft.for(ee.TRANSACTION_ID).define({decorator:()=>(t,e)=>mt(F(),Q(),Z(Fe),tt(Fe),yt(ut.key(ee.FABRIC,e,ee.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function Be(t,e,r){let i=e;if("string"!=typeof i)try{const s=k.ownerOf(t)||r.get("stub").getCreator().toString();e&&"function"==typeof e&&(i=await e(t,s,r))}catch(t){throw new G("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new G("No collection found model "+t.constructor.name);return i}async function _e(t,e,r,i){const s=await Be(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 ${k.tableName(this.class)} created with ${k.pk(i)}: ${a[k.pk(i)]}`)}async function Pe(t,e,r,i){const s=await Be(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 ${k.tableName(this.class)} updated with ${k.pk(i)}: ${a[k.pk(i)]}`)}async function je(t,e,r,i){const s=await Be(i,e.resolver,t),n=this.override(Object.assign({},this._overrides,{segregate:s,ignoreValidation:!0,ignoreHandlers:!0})),a=await n.delete(k.pk(i),t);t.logger.info(`Mirror for ${k.tableName(this.class)} deleted with ${k.pk(i)}: ${a[k.pk(i)]}`)}function Ke(t,e){return ft.for(ee.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return mt(wt(ut.key(ee.FABRIC,ee.MIRROR),i),Ve(t),et(_e,i,{priority:95}),rt(Pe,i,{priority:95}),it(je,i,{priority:95}))},args:[t,e]}).apply()}dt([pt("Stores the creator"),n(),y(),ht("design:type",String)],Oe.prototype,"createdBy",void 0),dt([pt("Stores the user that last updated the model"),n(),w(),ht("design:type",String)],Oe.prototype,"updatedBy",void 0),Oe=dt([gt(ie),ht("design:paramtypes",[Object])],Oe),k.prototype.isShared=function(){return k.isShared(this.constructor)},k.prototype.isPrivate=function(){return k.isPrivate(this.constructor)},k.prototype.segregate=function(){return k.segregate(this)},k.segregate=(t=>{if(!k.isTransient(t))return{model:t};const e=ut.validatableProperties(t.constructor),r=ut.get(t.constructor,X.TRANSIENT),i=ut.get(t.constructor,ee.PRIVATE),s=ut.get(t.constructor,ee.PRIVATE),n={model:{},transient:{},private:{},shared:{}},a=Object.keys(r),o=Object.keys(i),c=Object.keys(s);for(const r of e){const e=a.includes(r),i=o.includes(r),s=c.includes(r);e?(n.transient=n.transient||{},n.transient[r]=t[r],i&&(n.private=n.private||{},n.private[r]=t[r]),s&&(n.shared=n.shared||{},n.shared[r]=t[r])):(n.model=n.model||{},n.model[r]=t[r])}return n.model=k.build(n.model,t.constructor.name),n}).bind(k),k.isPrivate=(t=>!!ut.get("function"!=typeof t?t.constructor:t,ee.PRIVATE)).bind(k),k.isShared=(t=>!!ut.get("function"!=typeof t?t.constructor:t,ee.SHARED)).bind(k),k.mirrored=(t=>ut.get("function"!=typeof t?t.constructor:t,ut.key(ee.FABRIC,ee.MIRROR))).bind(k),k.ownerOf=(t=>{const e=ut.get(t.constructor,ut.key(ee.FABRIC,ee.OWNED_BY));if(e)return t[e]}).bind(k),k.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,ut.get(t,ut.key(ee.FABRIC,ee.MIRROR)))).bind(k),k.collectionsFor=(t=>{const e=[ee.PRIVATE],r=[ee.SHARED],i=ut.key(...e),s=ut.key(...r),n="function"==typeof t?t:t.constructor,a=ut.get(n,i),o=ut.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind(k);const Le=(t,e)=>{const r=e||("function"!=typeof t?k.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new G(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${xt(i.name)}${e?xt(e):""}`},ze=(t,e)=>{const r=e||("function"!=typeof t?k.ownerOf(t):void 0);if(!r)throw new G(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${xt(r)}PrivateCollection`};async function Me(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=k.ownerOf(i);if(!s)throw new U("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:n(i,s,t),o=r.reduce((r,n,o)=>{const c="string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t);if(c!==a)throw new b(`Segregated data collection mismatch: ${c} vs ${a}`);return r[n]=i[n],r},{}),c=new this.class(o),l=await this.override({segregated:a,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(c,t);Object.assign(i,l)}async function He(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=k.ownerOf(i);if(!s)throw new U("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:await n(i,s,t);r.reduce((r,n,o)=>(("string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t))!==a||(r[n]=i[n]),r),{})}async function Ue(t,e,r,i,s){}async function Ye(t,e,r,i){}function Ge(t,e,r){return(i,s)=>{const n=[];return s?n.push(bt(),st(),(r,i)=>{const s=ut.key(e,i),n=r.constructor,a=ut.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],ut.set(n,s,a);const c=ut.get(n,e)||{};new Set(c.collections||[]).add(t),a.collections=[...o],ut.set(n,e,a)},Z(Me,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),nt(He,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),tt(Ue,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),at(Ye,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})):ut.properties(i)?.forEach(s=>{r&&!r(s)||Ge(t,e)(i.prototype,s)}),mt(...n)(i,s)}}function Ve(t=ze){return ft.for(ee.PRIVATE).define({decorator:t=>Ge(t,ee.PRIVATE),args:[t]}).apply()}function Je(t){return ft.for(ee.SHARED).define({decorator:t=>Ge(t,ee.SHARED),args:[t]}).apply()}class qe extends _{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=ut.modelName(t.constructor)}catch(t){r=void 0}e[P.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 k.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[P.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return k.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function We(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function Xe(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 Qe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new ge(`Addition overflow: ${t} + ${e}`);return r}function Ze(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new ge(`Subtraction overflow: ${t} - ${e}`);return r}function tr(t){if(!/^\d+$/.test(t))throw new U(j("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new U(j("Failed to parse: {0}","string is not a parsable integer"));return e}class er extends _{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=ut.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[P.ANCHOR]=i||t.constructor.name),k.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class rr extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new G("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 ne.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new G(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await ne.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await ne.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=await this.logCtx(t,this.initialize,!0),[i]=t;if(!i)throw new G("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:c}=n,l=o[0];e.debug(`Retrieving CA certificate from ${l}. cwd: ${process.cwd()}`);const d=await ne.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new Ct(s,{trustedRoots:Buffer.from(d),verify:c},a),u=await this.getUser(i,r);return e.debug("CA user loaded: "+u.getName()),{config:i,client:h}}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,this.getCertificates,!0);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 ye(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ye(i)}}async read(t,...e){const{log:r}=await this.logCtx(e,this.read,!0);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`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,this.register,!0);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=pe.fabricIdFromCertificate(s),c=pe.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new se({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,this.enroll,!0);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=rr.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,this.registerAndEnroll,!0),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,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new q("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 G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const ir=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60},A),sr=new At("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 ar(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function or(t,e,r,i){sr.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new $t(t),n=$t.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function cr(t,e){const r=await nr(e,async t=>{const{promises:e}=await p(import("fs")),r=await lr(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function lr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function dr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function hr(t){const e=await nr(t,async t=>{const{promises:e}=await p(import("fs")),r=await lr(t);return await e.readFile(r)}),r=await ur(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Ot.newPrivateKeySigner(i)}async function ur(t){let e;if(vt())e=globalThis.crypto.subtle;else{const t=await p(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 G(t)}}class pr{static#t=null;static#e=!1;constructor(t){if(pr.#t||(pr.#t=new jt.PKCS11,pr.#t.load(this.findHSMPKCS11Lib(t))),!pr.#e){try{pr.#t.C_Initialize()}catch(t){if(t.code!==jt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}pr.#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(Kt.existsSync(t))return t;throw new Ae("Unable to find PKCS11 library")}dispose(){pr.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:jt.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=pr.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>pr.#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{pr.#t.C_Login(t,e,r)}catch(t){if(t.code!==jt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:jt.CKA_ID,value:r},{type:jt.CKA_CLASS,value:e},{type:jt.CKA_KEY_TYPE,value:jt.CKK_EC}];pr.#t.C_FindObjectsInit(t,i);const s=pr.#t.C_FindObjects(t,1)[0];if(!s)throw pr.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return pr.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=pr.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,jt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,jt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw pr.#t.C_CloseSession(s),t}return{signer:async t=>{pr.#t.C_SignInit(s,{mechanism:jt.CKM_ECDSA},n);const e=await pr.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*zt.Point.Fn.BYTES));return zt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{pr.#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:Lt.join(t,"cert.pem"),r=Kt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new kt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return kt.createHash("sha256").update(r).digest()}}class gr 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 G("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=[S.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);n.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&n.push(S.SELECT,this.selectSelector.join(` ${S.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(S.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=Nt(n.join(" ")),s.params=i,this.prepared=s,this}build(){throw new b("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(t,...e){throw new b("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class fr 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 mr;class yr extends E{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Gt}static{this.log=Et.for(yr)}constructor(t,e){super(t,ie,e),this.serializer=yr.serializer}Statement(t){return new gr(this,t)}Paginator(t,e,r){return new fr(this,t,e,r)}flags(t,e,r,...i){return super.flags(t,e,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=>k.tableName(t)):k.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({},e,s.toOverrides()):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...i,s);if(s){if(!(s instanceof this.Context))return(new this.Context).accumulate({...s.cache,...n,parentContext:s});const e=s.get("operation"),i=s.get("affectedTables");return e!==t||r!==i?(new this.Context).accumulate({...s.cache,...n,parentContext:s}):s.accumulate(n)}return(new this.Context).accumulate({...ir,...n})}decode(t){return yr.decoder.decode(t)}repository(){return Mt}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=k.tableName(t),a={};return a[lt.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=k.tableName(t);if(e.length!==r.length)throw new G("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[lt.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=k.tableName(t);if(e.length!==r.length)throw new G("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[lt.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=k.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ot.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 Y(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=k.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,ot.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 Y(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=k.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,ot.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 Y(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=k.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,ot.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 Y(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=k.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[k.pk(t.constructor)],transient:s.transient,private:s.private,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)throw new G(`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=k.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=k.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,z.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=k.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[lt.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=k.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.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=k.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,z.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 "+k.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 Y("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return k.isModel(t)?c.map(t=>k.build(t)):c}return l=c,k.isModel(l)?k.build(l):l;var l}getClient(){return this._client||(this._client=yr.getClient(this.config)),this._client}async Gateway(t){return yr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return yr.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s,n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData: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 yr.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=Et.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(Kt.readFileSync(r,"utf8"))}catch(t){throw new G(`Failed to read the tls certificate from ${r}: ${t}`)}const i=_t.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Pt(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=Et.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await cr(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new pr(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 hr(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=Rt(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new yr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new Se(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new xe(t):e.includes("PHANTOM_READ_CONFLICT")?new Ee(t):t instanceof Error&&t.code&&9===t.code?new ve(t):e.includes(q.name)?new q(t):e.includes(J.name)?new J(t):e.includes(ct.name)?new ct(t):e.includes(x.name)?new x(t):e.includes(N.name)?new N(t):e.includes(b.name)?new b(t):e.includes(T.name)?new T(t):e.includes(I.name)?new I(t):e.includes(g.name)?new g(t):e.includes(O.name)?new O(t):e.includes(R.name)?new R(t):e.includes(Y.name)?new Y(t):new G(t)}}dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"create",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"read",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"update",null),dt([Tt(),It(),ht("design:type",Function),ht("design:paramtypes",[Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"delete",null),dt([Tt(),ht("design:type",Function),ht("design:paramtypes",[Object,"function"==typeof(mr="undefined"!=typeof D&&D)?mr:Object,Object,l]),ht("design:returntype",Promise)],yr.prototype,"raw",null),yr.decoration(),E.setCurrent(ie);class wr extends ${constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof yr))throw new 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}=E.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new G("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:k.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new G('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new G("No adapter found. should be impossible");const e=t||await this.adapter.context(z.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||k),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}=Xe(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?k.get(i):k.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 G("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},k),{ctx:e}=this.logCtx([t],this.initialize),r=(await yr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new G("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}yr&&(yr._baseDispatch=wr);const br="##VERSION##",Cr="##PACKAGE##";ut.registerLibrary(Cr,br);export{me as AllowanceError,oe as BASE_ALPHABET,fe as BalanceError,ue as BaseEncoder,ce as CRYPTO,Gt as ClientSerializer,ne as CoreUtils,pe as CryptoUtils,ir as DefaultFabricClientFlags,qe as DeterministicSerializer,he as ERC20Events,ve as EndorsementError,xe as EndorsementPolicyError,Ie as FabricBaseModel,yr as FabricClientAdapter,wr as FabricClientDispatch,Mt as FabricClientRepository,Vt as FabricERC20ClientRepository,Ne as FabricEnrollmentService,ie as FabricFlavour,Oe as FabricIdentifiedBaseModel,rr as FabricIdentityService,ee as FabricModelKeys,de as HFCAIdentityAttributes,le as HFCAIdentityType,se as Identity,te as IdentityCredentials,re as IdentityType,ze as ImplicitPrivateCollection,we as MissingContextError,Ae as MissingPKCSS11Lib,Le as ModelCollection,Se as MvccReadConflictError,Ce as NotInitializedError,ge as OverflowError,Re as Owner,Cr as PACKAGE_NAME,Ee as PhantomReadConflictError,ye as RegistrationError,Te as RegistrationRequestBuilder,er as SimpleDeterministicSerializer,be as UnauthorizedPrivateDataAccess,br as VERSION,Qe as add,nr as contentOfLoadFile,_e as createMirrorHandler,je as deleteMirrorHandler,Be as evalMirrorMetadata,ur as extractPrivateKey,We as generateFabricEventName,Wt as generateModelIndexes,or as getCAUser,lr as getFirstDirFileName,dr as getFirstDirFileNameContent,cr as getIdentity,hr as getSigner,Ke as mirror,ke as ownedBy,$e as ownedByOnCreate,Xe as parseEventName,Ve as privateData,ar as readFile,Xt as readModelFile,Qt as readModelFolders,tr as safeParseInt,Me as segregatedDataOnCreate,Ye as segregatedDataOnDelete,He as segregatedDataOnRead,Ue as segregatedDataOnUpdate,Je as sharedData,Ze as sub,De as transactionId,Fe as transactionIdOnCreate,Pe as updateMirrorHandler,Zt 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 p,AuthorizationError as g,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as C,Statement as A,QueryClause as v,Adapter as S,QueryError as E,PagingError as x,MigrationError as N,ObserverError as T,ForbiddenError as I,ConnectionError as O,Dispatch as R}from"@decaf-ts/core";import{Model as $,required as k,model as F,JSONSerializer as B,ModelKeys as _,stringFormat as P,minlength as j,min as K}from"@decaf-ts/decorator-validation";import{OperationKeys as L,enforceDBDecorators as z,reduceErrorsToPrint as M,ValidationError as H,SerializationError as U,InternalError as Y,BaseError as G,ConflictError as V,NotFoundError as J,version as q,DBKeys as W,readonly as X,onCreate as Q,onUpdate as Z,afterCreate as tt,afterUpdate as et,afterDelete as rt,transient as it,onRead as st,onDelete as nt,BulkCrudOperationKeys as at,BadRequestError as ot}from"@decaf-ts/db-decorators";import{CouchDBKeys as ct}from"@decaf-ts/for-couchdb";import{__decorate as lt,__metadata as dt}from"tslib";import{Metadata as ht,description as ut,uses as pt,Decoration as gt,apply as ft,propMetadata as mt,metadata as yt,prop as wt}from"@decaf-ts/decoration";import bt from"fabric-ca-client";import{MiniLogger as Ct,isBrowser as At,LoggedClass as vt,Logging as St,toPascalCase as Et,toCamelCase as xt,debug as Nt,final as Tt}from"@decaf-ts/logging";import{signers as It,connect as Ot}from"@hyperledger/fabric-gateway";import{User as Rt}from"fabric-common";import $t,{X509Certificate as kt}from"crypto";import*as Ft from"@peculiar/x509";import{Crypto as Dt}from"@peculiar/webcrypto";import*as Bt from"@grpc/grpc-js";import{Client as _t}from"@grpc/grpc-js";import Pt from"pkcs11js";import jt from"fs";import Kt from"path";import{p256 as Lt}from"@noble/curves/nist";class zt 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})}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[ct.TABLE]&&t[ct.TABLE]===$.tableName(this.class)?new this.class(t):t):c[ct.TABLE]&&c[ct.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 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,L.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await z(this,r,t,L.CREATE,L.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=M(i);if(s)throw new H(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 Mt=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Mt.prototype,"name",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Mt.prototype,"symbol",void 0),lt([n(),k(),dt("design:type",Number)],Mt.prototype,"decimals",void 0),Mt=lt([a("erc20_tokens"),F(),dt("design:paramtypes",[Object])],Mt);let Ht=class extends o{constructor(t){super(t)}};lt([s({type:String}),dt("design:type",String)],Ht.prototype,"id",void 0),lt([n(),k(),dt("design:type",String)],Ht.prototype,"token",void 0),lt([n(),k(),dt("design:type",Number)],Ht.prototype,"balance",void 0),lt([n(),dt("design:type",String)],Ht.prototype,"captive",void 0),Ht=lt([a("erc20_wallets"),F(),dt("design:paramtypes",[Object])],Ht);let Ut=class extends o{constructor(t){super(t)}};lt([s({type:String}),n(),k(),dt("design:type",String)],Ut.prototype,"owner",void 0),lt([n(),k(),dt("design:type",String)],Ut.prototype,"spender",void 0),lt([n(),k(),dt("design:type",Number)],Ut.prototype,"value",void 0),Ut=lt([a("erc20_allowances"),F(),dt("design:paramtypes",[Object])],Ut);class Yt extends B{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=ht.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new U("Could not find metadata for "+t.constructor.name);i=e}return r[_.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[_.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 Gt extends zt{static{this.serializer=new Yt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new Y("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 Gt.decoder.decode(t)}constructor(t){super(t,Ht),this.serializer=Gt.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",[Gt.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 Vt(t,e,r){return[...t.map(t=>t===ct.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(ht.splitter)}function Jt(t,e,r,i){const s=e.pop();s&&s!==ct.TABLE?e.push(s):s===ct.TABLE&&e.unshift(s);const n=Vt(e,r,i);let a=[...e,...i||[]];r&&(a=a.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const o={index:{fields:a},name:n,ddoc:n,type:"json"};t[n]=o}function qt(t,e){const r=Vt([ct.TABLE]),i=e||{};i[r]={index:{fields:[ct.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=$.indexes(t);for(const t of Object.keys(n))for(const[,e]of Object.entries(n[t])){const r=e.directions,i=e.compositions,n=[t,ct.TABLE];Jt(s,n),i&&i.length&&Jt(s,n,void 0,i),r&&r.length&&r.forEach(t=>{Jt(s,n,t),i&&i.length&&Jt(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Wt(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 Xt(...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(...Wt(e))}return r}function Qt(t,e=process.cwd(),r){const i=require("fs"),s=require("path");function n(t){const e=s.dirname(t);if(i.existsSync(e))return!0;n(e),i.mkdirSync(e)}t.forEach(t=>{const a=s.resolve(s.join(e,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${t.name}.json`));n(a),i.writeFileSync(a,JSON.stringify(t,void 0,2))})}let Zt=class extends o{constructor(t){super(t)}};var te,ee;lt([ut("Unique identifier of the credentials record"),n(),s(),dt("design:type",String)],Zt.prototype,"id",void 0),lt([ut("PEM-encoded X.509 certificate for the identity"),n(),k(),dt("design:type",String)],Zt.prototype,"certificate",void 0),lt([ut("PEM-encoded root or intermediate certificate"),n(),k(),dt("design:type",String)],Zt.prototype,"rootCertificate",void 0),lt([ut("PEM-encoded private key"),n(),k(),dt("design:type",String)],Zt.prototype,"privateKey",void 0),Zt=lt([F(),dt("design:paramtypes",[Object])],Zt),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric",t.OWNED_BY="owned-by",t.TRANSACTION_ID="transaction-id",t.MIRROR="mirror"})(te||(te={})),(t=>{t.X509="X.509"})(ee||(ee={}));const re="hlf-fabric";let ie=class extends o{constructor(t){super(t),this.type=ee.X509}};lt([ut("Unique identifier of the identity"),s(),dt("design:type",String)],ie.prototype,"id",void 0),lt([d(Zt,{update:h.CASCADE,delete:h.CASCADE}),dt("design:type",Zt)],ie.prototype,"credentials",void 0),lt([n(),k(),u(),dt("design:type",String)],ie.prototype,"mspId",void 0),lt([n(),k(),dt("design:type",String)],ie.prototype,"type",void 0),ie=lt([F(),dt("design:paramtypes",[Object])],ie);class se{static{this.logger=new Ct(se.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 p(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(P("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Rt(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?(se.cryptoSuite||(se.cryptoSuite=Rt.newCryptoSuite(t)),se.cryptoSuite):Rt.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 kt(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return $t.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 p(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 p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await p(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return It.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await p(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 ne=new Dt;var ae,oe,ce,le,de;Ft.cryptoProvider.set(ne),(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-_.!~"})(ae||(ae={})),(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"})(oe||(oe={}));class he{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 ue{static{this.b58encoder=new he(ae.BASE58)}static{this.logger=new Ct(ue.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(P("Parsing certificate: {0}",t));const e=new Ft.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(P("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=ne.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 ne.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 Ft.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,ne.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Ft.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 At()?globalThis.window.crypto.subtle:ne.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=ne.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,oe.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:oe.KEY_ALGORYTHM,hash:oe.HASH,salt:i,iterations:oe.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*oe.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:oe.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:oe.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class pe extends Y{constructor(t){super(t,pe.name)}}class ge extends Y{constructor(t){super(t,ge.name)}}class fe extends Y{constructor(t){super(t,fe.name)}}class me extends g{constructor(t){super(t,me.name)}}class ye extends Y{constructor(t){super(t,ye.name,500)}}class we extends G{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(we.name,t,403)}}class be extends G{constructor(t){super(be.name,t,409)}}class Ce extends Y{constructor(t){super(t,Ce.name,500)}}class Ae extends Y{constructor(t){super(t,Ae.name,500)}}class ve extends Y{constructor(t){super(t,ve.name,500)}}class Se extends Y{constructor(t){super(t,Se.name,500)}}class Ee extends Y{constructor(t){super(t,Ee.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(ce||(ce={})),(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"})(le||(le={}));class xe extends vt{constructor(t){se.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 se.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new Y(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await se.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await se.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 se.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new bt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`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=St.for(xe,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=ue.fabricIdFromCertificate(r),o=ue.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new ie({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=xe.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new J("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 Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class Ne extends ${constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new H(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}}lt([k(),dt("design:type",String)],Ne.prototype,"affiliation",void 0),lt([j(1),dt("design:type",Array)],Ne.prototype,"attrs",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentID",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"enrollmentSecret",void 0),lt([K(0),dt("design:type",Number)],Ne.prototype,"maxEnrollments",void 0),lt([k(),dt("design:type",String)],Ne.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(de||(de={}));let Te=class extends ${constructor(t){super(t)}};lt([ut("Stores the original timestamp of creation"),n(),f(),dt("design:type",Date)],Te.prototype,"createdAt",void 0),lt([ut("Stores the timestamp of the last update"),n(),m(),dt("design:type",Date)],Te.prototype,"updatedAt",void 0),lt([ut("Stores the version of the model"),n(),q(),dt("design:type",Number)],Te.prototype,"version",void 0),Te=lt([pt(re),dt("design:paramtypes",[Object])],Te);let Ie=class extends Te{constructor(t){super(t)}};function Oe(){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 J("No tokens avaialble");if(a.length>1)throw new J("To many token available : "+a.length);if(a[0].owner!=s)throw new g(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Re(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 $e(){return gt.for(te.OWNED_BY).define({decorator:()=>(t,e)=>ft(k(),X(),Q(Re),mt(ht.key(te.FABRIC,te.OWNED_BY),e))(t,e),args:[]}).apply()}async function ke(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Fe(){return gt.for(te.TRANSACTION_ID).define({decorator:()=>(t,e)=>ft(k(),X(),Q(ke),Z(ke),mt(ht.key(te.FABRIC,e,te.TRANSACTION_ID),e))(t,e),args:[]}).apply()}async function De(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 Y("Failed to resolve collection mirror name: "+t)}if(!i||"string"!=typeof i)throw new Y("No collection found model "+t.constructor.name);return i}async function Be(t,e,r,i){const s=await De(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 _e(t,e,r,i){const s=await De(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 Pe(t,e,r,i){const s=await De(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 je(t,e){return gt.for(te.MIRROR).define({decorator:(e,r)=>{const i={condition:r,resolver:e};return ft(yt(ht.key(te.FABRIC,te.MIRROR),i),Ge(t),tt(Be,i,{priority:95}),et(_e,i,{priority:95}),rt(Pe,i,{priority:95}))},args:[t,e]}).apply()}lt([ut("Stores the creator"),n(),y(),dt("design:type",String)],Ie.prototype,"createdBy",void 0),lt([ut("Stores the user that last updated the model"),n(),w(),dt("design:type",String)],Ie.prototype,"updatedBy",void 0),Ie=lt([pt(re),dt("design:paramtypes",[Object])],Ie),$.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=ht.validatableProperties(t.constructor),r=ht.get(t.constructor,W.TRANSIENT),i=ht.get(t.constructor,te.PRIVATE),s=ht.get(t.constructor,te.PRIVATE),n={model:{},transient:{},private:{},shared:{}},a=Object.keys(r),o=Object.keys(i),c=Object.keys(s);for(const r of e){const e=a.includes(r),i=o.includes(r),s=c.includes(r);e?(n.transient=n.transient||{},n.transient[r]=t[r],i&&(n.private=n.private||{},n.private[r]=t[r]),s&&(n.shared=n.shared||{},n.shared[r]=t[r])):(n.model=n.model||{},n.model[r]=t[r])}return n.model=$.build(n.model,t.constructor.name),n}).bind($),$.isPrivate=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.PRIVATE)).bind($),$.isShared=(t=>!!ht.get("function"!=typeof t?t.constructor:t,te.SHARED)).bind($),$.mirrored=(t=>ht.get("function"!=typeof t?t.constructor:t,ht.key(te.FABRIC,te.MIRROR))).bind($),$.ownerOf=(t=>{const e=ht.get(t.constructor,ht.key(te.FABRIC,te.OWNED_BY));if(e)return t[e]}).bind($),$.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,ht.get(t,ht.key(te.FABRIC,te.MIRROR)))).bind($),$.collectionsFor=(t=>{const e=[te.PRIVATE],r=[te.SHARED],i=ht.key(...e),s=ht.key(...r),n="function"==typeof t?t:t.constructor,a=ht.get(n,i),o=ht.get(n,s);return{privateCols:a?.collections||[],sharedCols:o?.collections||[]}}).bind($);const Ke=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0),i="function"==typeof t?t:t.constructor;if(!r)throw new Y(`Model ${i.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${Et(i.name)}${e?Et(e):""}`},Le=(t,e)=>{const r=e||("function"!=typeof t?$.ownerOf(t):void 0);if(!r)throw new Y(`Model ${t.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${Et(r)}PrivateCollection`};async function ze(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:n(i,s,t),o=r.reduce((r,n,o)=>{const c="string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t);if(c!==a)throw new b(`Segregated data collection mismatch: ${c} vs ${a}`);return r[n]=i[n],r},{}),c=new this.class(o),l=await this.override({segregated:a,mergeModel:!1,ignoreHandlers:!0,ignoreValidation:!0}).create(c,t);Object.assign(i,l)}async function Me(t,e,r,i){if(r.length!==e.length)throw new Y("Segregated data keys and metadata length mismatch");const s=$.ownerOf(i);if(!s)throw new H("There's no assigned organization for model "+i.constructor.name);const n=e[0].collections,a="string"==typeof n?n:await n(i,s,t);r.reduce((r,n,o)=>(("string"==typeof e[o].collections?e[o].collections:e[o].collections(i,s,t))!==a||(r[n]=i[n]),r),{})}async function He(t,e,r,i,s){}async function Ue(t,e,r,i){}function Ye(t,e,r){return(i,s)=>{const n=[];return s?n.push(wt(),it(),(r,i)=>{const s=ht.key(e,i),n=r.constructor,a=ht.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],ht.set(n,s,a);const c=ht.get(n,e)||{};new Set(c.collections||[]).add(t),a.collections=[...o],ht.set(n,e,a)},Q(ze,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),st(Me,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),Z(He,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),nt(Ue,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})):ht.properties(i)?.forEach(s=>{r&&!r(s)||Ye(t,e)(i.prototype,s)}),ft(...n)(i,s)}}function Ge(t=Le){return gt.for(te.PRIVATE).define({decorator:t=>Ye(t,te.PRIVATE),args:[t]}).apply()}function Ve(t){return gt.for(te.SHARED).define({decorator:t=>Ye(t,te.SHARED),args:[t]}).apply()}class Je extends B{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=ht.modelName(t.constructor)}catch(t){r=void 0}e[_.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[_.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 qe(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function We(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 Xe(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new pe(`Addition overflow: ${t} + ${e}`);return r}function Qe(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new pe(`Subtraction overflow: ${t} - ${e}`);return r}function Ze(t){if(!/^\d+$/.test(t))throw new H(P("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new H(P("Failed to parse: {0}","string is not a parsable integer"));return e}class tr extends B{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=ht.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[_.ANCHOR]=i||t.constructor.name),$.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class er extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new Y("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 se.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new Y(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await se.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await se.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=await this.logCtx(t,this.initialize,!0),[i]=t;if(!i)throw new Y("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:c}=n,l=o[0];e.debug(`Retrieving CA certificate from ${l}. cwd: ${process.cwd()}`);const d=await se.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new bt(s,{trustedRoots:Buffer.from(d),verify:c},a),u=await this.getUser(i,r);return e.debug("CA user loaded: "+u.getName()),{config:i,client:h}}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,this.getCertificates,!0);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new me(t);const[,r,i]=e;switch(r){case"74":case"71":return new V(i);case"20":return new g(i);default:return new me(i)}}async read(t,...e){const{log:r}=await this.logCtx(e,this.read,!0);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new J(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new J(`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,this.register,!0);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=ue.fabricIdFromCertificate(s),c=ue.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new ie({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,this.enroll,!0);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=er.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,this.registerAndEnroll,!0),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,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new J("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 Y(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new Y(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const rr=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60}),ir=new Ct("fabric-fs");async function sr(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 p(import("fs"));return await e.readFile(t)})(t)}async function ar(t,e,r,i){ir.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Rt(t),n=Rt.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 sr(e,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function cr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function lr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function dr(t){const e=await sr(t,async t=>{const{promises:e}=await p(import("fs")),r=await cr(t);return await e.readFile(r)}),r=await hr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return It.newPrivateKeySigner(i)}async function hr(t){let e;if(At())e=globalThis.crypto.subtle;else{const t=await p(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 Y(t)}}class ur{static#t=null;static#e=!1;constructor(t){if(ur.#t||(ur.#t=new Pt.PKCS11,ur.#t.load(this.findHSMPKCS11Lib(t))),!ur.#e){try{ur.#t.C_Initialize()}catch(t){if(t.code!==Pt.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}ur.#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(jt.existsSync(t))return t;throw new Ce("Unable to find PKCS11 library")}dispose(){ur.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Pt.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=ur.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>ur.#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{ur.#t.C_Login(t,e,r)}catch(t){if(t.code!==Pt.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Pt.CKA_ID,value:r},{type:Pt.CKA_CLASS,value:e},{type:Pt.CKA_KEY_TYPE,value:Pt.CKK_EC}];ur.#t.C_FindObjectsInit(t,i);const s=ur.#t.C_FindObjects(t,1)[0];if(!s)throw ur.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return ur.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=ur.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Pt.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Pt.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw ur.#t.C_CloseSession(s),t}return{signer:async t=>{ur.#t.C_SignInit(s,{mechanism:Pt.CKM_ECDSA},n);const e=await ur.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*Lt.Point.Fn.BYTES));return Lt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{ur.#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:Kt.join(t,"cert.pem"),r=jt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new $t.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return $t.createHash("sha256").update(r).digest()}}class pr extends A{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 Y("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=[v.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(v.SELECT,this.selectSelector.join(` ${v.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(v.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=xt(n.join(" ")),s.params=i,this.prepared=s,this}build(){throw new b("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(t,...e){throw new b("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class gr 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 fr;class mr extends S{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Yt}static{this.log=St.for(mr)}constructor(t,e){super(t,re,e),this.serializer=mr.serializer}Statement(t){return new pr(this,t)}Paginator(t,e,r){return new gr(this,t,e,r)}async flags(t,e,r,...i){return Object.assign(await super.flags(t,e,Object.assign({},rr,r),...i))}decode(t){return mr.decoder.decode(t)}repository(){return zt}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=$.tableName(t),a={};return a[ct.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 Y("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[ct.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 Y("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[ct.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new Y("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,at.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 U(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,at.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 U(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new Y("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,at.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 U(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,at.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 U(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,private:s.private,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)throw new Y(`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,L.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,L.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[ct.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,L.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,L.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 U("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}getClient(){return this._client||(this._client=mr.getClient(this.config)),this._client}async Gateway(t){return mr.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return mr.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 mr.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=St.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(jt.readFileSync(r,"utf8"))}catch(t){throw new Y(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Bt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new _t(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=St.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 ur(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=Ot(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new mr._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new ve(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ee(t):e.includes("PHANTOM_READ_CONFLICT")?new Se(t):t instanceof Error&&t.code&&9===t.code?new Ae(t):e.includes(J.name)?new J(t):e.includes(V.name)?new V(t):e.includes(ot.name)?new ot(t):e.includes(E.name)?new E(t):e.includes(x.name)?new x(t):e.includes(b.name)?new b(t):e.includes(N.name)?new N(t):e.includes(T.name)?new T(t):e.includes(g.name)?new g(t):e.includes(I.name)?new I(t):e.includes(O.name)?new O(t):e.includes(U.name)?new U(t):new Y(t)}}lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"create",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"read",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"update",null),lt([Nt(),Tt(),dt("design:type",Function),dt("design:paramtypes",[Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"delete",null),lt([Nt(),dt("design:type",Function),dt("design:paramtypes",[Object,"function"==typeof(fr="undefined"!=typeof D&&D)?fr:Object,Object,l]),dt("design:returntype",Promise)],mr.prototype,"raw",null),mr.decoration(),S.setCurrent(re);class yr extends R{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 mr))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}=S.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new Y("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 Y('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new Y("No adapter found. should be impossible");const e=t||await this.adapter.context(L.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}=We(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 Y("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 mr.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new Y("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}mr&&(mr._baseDispatch=yr);const wr="##VERSION##",br="##PACKAGE##";ht.registerLibrary(br,wr);export{fe as AllowanceError,ae as BASE_ALPHABET,ge as BalanceError,he as BaseEncoder,oe as CRYPTO,Yt as ClientSerializer,se as CoreUtils,ue as CryptoUtils,rr as DefaultFabricClientFlags,Je as DeterministicSerializer,de as ERC20Events,Ae as EndorsementError,Ee as EndorsementPolicyError,Te as FabricBaseModel,mr as FabricClientAdapter,yr as FabricClientDispatch,zt as FabricClientRepository,Gt as FabricERC20ClientRepository,xe as FabricEnrollmentService,re as FabricFlavour,Ie as FabricIdentifiedBaseModel,er as FabricIdentityService,te as FabricModelKeys,le as HFCAIdentityAttributes,ce as HFCAIdentityType,ie as Identity,Zt as IdentityCredentials,ee as IdentityType,Le as ImplicitPrivateCollection,ye as MissingContextError,Ce as MissingPKCSS11Lib,Ke as ModelCollection,ve as MvccReadConflictError,be as NotInitializedError,pe as OverflowError,Oe as Owner,br as PACKAGE_NAME,Se as PhantomReadConflictError,me as RegistrationError,Ne as RegistrationRequestBuilder,tr as SimpleDeterministicSerializer,we as UnauthorizedPrivateDataAccess,wr as VERSION,Xe as add,sr as contentOfLoadFile,Be as createMirrorHandler,Pe as deleteMirrorHandler,De as evalMirrorMetadata,hr as extractPrivateKey,qe as generateFabricEventName,qt as generateModelIndexes,ar as getCAUser,cr as getFirstDirFileName,lr as getFirstDirFileNameContent,or as getIdentity,dr as getSigner,je as mirror,$e as ownedBy,Re as ownedByOnCreate,We as parseEventName,Ge as privateData,nr as readFile,Wt as readModelFile,Xt as readModelFolders,Ze as safeParseInt,ze as segregatedDataOnCreate,Ue as segregatedDataOnDelete,Me as segregatedDataOnRead,He as segregatedDataOnUpdate,Ve as sharedData,Qe as sub,Fe as transactionId,ke as transactionIdOnCreate,_e as updateMirrorHandler,Qt as writeIndexes};
|
|
2
2
|
//# sourceMappingURL=for-fabric.js.map
|