@decaf-ts/for-fabric 0.13.29 → 0.13.30
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/cjs/client/FabricClientAdapter.cjs +6 -2
- package/lib/cjs/client/FabricClientAdapter.cjs.map +1 -1
- package/lib/cjs/version.cjs +3 -3
- package/lib/esm/client/FabricClientAdapter.js +6 -2
- package/lib/esm/client/FabricClientAdapter.js.map +1 -1
- package/lib/esm/version.js +3 -3
- package/lib/types/version.d.cts +3 -3
- package/lib/types/version.d.mts +3 -3
- package/package.json +1 -1
package/dist/for-fabric.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,r,i,a,n,o,s,c,l,d,u,h,g,p,f,y){"use strict";function m(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var w=m(h),b=m(p);function E(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;E(r),t.mkdirSync(r)}function C(e){const r=require("path").resolve(e.parentPath,e.name),i=require(r);return Object.values(i).filter(e=>{try{return new e instanceof t.Model}catch{return!1}})}function A(e,t=process.cwd(),r){if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const n=e._id.replace(/^_design\//,""),o=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));E(o);const s={...e};delete s._rev,i.writeFileSync(o,JSON.stringify(s,void 0,2))})}function v(e,t,r,i,a,n,o){return{name:e,policy:t,requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}}function O(e,t=e+"Private",r=0,i=0,a=0,n=!0,o=!0){const s=v(t,`OR('${e}.member')`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`OR('${e}.peer')`},s}function S(e,t,r=1,i=2,a=0,n=!0,o=!0){const s=v(t,`OR(${e.map(e=>`'${e}.member'`).join(",")})`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`AND(${e.map(e=>`'${e}.peer'`).join(",")})`},s}class M extends a.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new a.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)}}class I extends r.InternalError{constructor(e){super(e,I.name)}}class _ extends r.InternalError{constructor(e){super(e,_.name)}}class x extends r.InternalError{constructor(e){super(e,x.name)}}class T extends a.AuthorizationError{constructor(e){super(e,T.name)}}class N extends r.InternalError{constructor(e){super(e,N.name,500)}}class F extends r.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(F.name,e,403)}}class R extends r.BaseError{constructor(e){super(R.name,e,409)}}class P extends r.InternalError{constructor(e){super(e,P.name,500)}}class $ extends r.InternalError{constructor(e){super(e,$.name,500)}}class B extends r.InternalError{constructor(e){super(e,B.name,500)}}class K extends r.InternalError{constructor(e){super(e,K.name,500)}}class k extends r.InternalError{constructor(e){super(e,k.name,500)}}class L extends r.InternalError{constructor(e,t=L.name,r=590){super(e,t,r)}}class j extends r.InternalError{constructor(e){super(e,j.name,591)}}class z extends r.InternalError{constructor(e){super(e,z.name,592)}}class U extends L{constructor(e){super(e,U.name,593)}}class H extends a.Repository{constructor(e,t,r=!1){super(e,t,r),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return o.verbose(`paginating ${t.Model.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...s)}async listBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);n.verbose(`listing ${t.Model.tableName(this.class)} by ${e} ${r}`);try{return await this.statement(this.listBy.name,e,r,...o)}catch(i){if(i instanceof U)return n.warn(`listBy result set too large for ${t.Model.tableName(this.class)} key=${e+""} order=${r}. Returning empty list. Use paginateBy for large datasets.`),[];throw i}}async findBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...o)}async findOneBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...o)}async find(e,r=a.OrderDirection.ASC,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...o)}async page(e,r=a.OrderDirection.ASC,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE,!0)).for(this.page);return o.verbose(`paging ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...s)}async statement(e,...r){const{log:n,ctx:o,ctxArgs:s}=(await this.logCtx(r,a.PersistenceKeys.STATEMENT,!0)).for(this.statement);n.verbose("Executing prepared statement "+e);const c=s.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(o,a.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class)));let d;return d=Array.isArray(l)?l.map(e=>e[i.CouchDBKeys.TABLE]&&e[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(e):e):l[i.CouchDBKeys.TABLE]&&l[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(l):M.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l,this.applyAfterRead(d,o)}async applyAfterRead(e,i){return i.getOrUndefined("afterQueryHandlers")?e instanceof t.Model?(await r.enforceDBDecorators(this,i,e,r.OperationKeys.READ,r.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterRead(e,i))),e):M.isSerializedPage(e)?(await this.applyAfterRead(e.data,i),e):e:e}async countOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.Model.tableName(this.class)}${e?" by "+e:""}`);const o=e?[e,...n]:n;return this.statement(a.PreparedStatementKeys.COUNT_OF,...o)}async maxOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MAX_OF,e,...n)}async minOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MIN_OF,e,...n)}async avgOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.AVG_OF,e,...n)}async sumOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.SUM_OF,e,...n)}async distinctOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.DISTINCT_OF,e,...n)}async groupOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.Model.tableName(this.class)} by ${e}`),this.statement(a.PreparedStatementKeys.GROUP_OF,e,...n)}async healthcheck(...e){const{ctxArgs:t}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...t)}async create(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.create);a.debug(`Creating new ${this.class.name} in table ${t.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const o=this.adapter.prepare(e,i),{record:s,id:c,transient:l}=o,d=await this.adapter.create(this.class,c,s,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:a,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const o=this.adapter.prepare(e,n),{id:s,transient:c}=o;let l=o.record;return a.debug(`updating ${this.class.name} in table ${t.Model.tableName(this.class)} with id ${s}`),l=await this.adapter.update(this.class,s,l,c,...i),this.adapter.revert(l,this.class,s,c,n)}async createAllPrefix(e,...t){const{ctx:i,ctxArgs:a}=(await this.logCtx(t,r.OperationKeys.CREATE,!0)).for(this.createAllPrefix),n=i.get("ignoreHandlers"),o=i.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),n||await r.enforceDBDecorators(this,i,e,r.OperationKeys.CREATE,r.OperationKeys.ON),e))),!o){const t=i.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=r.reduceErrorsToPrint(a);if(n)throw new r.ValidationError(n)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=o.map(e=>e.record),l=o.map(e=>e.transient),d=await this.adapter.createAll(this.class,s,c,l,...n);return Promise.all(d.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,l[t],i)}))}async readAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${t.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...n)).map((t,r)=>this.adapter.revert(t,this.class,e[r],{},i))}async updateAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=await this.adapter.updateAll(this.class,s,o.map(e=>e.record),o.map(e=>e.transient),...n);return Promise.all(c.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,o[t].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.Model.mirroredAt(r)&&e.accumulate({legacy:!0})}}let G=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],G.prototype,"name",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],G.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],G.prototype,"symbol",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],G.prototype,"decimals",void 0),G=n.__decorate([a.table("erc20_tokens"),t.model(),n.__metadata("design:paramtypes",[Object])],G);let q=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],q.prototype,"id",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],q.prototype,"token",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],q.prototype,"balance",void 0),n.__decorate([a.column(),n.__metadata("design:type",String)],q.prototype,"captive",void 0),q=n.__decorate([a.table("erc20_wallets"),t.model(),n.__metadata("design:paramtypes",[Object])],q);let V=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),a.column(),t.required(),n.__metadata("design:type",String)],V.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],V.prototype,"spender",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],V.prototype,"value",void 0),V=n.__decorate([a.table("erc20_allowances"),t.model(),n.__metadata("design:paramtypes",[Object])],V);class Y extends t.JSONSerializer{constructor(){super()}preSerialize(e,i){const a=Object.assign({},e);let n=o.Metadata.modelName(e.constructor);if(!n||"Object"===n){if(!i)throw new r.SerializationError("Could not find metadata for "+e.constructor.name);n=i}return a[t.ModelKeys.ANCHOR]=n,a}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class J extends H{static{this.serializer=new Y}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,i,n,...o){if(!this.observerHandler)throw new r.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:c}=this.logCtx(o,this.updateObservers);let l;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.Model.get(e):e,l=void 0===n?void 0:Array.isArray(n)?n.map(r=>a.Sequence.parseValue(t.Model.sequenceFor(e).type,r)):a.Sequence.parseValue(t.Model.sequenceFor(e).type,n),await this.observerHandler.updateObservers(e,i,l,...c)}decode(e){return J.decoder.decode(e)}constructor(e){super(e,q),this.serializer=J.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,t,r){const i=await a.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(i.args,this.transferFrom),o=await this.adapter.submitTransaction(n,"TransferFrom",[e,t,r.toString()]);return"true"===this.decode(o)}async approve(e,t){const r=await a.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),n=await this.adapter.submitTransaction(i,"Approve",[e,t.toString()]);return"true"===this.decode(n)}async allowance(e,t){const r=await a.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),n=await this.adapter.submitTransaction(i,"Allowance",[e,t]);return Number(this.decode(n))}async initialize(e){const t=await a.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[J.serializer.serialize(e)]);return"true"===this.decode(i)}async checkInitialized(){const e=await a.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(t,"CheckInitialized")}async mint(e){const t=await a.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[e.toString()])}async burn(e){const t=await a.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[e.toString()])}async burnFrom(e,t){const r=await a.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[e,t.toString()])}async clientAccountBalance(){const e=await a.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(t,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const e=await a.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(t,"ClientAccountID");return this.decode(r)}}function W(e,i,a){let n,o,s;function c(i,a){if(n=n||t.Model.pk(e),s=s||t.Model.sequenceFor(e),o=o||t.Model.composed(e,n),o)return r.composeAttributeValue(i,o);const c=i[n]||a;if(void 0===c)throw new r.InternalError("could not rebuild id for "+i.constructor.name);return c}if(Array.isArray(i)){if(!Array.isArray(a)||a.length!==i.length)throw new r.InternalError("inconsistent parameters. both must be arrays of equal length");return i.map((e,t)=>c(e,a[t]))}return c(i,a)}var Q;e.IdentityCredentials=class extends a.BaseModel{constructor(e){super(e)}},n.__decorate([o.description("Unique identifier of the credentials record"),a.column(),a.pk(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),n.__decorate([o.description("PEM-encoded X.509 certificate for the identity"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),n.__decorate([o.description("PEM-encoded root or intermediate certificate"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),n.__decorate([o.description("PEM-encoded private key"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(Q=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",Q.SHARED="shared",Q.FABRIC="fabric",Q.OWNED_BY="owned-by",Q.TRANSACTION_ID="transaction-id",Q.MIRROR="mirror",Q.CONTRACT="fabric.contract",Q.CHAINCODE="fabric.chaincode",Q.CHANNEL="fabric.channel",Q.OVERRIDES="__overrides",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const X="hlf-fabric";e.Identity=class extends a.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},n.__decorate([o.description("Unique identifier of the identity"),a.pk(),n.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),n.__decorate([a.oneToOne(e.IdentityCredentials,{update:a.Cascade.CASCADE,delete:a.Cascade.CASCADE}),n.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),n.__decorate([a.column(),t.required(),a.index(),n.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.Identity);class Z{static{this.logger=new c.MiniLogger(Z.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}static async getCAUser(e,r,i,a,n){this.logger.debug(t.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const o=new d.User(e),s=n?.hsm?{software:!1,lib:n.hsm.library,slot:n.hsm.slot,label:n.hsm.tokenLabel,pin:n.hsm.pin+""}:void 0,c=this.getCryptoSuite(s);o.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,i,n.hsm):this.getSoftwareEnrollmentKey(c,r);return await o.setEnrollment(l,i,a),o}static getCryptoSuite(e){return e?(Z.cryptoSuite||(Z.cryptoSuite=d.User.newCryptoSuite(e)),Z.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,t){return{mspId:e,credentials:await this.contentOfLoadFile(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)})}}static async getFirstDirFileName(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}static async getFileContent(e){const{promises:t}=await a.normalizeImport(import("fs"));return(await t.readFile(e)).toString()}static async getSigner(e){const t=await this.contentOfLoadFile(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)}),r=await this.extractPrivateKey(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}static async extractPrivateKey(e){let t;if(globalThis.window&&globalThis.window.Crypto)t=globalThis.Crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(r,"base64").toString("binary"));return await t.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function ee(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const te=new g.Crypto;var re,ie,ae,ne,oe;w.cryptoProvider.set(te),e.BASE_ALPHABET=void 0,(re=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",re.BASE8="01234567",re.BASE11="0123456789a",re.BASE16="0123456789abcdef",re.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",re.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",re.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",re.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",re.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",re.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",re.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(ie=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",ie[ie.ITERATIONS=1e3]="ITERATIONS",ie[ie.KEYLENGTH=48]="KEYLENGTH",ie[ie.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",ie[ie.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",ie.ALGORYTHM="AES-GCM",ie.KEY_ALGORYTHM="PBKDF2";class se{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const n=(a-i)*this.iFactor+1>>>0,o=new Uint8Array(n);for(;i!==a;){let t=e[i],a=0;for(let e=n-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*o[e]>>>0,o[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let s=n-r;for(;s!==n&&0===o[s];)s++;let c=this.leader.repeat(t);for(;n>s;++s)c+=this.alphabet.charAt(o[s]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,n=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let o=0;for(let e=a-1;(0!==r||i>o)&&-1!==e;e--,o++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=o,t++}let o=a-i;for(;o!==a&&0===n[o];)o++;const s=new Uint8Array(r+(a-o));let c=r;for(;o!==a;)s[c++]=n[o++];return s}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class ce{static{this.b58encoder=new se(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(ce.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(t.stringFormat("Parsing certificate: {0}",e));const r=new w.X509Certificate(e),{subject:i,issuer:a}=r;return this.logger.debug(t.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=te.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(a,"base64").toString("binary"),o=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",o,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await te.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new w.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,te.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new w.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:te.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=te.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),n={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},o=await this.getSubtleCrypto().deriveBits(n,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(o)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}e.HFCAIdentityType=void 0,(ae=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",ae.ORDERER="orderer",ae.CLIENT="client",ae.USER="user",ae.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(ne=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",ne.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",ne.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",ne.HFINTERMEDIATECA="hf.IntermediateCA",ne.HFREVOKER="hf.Revoker",ne.HFAFFILIATIONMGR="hf.AffiliationMgr",ne.HFGENCRL="hf.GenCRL";class le extends c.LoggedClass{constructor(e){Z.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:i,url:a,hsm:n}=this.caConfig,o=this.log.for(this.User);o.debug(`Creating CA user for ${e} at ${a}`),o.debug("Retrieving CA certificate from "+t);const s=await Z.getFirstDirFileNameContent(t);let c;if(n)o.debug(`Using HSM configuration for CA ${e} with library ${n.library}`);else{if(!i)throw new r.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);o.debug("Retrieving CA key from "+i),c=await Z.getFirstDirFileNameContent(i)}return o.debug("Loading Admin user for ca "+e),this.user=await Z.getCAUser("admin",c,s,e,{hsm:n}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:n}=r;const o=a[0];e.debug(`Retrieving CA certificate from ${o}. cwd: ${process.cwd()}`);const c=await Z.getFileContent(o);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new s(t,{trustedRoots:Buffer.from(c),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),t?n.certs.map(e=>e.PEM):n}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new T(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new T(n)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),i=await this.User();let a;try{a=await t.newIdentityService().getOne(e,i)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n){let o;const s=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};o=await d.register(h,u),s.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return o}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:n}=t,o=c.Logging.for(le,{}).for(this.identityFromEnrollment);o.debug(`Generating Identity from certificate ${i} in msp ${r}`);const s=ce.fabricIdFromCertificate(i),l=ce.encode(s);o.debug(`Identity ${s} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:n,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const n=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=le.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,n){const o=await this.register(e,t,r,i,a,n),{userName:s}=e;return this.enroll(s,o)}async revoke(e){const t=await this.CA(),i=await this.User(),a=await this.read(e);if(!a)throw new r.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},i)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}class de extends t.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new r.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"affiliation",void 0),n.__decorate([t.minlength(1),n.__metadata("design:type",Array)],de.prototype,"attrs",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"enrollmentID",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"enrollmentSecret",void 0),n.__decorate([t.min(0),n.__metadata("design:type",Number)],de.prototype,"maxEnrollments",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"role",void 0),t.Model.prototype.isShared=function(){return t.Model.isShared(this.constructor)},t.Model.prototype.isPrivate=function(){return t.Model.isPrivate(this.constructor)},t.Model.prototype.segregate=function(){return t.Model.segregate(this)},t.Model.segregate=(i=>{if(!t.Model.isTransient(i))return{model:i};const a=o.Metadata.getAttributes(i.constructor)||[],n=o.Metadata.get(i.constructor,r.DBKeys.TRANSIENT),s=o.Metadata.get(i.constructor,e.FabricModelKeys.PRIVATE),c=o.Metadata.get(i.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(n||{}),u=Object.keys(s||{}),h=Object.keys(c||{});for(const e of a){const t=i[e],r=d.includes(e),a=!r,n=u.includes(e),o=h.includes(e);(r||n||o)&&(l.transient=l.transient||{},l.transient[e]=t),n&&(l.privates=l.privates||{},l.privates[e]=t),o&&(l.shared=l.shared||{},l.shared[e]=t),a&&(l.public=l.public||{},l.public[e]=t)}return l.model=t.Model.build(l.public,i.constructor.name),l}).bind(t.Model),t.Model.isPrivate=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(t.Model),t.Model.isShared=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(t.Model),t.Model.mirrored=(t=>o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(t.Model),t.Model.ownerOf=(t=>{const r=o.Metadata.get(t.constructor,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(t.Model),t.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,o.Metadata.get(t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(t.Model),t.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=o.Metadata.key(...r),n=o.Metadata.key(...i),s="function"==typeof t?t:t.constructor,c=o.Metadata.get(s,a),l=o.Metadata.get(s,n);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(t.Model),t.Model.chaincodeOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CHAINCODE);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),t.Model.contractOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CONTRACT);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),t.Model.channelOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CHANNEL);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),e.ERC20Events=void 0,(oe=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",oe.APPROVAL="Approval",e.FabricBaseModel=class extends t.Model{constructor(e){super(e)}},n.__decorate([o.description("Stores the original timestamp of creation"),a.column(),a.createdAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),n.__decorate([o.description("Stores the timestamp of the last update"),a.column(),a.updatedAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),n.__decorate([o.description("Stores the version of the model"),a.column(),r.version(),n.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=n.__decorate([o.uses(X),n.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},n.__decorate([o.description("Stores the creator"),a.column(),a.createdBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),n.__decorate([o.description("Stores the user that last updated the model"),a.column(),a.updatedBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=n.__decorate([o.uses(X),n.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel);const ue=(e,...t)=>e.name+"Contract";function he(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function ge(e,t,r,i){const{stub:a}=e,n=e.getOrUndefined("allowGenerationOverride")||!1;let o=(await a.getCreator()).mspid;e.logger.info(`Expected mspid to be ${i[r]} | ${o}. \n Using allowGenerationOverride: ${n}`),n&&(o=i[r]?i[r]:o),Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:o})}async function pe(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function fe(e,i,a){let n=i;if("string"!=typeof n)try{const r=t.Model.ownerOf(e)||a.get("stub").getCreator().toString();i&&"function"==typeof i&&(n=await i(e,r,a))}catch(e){throw new r.InternalError("Failed to resolve collection mirror name: "+e)}if(!n||"string"!=typeof n)throw new r.InternalError("No collection found model "+e.constructor.name);return n}async function ye(e,r,i,a){const n=await fe(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(s,e);e.logger.info(`Mirror for ${t.Model.tableName(this.class)} created with ${t.Model.pk(a)}: ${i[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function me(e,r,i,a){const n=await fe(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(s,e),e.logger.info(`Mirror for ${t.Model.tableName(this.class)} updated: ${a[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function we(e,r,i,a){const n=await fe(a,r.resolver,e),o=e;o.put("mirror",!0),o.put("mirrorCollection",n),o.put("segregated",n);try{const r=a[t.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.Model.tableName(this.class)} deleted: ${r+""}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0),o.put("segregated",void 0)}}async function be(e,t,r,i){const n=he(e.get("identity"));if(n&&(n===t.mspId||t.condition&&t.condition(n)))throw new a.AuthorizationError(`Organization ${n} is not authorized to modify mirrored data`)}async function Ee(e,t,r,i){const a=he(e.get("identity"));if(!a)return;const n=await fe(i,t.resolver,e),o=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${n}`),o.put("mirror",!0),o.put("mirrorCollection",n),o.put("fullySegregated",!0),o.readFrom(n))}const Ce=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0);if(!a)throw new r.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function Ae(i,a,n){a.length>0&&n.readFrom(a),!n.isFullySegregated&&a.length&&((i=>{const a=o.Metadata.getAttributes(i)||[],n=t.Model.pk(i),s=o.Metadata.get(i,r.DBKeys.TRANSIENT)||{},c=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.PRIVATE))||{},l=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.SHARED))||{};return a.some(e=>e!==n&&!(e in s)&&!(e in c)&&!(e in l))})(i.constructor)||n.markFullySegregated())}async function ve(e,r,i,a){const n=Array.isArray(r)?r:[r],o=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(a)||he(e.get("identity"));if(!o)return;const s=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(a,o,e);i&&!s.includes(i)&&s.push(i)}Ae(a,s,e);const c=Array.isArray(i)?i:[i],l=t.Model.pk(a.constructor),d=t.Model.sequenceName(a,"pk"),u=a[l],h=null!=u;if(e.setSequenceSegregation(d,e.isFullySegregated,s),h)for(const r of c){const i=t.Model.sequenceName(a,u+"",r+"");e.setSequenceSegregation(i,e.isFullySegregated,s)}}async function Oe(e,i,n,o){const s=Array.isArray(i)?i:[i],c=Array.isArray(n)?n:[n];if(c.length!==s.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const l=t.Model.ownerOf(o)||he(e.get("identity"));if(!l)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const d=s[0].collections,u="string"==typeof d?d:d(o,l,e);c.forEach((t,r)=>{const i="string"==typeof s[r].collections?s[r].collections:s[r].collections(o,l,e);if(i!==u)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function Se(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(n)||he(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:await c(n,s,e);e.readFrom(l)}async function Me(e,i,n,o,s){const c=Array.isArray(i)?i:[i],l=Array.isArray(n)?n:[n];if(l.length!==c.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const d=t.Model.ownerOf(o)||he(e.get("identity"));if(!d)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(o,d,e);l.forEach((t,r)=>{const i="string"==typeof c[r].collections?c[r].collections:c[r].collections(o,d,e);if(i!==h)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function Ie(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(n)||he(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:c(n,s,e);e.readFrom(l)}function _e(e,t,i){return(i,a)=>{const n=[];if(!a){const r=o.Metadata.getAttributes(i);return r?.forEach(r=>{_e(e,t)(i.prototype,r)}),i}{const i="string"==typeof e?e:e.toString(),a=i+":data",s={collections:e},c={priority:35,group:i+":extract"};n.push(o.prop(),r.transient(),(i,a)=>{const n=o.Metadata.key(t,a),s=i.constructor,c=o.Metadata.get(s,n)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],o.Metadata.set(s,n,c);const d=o.Metadata.get(s,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],o.Metadata.set(s,t,d);const h={...o.Metadata.get(s,r.DBKeys.TRANSIENT)||{},[a]:{}};o.Metadata.set(s,r.DBKeys.TRANSIENT,h)},r.on(r.DBOperations.ALL,ve,s,c),r.onCreate(Oe,{collections:e},{priority:95,group:a}),r.onRead(Se,{collections:e},{priority:95,group:a}),r.onUpdate(Me,{collections:e},{priority:95,group:a}),r.onDelete(Ie,{collections:e},{priority:95,group:a}))}return o.apply(...n)(i,a)}}function xe(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(xe):e.constructor!==Object?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=xe(e[r]),t),{})}class Te extends t.JSONSerializer{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=o.Metadata.modelName(e.constructor)}catch(e){i=void 0}r[t.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return t.Model.relations(e).forEach(e=>{r[e]=a(r[e])}),r}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e){return require("json-stringify-deterministic")(xe(this.preSerialize(e)))}}function Ne(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class Fe extends t.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(xe(this.preSerialize(e,t)))}preSerialize(e,r=!0){const i=Object.assign({},e);let a;try{a=o.Metadata.modelName(e.constructor)}catch(e){a=void 0}function n(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(n):this.preSerialize(e)}return r&&(i[t.ModelKeys.ANCHOR]=a||e.constructor.name),t.Model.relations(e).forEach(e=>{i[e]=n.call(this,i[e])}),i}}class Re extends a.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new r.InternalError("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(e,t){const i=t.logger.for(this.getUser),{caName:a,caCert:n,caKey:o,url:s,hsm:c}=e;i.info(`Creating CA user for ${a} at ${s}`),i.verbose("Retrieving CA certificate from "+n);const l=await Z.getFirstDirFileNameContent(n);let d;if(c)i.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!o)throw new r.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);i.debug("Retrieving CA key from "+o),d=await Z.getFirstDirFileNameContent(o)}return i.debug("Loading Admin user for ca "+a),this._user=await Z.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:i}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[n]=e;if(!n)throw new r.InternalError("Missing Fabric CA configuration");const{url:o,tls:c,caName:l}=n;t.info(`Initializing CA Client for CA ${n.caName} at ${n.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];t.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await Z.getFileContent(h);t.debug("CA Certificate: "+g.toString());const p=new s(o,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(n,i);return t.debug("CA user loaded: "+f.getName()),{config:n,client:p}}async getCertificates(e,t=!0,...i){e instanceof a.Context?(i=[e],t=!0,e=void 0):"boolean"==typeof e?(t=e,e=void 0):"boolean"!=typeof t&&(i=[t,...i],t=!0);const{log:n}=(await this.logCtx(i,r.OperationKeys.READ,!0)).for(this.getCertificates);n.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const o=(await this.certificates.getCertificates(e||{},this.user)).result;return n.verbose(`Found ${o.certs.length} certificates`),n.debug(o.certs),t?o.certs.map(e=>e.PEM):o}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new T(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new T(n)}}async read(e,...t){const{log:i}=(await this.logCtx(t,r.OperationKeys.READ,!0)).for(this.read);let a;i.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n,...o){const{log:s}=(await this.logCtx(o,"register",!0)).for(this.register);let c;try{const{userName:o,password:l}=e,d={enrollmentID:o,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};c=await this.client.register(d,this.user),s.info(`Registration for ${o} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:n,key:o,rootCertificate:s}=t;a.verbose(`Generating Identity from certificate ${n} in msp ${r}`);const c=ce.fabricIdFromCertificate(n),l=ce.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:n,privateKey:o.toBytes(),rootCertificate:s},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});n=Re.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${n.id}`)}catch(e){throw this.parseError(e)}return n}async registerAndEnroll(e,t=!1,r="",i,a,n,...o){const{ctx:s}=(await this.logCtx(o,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,n,s),{userName:l}=e;return this.enroll(l,c,s)}async updateIdentity(e,t,r,...i){const{log:a,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const o=this.client.newIdentityService(),s=await o.getOne(e,this.user);await o.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(s.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=Re.identityFromEnrollment(u,this.config.caName,n);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=ee(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...i){const{log:a}=(await this.logCtx(i,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const n=await this.read(e);if(!n)throw new r.NotFoundError("Could not find enrollment with id "+e);let o;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:n.id};o=await this.client.revoke(e,this.user)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!o.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${o.errors.join("\n")}`);return o}}var De;e.CA_ROLE=void 0,(De=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",De.USER="user",De.CLIENT="client";const Pe=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,allowContextTransientMap:!1,rebuildWithTransient:!0,encryptTransient:!1,syntheticEvents:!0}),$e=new c.MiniLogger("fabric-fs");async function Be(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Ke(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}async function ke(e,t){return{mspId:e,credentials:await Be(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Le(e);return await t.readFile(r)})}}async function Le(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}async function je(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}async function ze(e){const t=await Be(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Le(e);return await t.readFile(r)}),r=await Ue(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}async function Ue(e){let t;if(c.isBrowser())t=globalThis.crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),n=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));try{return await t.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new r.InternalError(e)}}const He=["allowGenerationOverride"];class Ge extends a.Context{constructor(e){super(e)}toOverrides(){const e={};for(const t of He){const r=this.getOrUndefined(t);void 0!==r&&(e[t]=r)}return e}}function qe(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class Ve extends a.Statement{constructor(e,t){super(e,t)}squash(e){const t=super.squash(e);if(!t)return t;const{method:i,params:n,args:o}=t,{direction:s,limit:c}=n;switch(i){case a.PreparedStatementKeys.FIND:break;case a.PreparedStatementKeys.PAGE:o.push(s,c);break;case a.PreparedStatementKeys.FIND_BY:break;case a.PreparedStatementKeys.LIST_BY:o.push(s);break;case a.PreparedStatementKeys.PAGE_BY:o.push(s,c);break;case a.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new r.InternalError("Unsupported method "+i)}return t}async executePrepared(...e){const t=a.Repository.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return t.statement(r,...i,...e)}async prepare(e){if(!(e=e||await this.adapter.context(a.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector)))throw new r.InternalError("No context available for statement");if(this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],i={},n={class:this.fromSelector,args:t,params:i},o=[a.QueryClause.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);o.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&o.push(a.QueryClause.SELECT,this.selectSelector.join(` ${a.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(o.push(a.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),t.push(this.orderBySelectors[0][1])),n.method=c.toCamelCase(o.join(" ")),n.params=i,this.prepared=n,this}processRecord(e,n){const s=t.Model.pk(this.fromSelector),c=o.Metadata.get(this.fromSelector,o.Metadata.key(r.DBKeys.ID,s))?.type;if(e[i.CouchDBKeys.ID]){const[,...t]=e[i.CouchDBKeys.ID].split(i.CouchDBKeys.SEPARATOR),r=t.join("_");e[s]=a.Sequence.parseValue(c,r)}return super.processRecord(e,n)}async raw(e,...t){const{ctx:r}=this.logCtx(t,this.raw),i=e?.aggregateInfo;if(e?.aggregate&&i)return this.executeAggregate(i,r);const a=await this.adapter.raw(e,!0,this.fromSelector,r);if(!this.selectSelector){const e=a.map(e=>this.processRecord(e,r));return r.getOrUndefined("afterQueryHandlers")?await this.applyAfterHandlersToResult(e,r):e}return a}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const n={};n[i.CouchDBKeys.TABLE]={},n[i.CouchDBKeys.TABLE]=t.Model.tableName(this.fromSelector);const o={selector:n};if(this.selectSelector&&(o.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(a.Condition.and(this.whereCondition,a.Condition.attribute(i.CouchDBKeys.TABLE).eq(o.selector[i.CouchDBKeys.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(i.CouchDBGroupOperator).indexOf(r[0]))switch(r[0]){case i.CouchDBGroupOperator.AND:t[i.CouchDBGroupOperator.AND]=[...Object.values(t[i.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const a=r[0];return a===i.CouchDBGroupOperator.AND?e.push(...t[a]):e.push(t),e},[])],o.selector=t;break;case i.CouchDBGroupOperator.OR:{const e={};e[i.CouchDBGroupOperator.AND]=[t,...Object.entries(o.selector).map(([e,t])=>{const r={};return r[e]=t,r})],o.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{o.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${o.selector[t]} by ${r}`),o.selector[t]=r})}if(this.orderBySelectors?.length){o.sort=o.sort||[],o.selector=o.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,a={};a[r]=t,o.sort.push(a),o.selector[r]||(o.selector[r]={},o.selector[r][i.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?o.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+i.CouchDBQueryLimit),o.limit=i.CouchDBQueryLimit),this.offsetSelector&&(o.skip=this.offsetSelector),o}parseCondition(e){const{attr1:t,operator:r,comparison:n}=e;if(r===a.Operator.STARTS_WITH){if("string"!=typeof t)throw new a.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("STARTS_WITH requires a string comparison");const e={start:o=n,end:qe(o)},r={};return r[t]={},r[t][i.CouchDBOperator.BIGGER_EQ]=e.start,r[t][i.CouchDBOperator.SMALLER]=e.end,{selector:r}}var o,s;if(r===a.Operator.ENDS_WITH){if("string"!=typeof t)throw new a.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("ENDS_WITH requires a string comparison");const e={};return e[t]={[i.CouchDBOperator.REGEXP]:(s=n,s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(r===a.Operator.BETWEEN){const e=t;if(!Array.isArray(n)||2!==n.length)throw new a.QueryError("BETWEEN operator requires [min, max] comparison");const[r,o]=n,s={};return s[e]={},s[e][i.translateOperators(a.Operator.BIGGER_EQ)]=r,s[e][i.translateOperators(a.Operator.SMALLER_EQ)]=o,{selector:s}}let c={};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(r))c[t]={},c[t][i.translateOperators(r)]=n;else if(r===a.Operator.NOT)c=this.parseCondition(t).selector,c[i.translateOperators(a.Operator.NOT)]={},c[i.translateOperators(a.Operator.NOT)][t.attr1]=n;else{const e=this.parseCondition(t).selector,a=this.parseCondition(n).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(i.translateOperators(r),e,a).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",t=this.createAggregateDescriptor("sum",e),r=this.createAggregateDescriptor("count",e);if(!t||!r)throw new a.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:t.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of r){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new a.QueryError(`No CouchDB view metadata found for table ${t.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const a=i.findViewMetadata(this.fromSelector,e,r);if(!a.length)return;const n=a[0],o=t.Model.tableName(this.fromSelector),s=i.generateViewName(o,n.attribute,e,n),c=n.ddoc||i.generateDesignDocName(o,s),l={reduce:void 0!==n.reduce||!n.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:n,descriptor:{ddoc:c,view:s,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,t){if("avg"!==e.kind)throw new a.QueryError("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,n]=[e.sumDescriptor,e.countDescriptor],[o,s]=await Promise.all([r.view(i.ddoc,i.view,i.options,t),r.view(n.ddoc,n.view,n.options,t)]),c=o.rows?.[0]?.value??0,l=s.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,t){if("avg"===e.kind)throw new a.QueryError("Average results should be handled before processing rows");const r=t.rows||[],i=e,n=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(e=>e.key??e.value):n.returnDocs?r.map(e=>e.value??e.doc??e):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}var Ye;class Je extends a.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Y}static{this.log=c.Logging.for(Je)}get Context(){return Ge}constructor(e,t){super(Object.assign({},Pe,e),X,t),this.serializer=Je.serializer}chaincodeFor(e,...t){return Je.chaincodeFor(e,this.config,...t)}channelFor(e,...t){return Je.channelFor(e,this.config,...t)}contractFor(e,...t){return Je.contractFor(e,this.config,...t)}Statement(e){return new Ve(this,e)}Paginator(e,t,r){return new M(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,r,i,...n){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.Model.tableName(e)):t.Model.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let o=n.pop();void 0===o||o instanceof a.Context||(n.push(o),o=void 0),r=o?Object.assign({},o.toOverrides(),r):r;const s=await this.flags("string"==typeof e?e:e.name,i,r,...[...n,o].filter(Boolean));if(o){if(!(o instanceof this.Context)){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}const t=o.getOrUndefined("operation"),r=o.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}return o.accumulate(s)}return(new this.Context).accumulate({...s})}decode(e){return Je.decoder.decode(e)}repository(){return H}createPrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.createPrefix),s=t.Model.tableName(e),c={};return c[i.CouchDBKeys.TABLE]=s,Object.assign(c,a),[e,r,c,...o]}createAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.createAllPrefix),l=a.map((e,t)=>{const r={};return r[i.CouchDBKeys.TABLE]=s,Object.assign(r,n[t]),r});return[e,a,l,...c]}updateAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.updateAllPrefix),l=a.map(()=>{const e={};return e[i.CouchDBKeys.TABLE]=s,e});return[e,a,l,...c]}async createAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.createAll),d=t.Model.tableName(e);c.info(`adding ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=a.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,r.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(g)],u?{[d]:s}:void 0,this.getEndorsingOrganizations(l),e);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,f[0][t.Model.pk(e)]||i[0])?this.readAll(e,W(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s?.[r]||{}),f[r])),i),l):f}async readAll(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.readAll),s=t.Model.tableName(e);n.info(`reading ${i.length} entries to ${s} table`),n.verbose("pks: "+i);const c=await this.evaluateTransaction(o,r.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(i)],void 0,void 0,e);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}async updateAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.updateAll),d=t.Model.tableName(e);c.info(`updating ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=a.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,r.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(g)],u?{[d]:s}:void 0,this.getEndorsingOrganizations(l),e);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,i[0])?this.readAll(e,W(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s?.[r]||{}),f[r])),i),l):f}async deleteAll(e,i,...a){const{log:n,ctx:o,ctxArgs:s}=this.logCtx(a,this.deleteAll),c=t.Model.tableName(e),l=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let d;const u=this.shouldRefreshAfterWrite(e,o,l,i[0]);u&&(d=await this.readAll(e,i,...s)),n.info(`deleting ${i.length} entries to ${c} table`),n.verbose("pks: "+i);const h=await this.submitTransaction(o,r.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(i)],void 0,this.getEndorsingOrganizations(o),e);try{return u?d:JSON.parse(this.decode(h)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}prepare(e,...i){const{log:n,ctx:o}=this.logCtx(i,this.prepare),s=t.Model.segregate(e);e[a.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+e[a.PersistenceKeys.METADATA]),Object.defineProperty(s.model,a.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[a.PersistenceKeys.METADATA]}));const c=t.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new r.InternalError("No mirror MSP could be found");let t=this.getEndorsingOrganizations(o)||[];t=Array.isArray(t)?t:[t];const i=[...new Set([...t,e])];o.accumulate({endorsingOrgs:i,endorsingOrganizations:i,legacy:!0})}return{record:s.model,model:s.model,id:e[t.Model.pk(e.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(e,t,r,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(o,o.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&n.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,a){if(!i)return!1;const n=t.Model.pk(e),o=t.Model.composed(e,n),s=t.Model.generated(e,n),c=null!=a;return!(c||!o)||(!c&&s?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}injectTransientOverrides(t,r){const i=this.hasMeaningfulTransientData(t),a=!!r.getOrUndefined("allowContextTransientMap");if(!i&&!a)return;const n=r.toOverrides(),o=i?Object.assign({},t):{};return a&&Object.keys(n).length&&(o[e.FabricModelKeys.OVERRIDES]=n),Object.keys(o).length?o:void 0}hasMeaningfulTransientData(e){if(null==e)return!1;if(Array.isArray(e))return e.some(e=>this.hasMeaningfulTransientData(e));if("object"!=typeof e)return!0;const t=Object.entries(e);return!!t.length&&t.some(([,e])=>this.hasMeaningfulTransientData(e))}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(e){return!!this.config.allowGatewayOverride}async create(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.create),d=t.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=await this.submitTransaction(l,r.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],u?{[d]:n}:void 0,this.getEndorsingOrganizations(l),e),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,W(e,t.Model.merge(Object.assign({},a,n||{}),p,e),i),l):p}async healthcheck(e,...r){const{log:i,ctx:a}=this.logCtx(r,this.healthcheck),n=t.Model.tableName(e);i.verbose(`reading entry from ${n} table`);const o=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e);return JSON.parse(this.decode(o))}async read(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.read),s=t.Model.tableName(e);n.verbose(`reading entry from ${s} table`),n.debug("pk: "+i);const c=await this.evaluateTransaction(o,r.OperationKeys.READ,[i.toString()],void 0,void 0,e);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,r,a,...n){const o=t.Model.tableName(e),{ctxArgs:s}=this.logCtx(n,this.updatePrefix),c={};return c[i.CouchDBKeys.TABLE]=o,Object.assign(c,a),[e,r,c,...s]}async update(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=t.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=await this.submitTransaction(l,r.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name)],u?{[d]:n}:void 0,this.getEndorsingOrganizations(l),e),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,W(e,t.Model.merge(Object.assign({},a,n||{}),p,e),i),l):p}async delete(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.delete),s=t.Model.tableName(e),c=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let l;const d=this.shouldRefreshAfterWrite(e,o,c,i);d&&(l=await this.read(e,i,o)),n.verbose(`deleting entry from ${s} table`),n.debug("pk: "+i);const u=await this.submitTransaction(o,r.OperationKeys.DELETE,[i.toString()],void 0,this.getEndorsingOrganizations(o),e);return d?l:this.serializer.deserialize(this.decode(u))}async raw(e,i=!0,a,...n){const{log:o,ctx:s}=this.logCtx(n,this.raw);let c,l;o.info("Performing raw statement on table "+t.Model.tableName(a));try{c=await this.evaluateTransaction(s,"raw",[JSON.stringify(e),i],void 0,void 0,a)}catch(e){throw this.parseError(e)}try{l=JSON.parse(this.decode(c))}catch(e){throw new r.SerializationError("Failed to process result: "+e)}if(Array.isArray(l)){if(!l.length)return l;const e=l[0];return t.Model.isModel(e)?l.map(e=>t.Model.build(e)):l}return d=l,t.Model.isModel(d)?t.Model.build(d):d;var d}async view(e,t,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.view);let s,c;n.info(`Querying view ${e}/${t}`);try{s=await this.evaluateTransaction(o,"view",[e,t,JSON.stringify(i)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(s))}catch(e){throw new r.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Je.getClient(this.config)),this._client}async Gateway(e){return Je.getGateway(e,this.config,this.client)}async Contract(e,t){return Je.getContract(await this.Gateway(e),this.config,t,e)}async transaction(e,t,r=!0,i,a={},n,o){const s=this.log.for(this.transaction);if(a=this.injectTransientOverrides(a,e),r&&this.shouldUseLegacyGateway(e)){const r=this.prepareLegacyArgs(i),n=this.buildLegacyTransient(a),s=this.buildLegacyPeerConfigs(e);return await this.submitLegacyWithExplicitEndorsers(e,t,r,n,s,o)}const c=await this.Gateway(e);try{const c=await this.Contract(e,o);s.verbose(`${r?"Submit":"Evaluate"}ting transaction ${c.getContractName()}.${t}`),s.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate,d=(i||[]).map(e=>this.normalizeTransactionArgument(e)),u=Object.entries(a||{});n=n?.length?n:void 0;const h={arguments:d,transientData:u.length?u.reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}):void 0,endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,t,h)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}normalizeTransactionArgument(e){return null==e||"string"==typeof e||"object"!=typeof e||e instanceof Uint8Array?e:JSON.stringify(e)}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}resolveLegacyMspCount(){const e=this.config.legacyMspCount??1,t=Number(e);return!Number.isFinite(t)||1>t?1:Math.floor(t)}pickLegacyCandidates(e,t){if(!e.length||0>=t)return[];const r=[...e],i=Math.min(t,r.length),a=[];for(;a.length<i&&r.length;){const e=Math.floor(Math.random()*r.length),[t]=r.splice(e,1);t&&a.push(t)}return a}buildLegacyPeerConfigs(e){const t=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}];let r=this.getEndorsingOrganizations(e)||[];r=Array.isArray(r)?r:[r];const i=(r.filter(e=>!!e)||[]).filter(e=>e!==this.config.mspId);if(!i.length)return t;const n=this.config.mspMap,o=this.resolveLegacyMspCount();for(const e of i){const r=n?.[e];if(!r?.length)throw new a.UnsupportedError(`No peer mapping available for MSP ${e}. Provide it via config.mspMap`);const i=this.pickLegacyCandidates(r,o);if(!i.length)throw new a.UnsupportedError(`No valid peer mapping available for MSP ${e}. Provide it via config.mspMap`);for(const r of i){if(!r.endpoint)throw new a.UnsupportedError(`Invalid peer mapping for MSP ${e}: missing endpoint`);t.push({mspId:e,peerEndpoint:r.endpoint,peerHostAlias:r.alias,tlsCert:r.tlsCert||this.config.tlsCert})}}return t}async submitLegacyWithExplicitEndorsers(e,t,i,a,n,o){const s=this.log.for(this.submitLegacyWithExplicitEndorsers),c=this.normalizeLegacyPeers(n),l=await this.resolveLegacyIdentityMaterial(),d=await f.Wallets.newInMemoryWallet(),u=this.config.mspId+"-legacy";await d.put(u,{credentials:{certificate:l.certificate,privateKey:l.privateKey},mspId:this.config.mspId,type:"X.509"});const h=await this.buildLegacyConnectionProfile(c),g=new f.Gateway;try{await g.connect(h,{identity:u,wallet:d,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(c)},tlsInfo:{certificate:l.certificate,key:l.privateKey}});let n=this.config.channel,p=this.config.chaincodeName,f=this.config.contractName;if(o)if("string"==typeof o)f=o;else{if(!e)throw new r.InternalError("No context received to determine chaincode config");n=await this.channelFor(o,e)||n,p=await this.chaincodeFor(o,e)||p,f=await this.contractFor(o,e)}const y=await g.getNetwork(n),m=y.getContract(p,f).createTransaction(t);a&&m.setTransient(a);const w=c.map(e=>y.getChannel().getEndorser(e.name)).filter(e=>!!e);w.length&&m.setEndorsingPeers(w),s.verbose(`Legacy submitting ${f}.${t} via peers ${c.map(e=>e.peerEndpoint).join(", ")}`);const b=await m.submit(...i);return Uint8Array.from(b)}catch(e){throw this.parseError(e)}finally{g.disconnect()}}normalizeLegacyPeers(e){const t=new Map,r=e=>{const r=`${e.peerEndpoint}|${e.peerHostAlias||""}`;if(t.has(r))return;const i=`peer-${e.mspId}-${t.size}`;t.set(r,{...e,name:i})};return e.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(t.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(e){const t={},r={},i={};for(const a of e){const e=await this.readPemInput(a.tlsCert||this.config.tlsCert),n=a.peerHostAlias||this.extractHost(a.peerEndpoint);t[a.name]={url:this.ensureGrpcUrl(a.peerEndpoint),tlsCACerts:{pem:e},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[a.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[a.mspId]=i[a.mspId]||{mspid:a.mspId,peers:[]},i[a.mspId].peers.push(a.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:t,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(e){return e.every(e=>this.isLocalEndpoint(e.peerEndpoint))}isLocalEndpoint(e){const t=this.extractHost(e).toLowerCase();return"localhost"===t||"127.0.0.1"===t}extractHost(e){return e.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(e){return/^grpcs?:\/\//i.test(e)?e:"grpcs://"+e}async readPemInput(e){if(!e)throw new r.InternalError("Missing certificate or key material");if(Buffer.isBuffer(e))return e.toString("utf8");const t=e.trim();if(/-----BEGIN [A-Z ]+-----/.test(t))return t;const i=await y.promises.stat(e).catch(()=>{});return i?.isDirectory()?await je(e):(await Ke(e)).toString()}parseError(e){return Je.parseError(e)}async submitTransaction(e,t,r,i,a,n){return this.transaction(e,t,!0,r,i,a,n)}async evaluateTransaction(e,t,r,i,a,n){return this.transaction(e,t,!1,r,i,a,n)}async migrate(e,...t){const{ctx:r}=(await this.logCtx(t,a.PersistenceKeys.MIGRATION,!0)).for(this.migrate);return this.submitTransaction(r,"migrate",[e,t],void 0,void 0,"MigrationContract")}async shutdown(...e){await super.shutdown(...e),this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static async getContract(e,t,i,a){const n=this.log.for(this.getContract);let o=t.channel,s=t.chaincodeName,c=t.contractName;if(i)if("string"==typeof i)c=i;else{if(!a)throw new r.InternalError("No context received to determine chaincode config");o=await this.channelFor(i,t,a)||o,s=await this.chaincodeFor(i,t,a)||s,c=await this.contractFor(i,t,a)}const l=this.getNetwork(e,o);let d;try{n.debug(`Retrieving chaincode ${s} contract ${c} from network ${o}`),d=l.getContract(s,c)}catch(e){throw this.parseError(e)}return d}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let i=e.tlsCert;if("string"==typeof i)if(i.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))i=Buffer.from(i,"utf8");else try{i=Buffer.from(y.readFileSync(i,"utf8"))}catch(e){throw new r.InternalError(`Failed to read the tls certificate from ${i}: ${e}`)}const a=b.credentials.createSsl(i);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,t,r){const i=c.Logging.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const n=await ke(t.mspId,t.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+ce.fabricIdFromCertificate(n.credentials.toString()))}catch(e){i.error("Failed to extract Fabric ID from certificate",e)}let o;if(t.hsm)throw new a.UnsupportedError("HSM NOT IMPLEMENTED");o=await ze(t.keyCertOrDirectoryPath);const s={client:e,identity:n,signer:o,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+t.mspId);const d=l.connect(s);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Je._baseDispatch(this.client)}static chaincodeFor(e,r,...i){return t.Model.chaincodeOf(e,...i)||r.chaincodeName}static channelFor(e,r,...i){return t.Model.channelOf(e,...i)||r.channel}static contractFor(e,r,...i){return t.Model.contractOf(e,...i)||ue(e,...i)}static parseError(e){let t="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(t=""+e.details[0].message),e instanceof l.EndorseError&&e.details.length&&10===e.code&&e.details[0].message?.includes(a.UnsupportedError.name)&&(t=""+e.details[0].message),t.includes("MVCC_READ_CONFLICT")?new B(e):t.includes("DEADLINE_EXCEEDED")?new j(e):t.includes("chaincode stream terminated")||t.includes("RESOURCE_EXHAUSTED")||t.includes("received message larger than max")||t.includes("grpc: received message larger")?new U(e):t.includes("ENDORSEMENT_POLICY_FAILURE")?new k(e):t.includes("PHANTOM_READ_CONFLICT")?new K(e):e instanceof Error&&e.code&&9===e.code?new $(e):t.includes(r.ValidationError.name)?new r.ValidationError(e):t.includes(r.NotFoundError.name)?new r.NotFoundError(e):t.includes(r.ConflictError.name)?new r.ConflictError(e):t.includes(r.BadRequestError.name)?new r.BadRequestError(e):t.includes(a.QueryError.name)?new a.QueryError(e):t.includes(a.PagingError.name)?new a.PagingError(e):t.includes(a.UnsupportedError.name)?new a.UnsupportedError(e):t.includes(a.MigrationError.name)?new a.MigrationError(e):t.includes(a.ObserverError.name)?new a.ObserverError(e):t.includes(a.AuthorizationError.name)?new a.AuthorizationError(e):t.includes(a.ForbiddenError.name)?new a.ForbiddenError(e):t.includes(a.ConnectionError.name)?new a.ConnectionError(e):t.includes(r.SerializationError.name)?new r.SerializationError(e):new r.InternalError(e)}}n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"create",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"healthcheck",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"read",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"update",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"delete",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,"function"==typeof(Ye="undefined"!=typeof D&&D)?Ye:Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"raw",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String,String,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"view",null),Je.decoration(),a.Adapter.setCurrent(X);class We extends a.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(...e){const{log:t,ctxArgs:r}=(await this.logCtx(e,a.PersistenceKeys.SHUTDOWN,!0)).for(this.close);try{await super.close(...r)}catch(e){t.error("Failed to close Fabric proxies event listener",e)}if(this.listeningStack)try{await this.listeningStack.close()}catch(e){t.error("Failed to close Fabric event listener",e)}finally{this.listeningStack=void 0}}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof Je))throw new a.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,i,n,...o){const{log:s,ctxArgs:c}=a.Adapter.logCtx(this.updateObservers,i,!1,...o);if(this.adapter)try{await this.adapter.refresh(e,i,n,...c)}catch(e){throw new r.InternalError("Failed to refresh dispatch: "+e)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.Model.tableName(e)}:${i}`)}async handleEvents(e){if(!this.listeningStack)throw new r.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new r.InternalError("No adapter found. should be impossible");const i=e||await this.adapter.context(r.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:r,event:n,owner:o}=Ne(e.eventName);if(this.adapter.config?.mspEventOnly&&o&&o!==this.adapter.config?.mspId)continue;const s=this.parsePayload(e.payload);try{const e=(r?t.Model.get(r):t.Model.get(this.models[0].name))??(r||this.models[0]?.name),a=s.result?[s.result,i]:[i];await this.updateObservers(e,n,s.id,...a)}catch(e){a.error(`Failed update observables for table ${r} event ${n} id: ${s.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close(i)}}async initialize(){if(!this.adapter)throw new r.InternalError("No adapter or config observed for dispatch");const e=!1!==this.adapter.config.syntheticEvents;if(!e){const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t.Model),{ctx:i}=this.logCtx([e],this.initialize),a=(await Je.getGateway(i,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new r.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(i)}[r.OperationKeys.CREATE,r.OperationKeys.UPDATE,r.OperationKeys.DELETE,r.BulkCrudOperationKeys.CREATE_ALL,r.BulkCrudOperationKeys.UPDATE_ALL,r.BulkCrudOperationKeys.DELETE_ALL].forEach(i=>{if(!this.adapter)throw new r.InternalError("No adapter provided for the fallback of fully segregated models");if(!this.adapter[i])throw new r.InternalError(`Method ${i} not found in ${this.adapter.alias} adapter to bind Observables Dispatch`);let a=Object.getOwnPropertyDescriptor(this.adapter,i),n=this.adapter;for(;!a&&n!==Object.prototype;)n=Object.getPrototypeOf(n),a=Object.getOwnPropertyDescriptor(n,i);function o(e){switch(e){case r.BulkCrudOperationKeys.CREATE_ALL:return r.OperationKeys.CREATE;case r.BulkCrudOperationKeys.UPDATE_ALL:return r.OperationKeys.UPDATE;case r.BulkCrudOperationKeys.DELETE_ALL:return r.OperationKeys.DELETE;default:return e}}a&&a.writable?this.adapter[i]=new Proxy(this.adapter[i],{apply:async(r,a,n)=>{const s=await r.apply(a,n),c=n[0];if(!e&&!t.Model.isTransient(c))return s;const{log:l,ctxArgs:d,ctx:u}=a.logCtx(n.slice(n.length-1),r),h=n[1],g=[c,o(i),h];return u.getOrUndefined("observeFullResult")&&g.push(s),this.updateObservers(g[0],g[1],g[2],...g.slice(3),...d).catch(e=>l.error(`Failed to dispatch observer refresh for ${i} on ${c.name||c} for ${h}: ${e}`)),s}}):this.log.error(`Could not find method ${i} to bind Observables Dispatch`)})}}Je&&(Je._baseDispatch=We);const Qe="##VERSION##",Xe="##PACKAGE##";o.Metadata.registerLibrary(Xe,Qe),e.AllowanceError=x,e.BalanceError=_,e.BaseEncoder=se,e.COMMIT="ff3d1a6",e.ClientSerializer=Y,e.CoreUtils=Z,e.CryptoUtils=ce,e.DefaultContractResolver=ue,e.DefaultFabricClientFlags=Pe,e.DeterministicSerializer=Te,e.EndorsementError=$,e.EndorsementPolicyError=k,e.FULL_VERSION="0.13.28-ff3d1a6",e.FabricClientAdapter=Je,e.FabricClientContext=Ge,e.FabricClientDispatch=We,e.FabricClientRepository=H,e.FabricERC20ClientRepository=J,e.FabricEnrollmentService=le,e.FabricFlavour=X,e.FabricIdentityService=Re,e.ImplicitPrivateCollection=Ce,e.MissingContextError=N,e.MissingPKCSS11Lib=P,e.ModelCollection=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!a)throw new r.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(n.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=B,e.NamespaceCollection=e=>(i,a)=>{const n=a||("function"!=typeof i?t.Model.ownerOf(i):void 0),o="function"==typeof i?i:i.constructor;if(!n)throw new r.InternalError(`Model ${o.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${n?c.toPascalCase(n):""}`},e.NotInitializedError=R,e.OverflowError=I,e.Owner=function(){return function(e,t,i){const n=i.value;return i.value=async function(...e){const i=e[0],o=i.clientIdentity.getID(),s=await this.tokenRepository.select(),c=await s.execute(i);if(0==c.length)throw new r.NotFoundError("No tokens avaialble");if(c.length>1)throw new r.NotFoundError("To many token available : "+c.length);if(c[0].owner!=o)throw new a.AuthorizationError(`User not authorized to run ${t} on the token`);return await n.apply(this,e)},i}},e.PACKAGE_NAME=Xe,e.PhantomReadConflictError=K,e.QueryResultTooLargeError=U,e.RegistrationError=T,e.RegistrationRequestBuilder=de,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=Fe,e.TransactionBufferSizeError=z,e.TransactionLimitsError=L,e.TransactionTimeoutError=j,e.UnauthorizedPrivateDataAccess=F,e.VERSION=Qe,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new I(`Addition overflow: ${e} + ${t}`);return r},e.applyMirrorFlags=async(e,r,i)=>{if(!r)return;const a=t.Model.mirroredAt(e);if(!a)return;if(!(r===a.mspId||a.condition&&a.condition(r)))return;const n=await fe(new e,a.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)},e.applySegregationFlags=Ae,e.chaincode=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CHAINCODE,r)},e.channel=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CHANNEL,r)},e.collectionFor=v,e.contentOfLoadFile=Be,e.contract=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CONTRACT,r)},e.createMirrorHandler=ye,e.deleteMirrorHandler=we,e.evalMirrorMetadata=fe,e.extractCollections=async(e,i,a={},n=!1)=>{let{privateCols:o,sharedCols:s}=t.Model.collectionsFor(e);function c(t){try{return"string"==typeof t?t:t(e,i[0])}catch(e){throw new r.InternalError(e)}}o=o.map(c),s=s.map(c);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.sharedCols||{}),u=n?t.Model.mirroredAt(e):void 0,h=i.map(e=>o.map(t=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n}=l;return O(e,t,r,i,a,n,!1)})).flat();if(u&&u.mspId){const t="string"==typeof u.resolver?u.resolver:u.resolver(e,u.mspId);if(t&&!h.some(e=>e.name===t&&e.policy.includes(u.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:a}=l;h.push(O(u.mspId,t,e,r,i,a,!1))}}return{privates:h,shared:s.map(e=>{const{requiredPeerCount:t,maxPeerCount:r,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}=d;return S(i,e,t,r,a,n,o)})}},e.extractIds=W,e.extractMspId=he,e.extractPrivateKey=Ue,e.extractSegregatedCollections=ve,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=i.generateViews([e]),a=t||{};return r.forEach(e=>{a[e._id]=e}),r},e.generateModelIndexes=(e,r)=>{const a=i.generateIndexes([e]),n=((e,r)=>{try{return t.Model.pk(e)+""}catch{const t=`Skipping ${e.name} while extracting indexes: no primary key is defined`;return void r.verbose(t)}})(e,r);return((e,t)=>t?e.map(e=>{const r=e?.index?.fields;if(!e?.name||"string"!=typeof e.name||!e.name.includes("defaultQuery")||!Array.isArray(r)||0===r.length)return e;if(r.filter(e=>"object"==typeof e&&!Array.isArray(e)).length!==r.length)return e;if(r.some(e=>!(!e||"object"!=typeof e||Array.isArray(e))&&Object.prototype.hasOwnProperty.call(e,t)))return e;const i=r[r.length-1],a="desc"===((Object.values(i||{})[0]||"asc")+"").toLowerCase()?"desc":"asc";return Object.assign({},e,{index:Object.assign({},e.index,{fields:[...r,{[t]:a}]})})}):e)(a,n||"")},e.getAkiAndSerialFromCert=ee,e.getCAUser=async(e,t,r,i)=>{$e.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),n=d.User.newCryptoSuite();a.setCryptoSuite(n);const o=n.createKeyFromRaw(t);return await a.setEnrollment(o,r,i),a},e.getFirstDirFileName=Le,e.getFirstDirFileNameContent=je,e.getIdentity=ke,e.getSigner=ze,e.mirror=(t,i,a)=>{const n="string"!=typeof i&&!!i,s=n?void 0:i,c=n?i:a;return o.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,i,a)=>{const n={condition:a,mspId:i,resolver:t};return o.apply(o.metadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),n),r.onRead(Ee,n,{priority:30}),r.onCreate(be,n,{priority:20}),r.onUpdate(be,n,{priority:20}),r.onDelete(be,n,{priority:20}),r.onCreate(ye,n,{priority:100}),r.onUpdate(me,n,{priority:100}),r.onDelete(we,n,{priority:100}))},args:[t,s,c]}).apply()},e.mirrorWriteGuard=be,e.ownedBy=()=>o.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(i,a)=>o.apply(t.required(),r.generated(),r.readonly(),r.onCreate(ge),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(i,a),args:[]}).apply(),e.ownedByOnCreate=ge,e.parseEventName=Ne,e.privateCollectionFor=O,e.privateData=(t=Ce)=>o.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>_e(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=Ke,e.readMirrorHandler=Ee,e.readModelFile=C,e.readModelFolders=async(...e)=>{const t=require("fs"),r=require("path"),i=[];for(const a of e){const e=r.resolve(a),n=t.readdirSync(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const e of n)i.push(...C(e))}return i},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string contains digits"));const i=parseInt(e);if(isNaN(i))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return i},e.segregatedDataOnCreate=Oe,e.segregatedDataOnDelete=Ie,e.segregatedDataOnRead=Se,e.segregatedDataOnUpdate=Me,e.sharedCollectionFor=S,e.sharedData=t=>o.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>_e(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sortKeysOnlyRecursive=xe,e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new I(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>o.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(i,a)=>o.apply(t.required(),r.readonly(),r.onCreate(pe),r.onUpdate(pe),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(i,a),args:[]}).apply(),e.transactionIdOnCreate=pe,e.updateMirrorHandler=me,e.writeCollectionDesignDocs=(e,t=process.cwd(),r)=>{e?.length&&A(e,t,r)},e.writeCollections=(e,t=process.cwd(),r="collections_config")=>{const i=require("fs"),a=require("path"),n=a.resolve(a.join(t,`./META-INF/${r}.json`));!function e(t){const r=a.dirname(t);if(i.existsSync(r))return!0;e(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))},e.writeDesignDocs=A,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));E(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("@decaf-ts/core"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("fabric-network"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","@decaf-ts/core","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fabric-network","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.decafTsCore,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fabricNetwork,e.fs);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,i,a,n,o,s,c,l,d,u,h,g,p,f,y){"use strict";function m(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var w=m(h),b=m(p);function E(e){const t=require("fs"),r=require("path").dirname(e);if(t.existsSync(r))return!0;E(r),t.mkdirSync(r)}function C(e){const r=require("path").resolve(e.parentPath,e.name),i=require(r);return Object.values(i).filter(e=>{try{return new e instanceof t.Model}catch{return!1}})}function A(e,t=process.cwd(),r){if(!e.length)return;const i=require("fs"),a=require("path");e.forEach(e=>{const n=e._id.replace(/^_design\//,""),o=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}design_docs/${n}.json`));E(o);const s={...e};delete s._rev,i.writeFileSync(o,JSON.stringify(s,void 0,2))})}function v(e,t,r,i,a,n,o){return{name:e,policy:t,requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}}function O(e,t=e+"Private",r=0,i=0,a=0,n=!0,o=!0){const s=v(t,`OR('${e}.member')`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`OR('${e}.peer')`},s}function S(e,t,r=1,i=2,a=0,n=!0,o=!0){const s=v(t,`OR(${e.map(e=>`'${e}.member'`).join(",")})`,r,i,a,n,o);return s.endorsementPolicy={signaturePolicy:`AND(${e.map(e=>`'${e}.peer'`).join(",")})`},s}class M extends a.Paginator{constructor(e,t,r,i){super(e,t,r,i)}prepare(e){throw new a.UnsupportedError("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(e=1,...t){return super.page(e,...t)}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)}}class I extends r.InternalError{constructor(e){super(e,I.name)}}class _ extends r.InternalError{constructor(e){super(e,_.name)}}class x extends r.InternalError{constructor(e){super(e,x.name)}}class T extends a.AuthorizationError{constructor(e){super(e,T.name)}}class N extends r.InternalError{constructor(e){super(e,N.name,500)}}class F extends r.BaseError{constructor(e="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(F.name,e,403)}}class R extends r.BaseError{constructor(e){super(R.name,e,409)}}class P extends r.InternalError{constructor(e){super(e,P.name,500)}}class $ extends r.InternalError{constructor(e){super(e,$.name,500)}}class B extends r.InternalError{constructor(e){super(e,B.name,500)}}class K extends r.InternalError{constructor(e){super(e,K.name,500)}}class k extends r.InternalError{constructor(e){super(e,k.name,500)}}class L extends r.InternalError{constructor(e,t=L.name,r=590){super(e,t,r)}}class j extends r.InternalError{constructor(e){super(e,j.name,591)}}class z extends r.InternalError{constructor(e){super(e,z.name,592)}}class U extends L{constructor(e){super(e,U.name,593)}}class H extends a.Repository{constructor(e,t,r=!1){super(e,t,r),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1,rebuildWithTransient:!1})}override(e){return super.override(Object.assign({},e,this._overrides)).for(e)}ObserverHandler(){return super.ObserverHandler()}async paginateBy(e,r,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return o.verbose(`paginating ${t.Model.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,e,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...s)}async listBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);n.verbose(`listing ${t.Model.tableName(this.class)} by ${e} ${r}`);try{return await this.statement(this.listBy.name,e,r,...o)}catch(i){if(i instanceof U)return n.warn(`listBy result set too large for ${t.Model.tableName(this.class)} key=${e+""} order=${r}. Returning empty list. Use paginateBy for large datasets.`),[];throw i}}async findBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return n.verbose(`finding all ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findBy.name,e,r,...o)}async findOneBy(e,r,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return n.verbose(`finding One ${t.Model.tableName(this.class)} with ${e} ${r}`),await this.statement(this.findOneBy.name,e,r,...o)}async find(e,r=a.OrderDirection.ASC,...i){const{log:n,ctxArgs:o}=(await this.logCtx(i,a.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.find.name,e,r,...o)}async page(e,r=a.OrderDirection.ASC,i={offset:1,limit:10},...n){const{log:o,ctxArgs:s}=(await this.logCtx(n,a.PreparedStatementKeys.PAGE,!0)).for(this.page);return o.verbose(`paging ${t.Model.tableName(this.class)} by default query attributes`),await this.statement(this.page.name,e,r,i,...s)}async statement(e,...r){const{log:n,ctx:o,ctxArgs:s}=(await this.logCtx(r,a.PersistenceKeys.STATEMENT,!0)).for(this.statement);n.verbose("Executing prepared statement "+e);const c=s.slice(0,-1),l=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(o,a.PersistenceKeys.STATEMENT,[e,JSON.stringify(c)],void 0,void 0,this.class)));let d;return d=Array.isArray(l)?l.map(e=>e[i.CouchDBKeys.TABLE]&&e[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(e):e):l[i.CouchDBKeys.TABLE]&&l[i.CouchDBKeys.TABLE]===t.Model.tableName(this.class)?new this.class(l):M.isSerializedPage(l)?Object.assign(l,{data:l.data.map(e=>new this.class(e))}):l,this.applyAfterRead(d,o)}async applyAfterRead(e,i){return i.getOrUndefined("afterQueryHandlers")?e instanceof t.Model?(await r.enforceDBDecorators(this,i,e,r.OperationKeys.READ,r.OperationKeys.AFTER),e):Array.isArray(e)?(await Promise.all(e.map(e=>this.applyAfterRead(e,i))),e):M.isSerializedPage(e)?(await this.applyAfterRead(e.data,i),e):e:e}async countOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);i.verbose(`counting ${t.Model.tableName(this.class)}${e?" by "+e:""}`);const o=e?[e,...n]:n;return this.statement(a.PreparedStatementKeys.COUNT_OF,...o)}async maxOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return i.verbose(`finding max of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MAX_OF,e,...n)}async minOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return i.verbose(`finding min of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.MIN_OF,e,...n)}async avgOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return i.verbose(`calculating avg of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.AVG_OF,e,...n)}async sumOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return i.verbose(`calculating sum of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.SUM_OF,e,...n)}async distinctOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return i.verbose(`finding distinct values of ${e} in ${t.Model.tableName(this.class)}`),this.statement(a.PreparedStatementKeys.DISTINCT_OF,e,...n)}async groupOf(e,...r){const{log:i,ctxArgs:n}=(await this.logCtx(r,a.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return i.verbose(`grouping ${t.Model.tableName(this.class)} by ${e}`),this.statement(a.PreparedStatementKeys.GROUP_OF,e,...n)}async healthcheck(...e){const{ctxArgs:t}=this.logCtx(e,this.healthcheck);return await this.adapter.healthcheck(this.class,...t)}async create(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.create);a.debug(`Creating new ${this.class.name} in table ${t.Model.tableName(this.class)}`),this.ensureLegacyMirrorFlag(i,e);const o=this.adapter.prepare(e,i),{record:s,id:c,transient:l}=o,d=await this.adapter.create(this.class,c,s,l,...n);return this.adapter.revert(d,this.class,c,l,i)}async update(e,...r){const{ctxArgs:i,log:a,ctx:n}=this.logCtx(r,this.update);this.ensureLegacyMirrorFlag(n,e);const o=this.adapter.prepare(e,n),{id:s,transient:c}=o;let l=o.record;return a.debug(`updating ${this.class.name} in table ${t.Model.tableName(this.class)} with id ${s}`),l=await this.adapter.update(this.class,s,l,c,...i),this.adapter.revert(l,this.class,s,c,n)}async createAllPrefix(e,...t){const{ctx:i,ctxArgs:a}=(await this.logCtx(t,r.OperationKeys.CREATE,!0)).for(this.createAllPrefix),n=i.get("ignoreHandlers"),o=i.get("ignoreValidation");if(!e.length)return[e,...a];if(e=await Promise.all(e.map(async e=>(e=new this.class(e),n||await r.enforceDBDecorators(this,i,e,r.OperationKeys.CREATE,r.OperationKeys.ON),e))),!o){const t=i.get("ignoredValidationProperties")||[],a=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=r.reduceErrorsToPrint(a);if(n)throw new r.ValidationError(n)}return[e,...a]}async createAll(e,...r){if(!e.length)return e;const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=o.map(e=>e.record),l=o.map(e=>e.transient),d=await this.adapter.createAll(this.class,s,c,l,...n);return Promise.all(d.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,l[t],i)}))}async readAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${t.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...n)).map((t,r)=>this.adapter.revert(t,this.class,e[r],{},i))}async updateAll(e,...r){const{ctx:i,log:a,ctxArgs:n}=this.logCtx(r,this.updateAll);a.debug(`Updating ${e.length} new ${this.class.name} in table ${t.Model.tableName(this.class)}`),e.forEach(e=>this.ensureLegacyMirrorFlag(i,e));const o=e.map(e=>this.adapter.prepare(e,i)),s=o.map(e=>e.id),c=await this.adapter.updateAll(this.class,s,o.map(e=>e.record),o.map(e=>e.transient),...n);return Promise.all(c.map(async(e,t)=>{const r=s[t];return this.adapter.revert(e,this.class,r,o[t].transient,i)}))}ensureLegacyMirrorFlag(e,r){t.Model.mirroredAt(r)&&e.accumulate({legacy:!0})}}let G=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],G.prototype,"name",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],G.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],G.prototype,"symbol",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],G.prototype,"decimals",void 0),G=n.__decorate([a.table("erc20_tokens"),t.model(),n.__metadata("design:paramtypes",[Object])],G);let q=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),n.__metadata("design:type",String)],q.prototype,"id",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],q.prototype,"token",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],q.prototype,"balance",void 0),n.__decorate([a.column(),n.__metadata("design:type",String)],q.prototype,"captive",void 0),q=n.__decorate([a.table("erc20_wallets"),t.model(),n.__metadata("design:paramtypes",[Object])],q);let V=class extends a.BaseModel{constructor(e){super(e)}};n.__decorate([a.pk({type:String}),a.column(),t.required(),n.__metadata("design:type",String)],V.prototype,"owner",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],V.prototype,"spender",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",Number)],V.prototype,"value",void 0),V=n.__decorate([a.table("erc20_allowances"),t.model(),n.__metadata("design:paramtypes",[Object])],V);class Y extends t.JSONSerializer{constructor(){super()}preSerialize(e,i){const a=Object.assign({},e);let n=o.Metadata.modelName(e.constructor);if(!n||"Object"===n){if(!i)throw new r.SerializationError("Could not find metadata for "+e.constructor.name);n=i}return a[t.ModelKeys.ANCHOR]=n,a}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e,t){return JSON.stringify(this.preSerialize(e,t))}}class J extends H{static{this.serializer=new Y}static{this.decoder=new TextDecoder("utf8")}async updateObservers(e,i,n,...o){if(!this.observerHandler)throw new r.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:c}=this.logCtx(o,this.updateObservers);let l;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),e="string"==typeof e?t.Model.get(e):e,l=void 0===n?void 0:Array.isArray(n)?n.map(r=>a.Sequence.parseValue(t.Model.sequenceFor(e).type,r)):a.Sequence.parseValue(t.Model.sequenceFor(e).type,n),await this.observerHandler.updateObservers(e,i,l,...c)}decode(e){return J.decoder.decode(e)}constructor(e){super(e,q),this.serializer=J.serializer}async tokenName(...e){const{ctx:t}=(await this.logCtx(e,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(t,"TokenName");return this.decode(r)}async symbol(...e){const{ctx:t}=(await this.logCtx(e,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(t,"Symbol");return this.decode(r)}async decimals(...e){const{ctx:t}=(await this.logCtx(e,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(t,"Decimals");return Number(this.decode(r))}async totalSupply(...e){const{ctx:t}=(await this.logCtx(e,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(t,"TotalSupply");return Number(this.decode(r))}async balanceOf(e,...t){const{ctx:r}=(await this.logCtx(t,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[e]);return Number(this.decode(i))}async transfer(e,t,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),a=await this.adapter.submitTransaction(i,"Transfer",[e,t.toString()]);return"true"===this.decode(a)}async transferFrom(e,t,r){const i=await a.Context.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:n}=this.logCtx(i.args,this.transferFrom),o=await this.adapter.submitTransaction(n,"TransferFrom",[e,t,r.toString()]);return"true"===this.decode(o)}async approve(e,t){const r=await a.Context.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),n=await this.adapter.submitTransaction(i,"Approve",[e,t.toString()]);return"true"===this.decode(n)}async allowance(e,t){const r=await a.Context.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),n=await this.adapter.submitTransaction(i,"Allowance",[e,t]);return Number(this.decode(n))}async initialize(e){const t=await a.Context.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[J.serializer.serialize(e)]);return"true"===this.decode(i)}async checkInitialized(){const e=await a.Context.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.checkInitialized);await this.adapter.evaluateTransaction(t,"CheckInitialized")}async mint(e){const t=await a.Context.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[e.toString()])}async burn(e){const t=await a.Context.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(t.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[e.toString()])}async burnFrom(e,t){const r=await a.Context.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[e,t.toString()])}async clientAccountBalance(){const e=await a.Context.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(t,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const e=await a.Context.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:t}=this.logCtx(e.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(t,"ClientAccountID");return this.decode(r)}}function W(e,i,a){let n,o,s;function c(i,a){if(n=n||t.Model.pk(e),s=s||t.Model.sequenceFor(e),o=o||t.Model.composed(e,n),o)return r.composeAttributeValue(i,o);const c=i[n]||a;if(void 0===c)throw new r.InternalError("could not rebuild id for "+i.constructor.name);return c}if(Array.isArray(i)){if(!Array.isArray(a)||a.length!==i.length)throw new r.InternalError("inconsistent parameters. both must be arrays of equal length");return i.map((e,t)=>c(e,a[t]))}return c(i,a)}var Q;e.IdentityCredentials=class extends a.BaseModel{constructor(e){super(e)}},n.__decorate([o.description("Unique identifier of the credentials record"),a.column(),a.pk(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"id",void 0),n.__decorate([o.description("PEM-encoded X.509 certificate for the identity"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"certificate",void 0),n.__decorate([o.description("PEM-encoded root or intermediate certificate"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"rootCertificate",void 0),n.__decorate([o.description("PEM-encoded private key"),a.column(),t.required(),n.__metadata("design:type",String)],e.IdentityCredentials.prototype,"privateKey",void 0),e.IdentityCredentials=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.IdentityCredentials),e.FabricModelKeys=void 0,(Q=e.FabricModelKeys||(e.FabricModelKeys={})).PRIVATE="private",Q.SHARED="shared",Q.FABRIC="fabric",Q.OWNED_BY="owned-by",Q.TRANSACTION_ID="transaction-id",Q.MIRROR="mirror",Q.CONTRACT="fabric.contract",Q.CHAINCODE="fabric.chaincode",Q.CHANNEL="fabric.channel",Q.OVERRIDES="__overrides",e.IdentityType=void 0,(e.IdentityType||(e.IdentityType={})).X509="X.509";const X="hlf-fabric";e.Identity=class extends a.BaseModel{constructor(t){super(t),this.type=e.IdentityType.X509}},n.__decorate([o.description("Unique identifier of the identity"),a.pk(),n.__metadata("design:type",String)],e.Identity.prototype,"id",void 0),n.__decorate([a.oneToOne(e.IdentityCredentials,{update:a.Cascade.CASCADE,delete:a.Cascade.CASCADE}),n.__metadata("design:type",e.IdentityCredentials)],e.Identity.prototype,"credentials",void 0),n.__decorate([a.column(),t.required(),a.index(),n.__metadata("design:type",String)],e.Identity.prototype,"mspId",void 0),n.__decorate([a.column(),t.required(),n.__metadata("design:type",String)],e.Identity.prototype,"type",void 0),e.Identity=n.__decorate([t.model(),n.__metadata("design:paramtypes",[Object])],e.Identity);class Z{static{this.logger=new c.MiniLogger(Z.name)}constructor(){}static async contentOfLoadFile(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}static async readFile(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}static async getCAUser(e,r,i,a,n){this.logger.debug(t.stringFormat("Creating CA {0} user {1} with certificate {2}",a,e,i));const o=new d.User(e),s=n?.hsm?{software:!1,lib:n.hsm.library,slot:n.hsm.slot,label:n.hsm.tokenLabel,pin:n.hsm.pin+""}:void 0,c=this.getCryptoSuite(s);o.setCryptoSuite(c);const l=n?.hsm?await this.getHSMEnrollmentKey(c,i,n.hsm):this.getSoftwareEnrollmentKey(c,r);return await o.setEnrollment(l,i,a),o}static getCryptoSuite(e){return e?(Z.cryptoSuite||(Z.cryptoSuite=d.User.newCryptoSuite(e)),Z.cryptoSuite):d.User.newCryptoSuite()}static getSoftwareEnrollmentKey(e,t){if(!t)throw Error("Private key must be provided when HSM configuration is not supplied");return e.createKeyFromRaw(t)}static async getHSMEnrollmentKey(e,t,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(t),a=await e.getKey(i);if(!a||"function"==typeof a.isPrivate&&!a.isPrivate())throw Error("Unable to resolve private key from HSM");return a}static async getCertificateSKI(e){const t=new u.X509Certificate(e).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(t.x||"","base64url"),a=Buffer.from(t.y||"","base64url");return u.createHash("sha256").update(Buffer.concat([r,i,a])).digest()}static async getIdentity(e,t){return{mspId:e,credentials:await this.contentOfLoadFile(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)})}}static async getFirstDirFileName(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}static async getFirstDirFileNameContent(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}static async getFileContent(e){const{promises:t}=await a.normalizeImport(import("fs"));return(await t.readFile(e)).toString()}static async getSigner(e){const t=await this.contentOfLoadFile(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await this.getFirstDirFileName(e);return await t.readFile(r)}),r=await this.extractPrivateKey(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}static async extractPrivateKey(e){let t;if(globalThis.window&&globalThis.window.Crypto)t=globalThis.Crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const r=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(r,"base64").toString("binary"));return await t.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}function ee(e){const t=new h.X509Certificate(e),r=t.extensions?.find(e=>"2.5.29.35"===e.type);if(!r)throw Error("Authority Key Identifier (AKI) extension not found in certificate.");let i=Buffer.from(new Uint8Array(r.value)).toString("hex").toUpperCase();return i.startsWith("30168014")&&i.length>=48&&(i=i.slice(8,48)),{aki:i,serial:t.serialNumber}}const te=new g.Crypto;var re,ie,ae,ne,oe;w.cryptoProvider.set(te),e.BASE_ALPHABET=void 0,(re=e.BASE_ALPHABET||(e.BASE_ALPHABET={})).BASE2="01",re.BASE8="01234567",re.BASE11="0123456789a",re.BASE16="0123456789abcdef",re.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",re.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",re.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",re.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",re.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",re.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",re.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~",e.CRYPTO=void 0,(ie=e.CRYPTO||(e.CRYPTO={})).HASH="SHA-256",ie[ie.ITERATIONS=1e3]="ITERATIONS",ie[ie.KEYLENGTH=48]="KEYLENGTH",ie[ie.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",ie[ie.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",ie.ALGORYTHM="AES-GCM",ie.KEY_ALGORYTHM="PBKDF2";class se{constructor(e){if(this.alphabet=e,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let e=0;e<this.baseMap.length;e++)this.baseMap[e]=255;for(let t=0;t<e.length;t++){const r=e.charAt(t),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=t}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(e){if("string"==typeof e?e=Buffer.from(e):ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e)),0===e.length)return"";let t=0,r=0,i=0;const a=e.length;for(;i!==a&&0===e[i];)i++,t++;const n=(a-i)*this.iFactor+1>>>0,o=new Uint8Array(n);for(;i!==a;){let t=e[i],a=0;for(let e=n-1;(0!==t||r>a)&&-1!==e;e--,a++)t+=256*o[e]>>>0,o[e]=t%this.base>>>0,t=t/this.base>>>0;if(0!==t)throw Error("Non-zero carry");r=a,i++}let s=n-r;for(;s!==n&&0===o[s];)s++;let c=this.leader.repeat(t);for(;n>s;++s)c+=this.alphabet.charAt(o[s]);return c}decodeUnsafe(e){if(0===e.length)return new Uint8Array(0);let t=0,r=0,i=0;for(;e[t]===this.leader;)r++,t++;const a=(e.length-t)*this.factor+1>>>0,n=new Uint8Array(a);for(;e[t];){let r=this.baseMap[e.charCodeAt(t)];if(255===r)return;let o=0;for(let e=a-1;(0!==r||i>o)&&-1!==e;e--,o++)r+=this.base*n[e]>>>0,n[e]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=o,t++}let o=a-i;for(;o!==a&&0===n[o];)o++;const s=new Uint8Array(r+(a-o));let c=r;for(;o!==a;)s[c++]=n[o++];return s}decode(e){const t=this.decodeUnsafe(e);if(t)return t;throw Error("Non-base"+this.base+" character")}}class ce{static{this.b58encoder=new se(e.BASE_ALPHABET.BASE58)}static{this.logger=new c.MiniLogger(ce.name)}constructor(){}static fabricIdFromCertificate(e){this.logger.debug(t.stringFormat("Parsing certificate: {0}",e));const r=new w.X509Certificate(e),{subject:i,issuer:a}=r;return this.logger.debug(t.stringFormat("Certificate parsed with subject {0} and issuer {1}",i,a)),`x509::/${i.replaceAll(", ","/")}::/${a.replaceAll(", ","/")}`}static encode(e){return this.b58encoder.encode(e)}static decode(e){const t=this.b58encoder.decode(e);return(new TextDecoder).decode(t)}static stringToArrayBuffer(e){const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t}static async extractKey(e,t,r){const i=te.subtle,a=t.toString("utf8").replace(RegExp(`-----BEGIN (${e.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${e.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(a,"base64").toString("binary"),o=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",o,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(e,t){return this.extractKey("private",e,t)}static async extractPublicKey(e,t){return this.extractKey("public",e,t)}static async sign(e,t){const r=await this.extractPrivateKey(e),i=await te.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,t);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}static async verify(e,t,r){const i=new w.X509Certificate(e),a=await i.publicKey.export();return t="string"==typeof t?Buffer.from(t,"hex"):t,r="string"==typeof r?Buffer.from(r):r,te.subtle.verify({name:"ECDSA",hash:"SHA-256"},a,t,r)}static async encrypt(e,t){const r=new w.X509Certificate(e),i=await r.publicKey.export();t="string"==typeof t?Buffer.from(t):t;const a=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,t);return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return c.isBrowser()?globalThis.window.crypto.subtle:te.subtle}static async decrypt(e,t){const r=await this.extractPrivateKey(e);return t="string"==typeof t?Buffer.from(t,"hex"):t,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,t)}static async getMaster(t){const r=new TextEncoder;if(void 0===t){const e=te.randomUUID();t=r.encode(e).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,e.CRYPTO.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,r){const i=(new TextEncoder).encode(t),a=await this.getSubtleCrypto().digest("SHA-256",i),n={name:e.CRYPTO.KEY_ALGORYTHM,hash:e.CRYPTO.HASH,salt:a,iterations:e.CRYPTO.ITERATIONS},o=await this.getSubtleCrypto().deriveBits(n,r,8*e.CRYPTO.KEYLENGTH);return this.getKey(o)}static async getKey(t){const r=t.slice(0,32),i=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",r,{name:e.CRYPTO.ALGORYTHM},!1,["encrypt","decrypt"]),iv:i}}static async encryptPin(t,r){const i=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,i)}static async decryptPin(t,r){const i=new TextDecoder,a=await this.getSubtleCrypto().decrypt({name:e.CRYPTO.ALGORYTHM,iv:r.iv},r.key,t);return i.decode(a)}}e.HFCAIdentityType=void 0,(ae=e.HFCAIdentityType||(e.HFCAIdentityType={})).PEER="peer",ae.ORDERER="orderer",ae.CLIENT="client",ae.USER="user",ae.ADMIN="admin",e.HFCAIdentityAttributes=void 0,(ne=e.HFCAIdentityAttributes||(e.HFCAIdentityAttributes={})).HFREGISTRARROLES="hf.Registrar.Roles",ne.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",ne.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",ne.HFINTERMEDIATECA="hf.IntermediateCA",ne.HFREVOKER="hf.Revoker",ne.HFAFFILIATIONMGR="hf.AffiliationMgr",ne.HFGENCRL="hf.GenCRL";class le extends c.LoggedClass{constructor(e){Z.getCryptoSuite(e.hsm?{software:!1,lib:e.hsm.library,slot:e.hsm.slot,label:e.hsm.tokenLabel,pin:e.hsm.pin+""}:void 0),super(),this.caConfig=e}async User(){if(this.user)return this.user;const{caName:e,caCert:t,caKey:i,url:a,hsm:n}=this.caConfig,o=this.log.for(this.User);o.debug(`Creating CA user for ${e} at ${a}`),o.debug("Retrieving CA certificate from "+t);const s=await Z.getFirstDirFileNameContent(t);let c;if(n)o.debug(`Using HSM configuration for CA ${e} with library ${n.library}`);else{if(!i)throw new r.InternalError(`Missing caKey configuration for CA ${e}. Provide a key directory or configure HSM support.`);o.debug("Retrieving CA key from "+i),c=await Z.getFirstDirFileNameContent(i)}return o.debug("Loading Admin user for ca "+e),this.user=await Z.getCAUser("admin",c,s,e,{hsm:n}),this.user}async CA(){if(this.ca)return this.ca;const e=this.log.for(this.CA),{url:t,tls:r,caName:i}=this.caConfig;let{trustedRoots:a,verify:n}=r;const o=a[0];e.debug(`Retrieving CA certificate from ${o}. cwd: ${process.cwd()}`);const c=await Z.getFileContent(o);return e.debug(`Creating CA Client for CA ${i} under ${t}`),this.ca=new s(t,{trustedRoots:Buffer.from(c),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const e=await this.CA();return this.client=e._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(e,t=!0){const r=await this.Certificate(),i=await this.User(),a=this.log.for(this.getCertificates);a.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(e||{},i)).result;return a.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),t?n.certs.map(e=>e.PEM):n}async getIdentities(){const e=await this.Identities(),t=this.log.for(this.getIdentities);t.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(e){const t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new T(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new T(n)}}async getAffiliations(){const e=await this.Affiliations(),t=this.log.for(this.getAffiliations);t.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await e.getAll(await this.User())).result;return t.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(e){const t=await this.CA(),i=await this.User();let a;try{a=await t.newIdentityService().getOne(e,i)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n){let o;const s=this.log.for(this.register);try{const{userName:c,password:l}=e,d=await this.CA(),u=await this.User(),h={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};o=await d.register(h,u),s.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return o}static identityFromEnrollment(t,r){const{certificate:i,key:a,rootCertificate:n}=t,o=c.Logging.for(le,{}).for(this.identityFromEnrollment);o.debug(`Generating Identity from certificate ${i} in msp ${r}`);const s=ce.fabricIdFromCertificate(i),l=ce.encode(s);o.debug(`Identity ${s} and encodedId ${l}`);const d=new Date;return new e.Identity({id:l,credentials:{id:l,certificate:i,privateKey:a.toBytes(),rootCertificate:n,createdOn:d,updatedOn:d},mspId:r,createdOn:d,updatedOn:d})}async enroll(e,t){let r;const i=this.log.for(this.enroll);try{const a=await this.CA();i.debug("Enrolling "+e);const n=await a.enroll({enrollmentID:e,enrollmentSecret:t});r=le.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${e} under ${this.caConfig.caName} as ${r.id}`)}catch(e){throw this.parseError(e)}return r}async registerAndEnroll(e,t=!1,r="",i,a,n){const o=await this.register(e,t,r,i,a,n),{userName:s}=e;return this.enroll(s,o)}async revoke(e){const t=await this.CA(),i=await this.User(),a=await this.read(e);if(!a)throw new r.NotFoundError("Could not find enrollment with id "+e);let n;try{n=await t.revoke({enrollmentID:a.id,reason:"User Deletation"},i)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!n.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${n.errors.join("\n")}`);return n}}class de extends t.Model{constructor(){super(...arguments),this.affiliation=""}build(){const e=this.hasErrors();if(e)throw new r.ValidationError(e.toString());const t={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(t.maxEnrollments=this.maxEnrollments),this.attrs&&(t.attrs=this.attrs),t}setAffiliation(e){return this.affiliation=e,this}addAttr(e){return this.attrs=this.attrs||[],this.attrs.push(e),this}setAttrs(e){return this.attrs=e,this}setEnrollmentID(e){return this.enrollmentID=e,this}setEnrollmentSecret(e){return this.enrollmentSecret=e,this}setMaxEnrollments(e){return this.maxEnrollments=e,this}setRole(e){return this.role=e,this}}n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"affiliation",void 0),n.__decorate([t.minlength(1),n.__metadata("design:type",Array)],de.prototype,"attrs",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"enrollmentID",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"enrollmentSecret",void 0),n.__decorate([t.min(0),n.__metadata("design:type",Number)],de.prototype,"maxEnrollments",void 0),n.__decorate([t.required(),n.__metadata("design:type",String)],de.prototype,"role",void 0),t.Model.prototype.isShared=function(){return t.Model.isShared(this.constructor)},t.Model.prototype.isPrivate=function(){return t.Model.isPrivate(this.constructor)},t.Model.prototype.segregate=function(){return t.Model.segregate(this)},t.Model.segregate=(i=>{if(!t.Model.isTransient(i))return{model:i};const a=o.Metadata.getAttributes(i.constructor)||[],n=o.Metadata.get(i.constructor,r.DBKeys.TRANSIENT),s=o.Metadata.get(i.constructor,e.FabricModelKeys.PRIVATE),c=o.Metadata.get(i.constructor,e.FabricModelKeys.SHARED),l={model:{},public:{},transient:{},privates:{},shared:{}},d=Object.keys(n||{}),u=Object.keys(s||{}),h=Object.keys(c||{});for(const e of a){const t=i[e],r=d.includes(e),a=!r,n=u.includes(e),o=h.includes(e);(r||n||o)&&(l.transient=l.transient||{},l.transient[e]=t),n&&(l.privates=l.privates||{},l.privates[e]=t),o&&(l.shared=l.shared||{},l.shared[e]=t),a&&(l.public=l.public||{},l.public[e]=t)}return l.model=t.Model.build(l.public,i.constructor.name),l}).bind(t.Model),t.Model.isPrivate=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.PRIVATE)).bind(t.Model),t.Model.isShared=(t=>!!o.Metadata.get("function"!=typeof t?t.constructor:t,e.FabricModelKeys.SHARED)).bind(t.Model),t.Model.mirrored=(t=>o.Metadata.get("function"!=typeof t?t.constructor:t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR))).bind(t.Model),t.Model.ownerOf=(t=>{const r=o.Metadata.get(t.constructor,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY));if(r)return t[r]}).bind(t.Model),t.Model.mirroredAt=(t=>(t="function"!=typeof t?t.constructor:t,o.Metadata.get(t,o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR)))).bind(t.Model),t.Model.collectionsFor=(t=>{const r=[e.FabricModelKeys.PRIVATE],i=[e.FabricModelKeys.SHARED],a=o.Metadata.key(...r),n=o.Metadata.key(...i),s="function"==typeof t?t:t.constructor,c=o.Metadata.get(s,a),l=o.Metadata.get(s,n);return{privateCols:c?.collections||[],sharedCols:l?.collections||[]}}).bind(t.Model),t.Model.chaincodeOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CHAINCODE);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),t.Model.contractOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CONTRACT);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),t.Model.channelOf=((t,...i)=>{const n=o.Metadata.get(t,e.FabricModelKeys.CHANNEL);if(!n||!n.resolver)return;if("string"==typeof n.resolver)return n.resolver;const s=i.pop();if(!(s&&s instanceof a.Context))throw new r.InternalError("No context provided for chaincode resolution");return n.resolver(t,...i,s)}).bind(t.Model),e.ERC20Events=void 0,(oe=e.ERC20Events||(e.ERC20Events={})).TRANSFER="Transfer",oe.APPROVAL="Approval",e.FabricBaseModel=class extends t.Model{constructor(e){super(e)}},n.__decorate([o.description("Stores the original timestamp of creation"),a.column(),a.createdAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"createdAt",void 0),n.__decorate([o.description("Stores the timestamp of the last update"),a.column(),a.updatedAt(),n.__metadata("design:type",Date)],e.FabricBaseModel.prototype,"updatedAt",void 0),n.__decorate([o.description("Stores the version of the model"),a.column(),r.version(),n.__metadata("design:type",Number)],e.FabricBaseModel.prototype,"version",void 0),e.FabricBaseModel=n.__decorate([o.uses(X),n.__metadata("design:paramtypes",[Object])],e.FabricBaseModel),e.FabricIdentifiedBaseModel=class extends e.FabricBaseModel{constructor(e){super(e)}},n.__decorate([o.description("Stores the creator"),a.column(),a.createdBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"createdBy",void 0),n.__decorate([o.description("Stores the user that last updated the model"),a.column(),a.updatedBy(),n.__metadata("design:type",String)],e.FabricIdentifiedBaseModel.prototype,"updatedBy",void 0),e.FabricIdentifiedBaseModel=n.__decorate([o.uses(X),n.__metadata("design:paramtypes",[Object])],e.FabricIdentifiedBaseModel);const ue=(e,...t)=>e.name+"Contract";function he(e){if(e)return"string"==typeof e?e:e.getMSPID()}async function ge(e,t,r,i){const{stub:a}=e,n=e.getOrUndefined("allowGenerationOverride")||!1;let o=(await a.getCreator()).mspid;e.logger.info(`Expected mspid to be ${i[r]} | ${o}. \n Using allowGenerationOverride: ${n}`),n&&(o=i[r]?i[r]:o),Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:o})}async function pe(e,t,r,i){const{stub:a}=e;i[r]=a.getTxID()}async function fe(e,i,a){let n=i;if("string"!=typeof n)try{const r=t.Model.ownerOf(e)||a.get("stub").getCreator().toString();i&&"function"==typeof i&&(n=await i(e,r,a))}catch(e){throw new r.InternalError("Failed to resolve collection mirror name: "+e)}if(!n||"string"!=typeof n)throw new r.InternalError("No collection found model "+e.constructor.name);return n}async function ye(e,r,i,a){const n=await fe(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0})),i=await r.create(s,e);e.logger.info(`Mirror for ${t.Model.tableName(this.class)} created with ${t.Model.pk(a)}: ${i[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function me(e,r,i,a){const n=await fe(a,r.resolver,e),o=e,s=a;o.put("mirror",!0),o.put("mirrorCollection",n);try{const r=this.override(Object.assign({},this._overrides,{mirror:!0,mirrorCollection:n,ignoreValidation:!0,ignoreHandlers:!0,applyUpdateValidation:!1,mergeForUpdate:!1}));await r.update(s,e),e.logger.info(`Mirror for ${t.Model.tableName(this.class)} updated: ${a[t.Model.pk(a)]}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0)}}async function we(e,r,i,a){const n=await fe(a,r.resolver,e),o=e;o.put("mirror",!0),o.put("mirrorCollection",n),o.put("segregated",n);try{const r=a[t.Model.pk(a)],i=this.override(Object.assign({},this._overrides,{segregated:n,mirror:!0,ignoreValidation:!0,ignoreHandlers:!0}));try{await i.delete(r,e)}catch{}e.logger.info(`Mirror for ${t.Model.tableName(this.class)} deleted: ${r+""}`)}finally{o.put("mirror",void 0),o.put("mirrorCollection",void 0),o.put("segregated",void 0)}}async function be(e,t,r,i){const n=he(e.get("identity"));if(n&&(n===t.mspId||t.condition&&t.condition(n)))throw new a.AuthorizationError(`Organization ${n} is not authorized to modify mirrored data`)}async function Ee(e,t,r,i){const a=he(e.get("identity"));if(!a)return;const n=await fe(i,t.resolver,e),o=e;(a===t.mspId||t.condition&&t.condition(a))&&(e.logger.info(`Mirror read: MSP ${a} matches, routing reads to mirror collection ${n}`),o.put("mirror",!0),o.put("mirrorCollection",n),o.put("fullySegregated",!0),o.readFrom(n))}const Ce=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0);if(!a)throw new r.InternalError(`Model ${e.constructor.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`__${c.toPascalCase(a)}PrivateCollection`};function Ae(i,a,n){a.length>0&&n.readFrom(a),!n.isFullySegregated&&a.length&&((i=>{const a=o.Metadata.getAttributes(i)||[],n=t.Model.pk(i),s=o.Metadata.get(i,r.DBKeys.TRANSIENT)||{},c=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.PRIVATE))||{},l=o.Metadata.get(i,o.Metadata.key(e.FabricModelKeys.SHARED))||{};return a.some(e=>e!==n&&!(e in s)&&!(e in c)&&!(e in l))})(i.constructor)||n.markFullySegregated())}async function ve(e,r,i,a){const n=Array.isArray(r)?r:[r],o=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(a)||he(e.get("identity"));if(!o)return;const s=[];for(const t of n){const r=t.collections,i="string"==typeof r?r:r(a,o,e);i&&!s.includes(i)&&s.push(i)}Ae(a,s,e);const c=Array.isArray(i)?i:[i],l=t.Model.pk(a.constructor),d=t.Model.sequenceName(a,"pk"),u=a[l],h=null!=u;if(e.setSequenceSegregation(d,e.isFullySegregated,s),h)for(const r of c){const i=t.Model.sequenceName(a,u+"",r+"");e.setSequenceSegregation(i,e.isFullySegregated,s)}}async function Oe(e,i,n,o){const s=Array.isArray(i)?i:[i],c=Array.isArray(n)?n:[n];if(c.length!==s.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const l=t.Model.ownerOf(o)||he(e.get("identity"));if(!l)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const d=s[0].collections,u="string"==typeof d?d:d(o,l,e);c.forEach((t,r)=>{const i="string"==typeof s[r].collections?s[r].collections:s[r].collections(o,l,e);if(i!==u)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${u}`)});const h=c.map(e=>e+"");e.writeTo(u,h)}async function Se(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(n)||he(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:await c(n,s,e);e.readFrom(l)}async function Me(e,i,n,o,s){const c=Array.isArray(i)?i:[i],l=Array.isArray(n)?n:[n];if(l.length!==c.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const d=t.Model.ownerOf(o)||he(e.get("identity"));if(!d)throw new r.ValidationError("There's no assigned organization for model "+o.constructor.name);const u=c[0].collections,h="string"==typeof u?u:u(o,d,e);l.forEach((t,r)=>{const i="string"==typeof c[r].collections?c[r].collections:c[r].collections(o,d,e);if(i!==h)throw new a.UnsupportedError(`Segregated data collection mismatch: ${i} vs ${h}`)});const g=l.map(e=>e+"");e.writeTo(h,g)}async function Ie(e,i,a,n){const o=Array.isArray(i)?i:[i];if((Array.isArray(a)?a:[a]).length!==o.length)throw new r.InternalError("Segregated data keys and metadata length mismatch");const s=(e.getOrUndefined("allowGenerationOverride")?e.getOrUndefined("ownerOverride"):void 0)||t.Model.ownerOf(n)||he(e.get("identity"));if(!s)throw new r.ValidationError("There's no assigned organization for model "+n.constructor.name);const c=o[0].collections,l="string"==typeof c?c:c(n,s,e);e.readFrom(l)}function _e(e,t,i){return(i,a)=>{const n=[];if(!a){const r=o.Metadata.getAttributes(i);return r?.forEach(r=>{_e(e,t)(i.prototype,r)}),i}{const i="string"==typeof e?e:e.toString(),a=i+":data",s={collections:e},c={priority:35,group:i+":extract"};n.push(o.prop(),r.transient(),(i,a)=>{const n=o.Metadata.key(t,a),s=i.constructor,c=o.Metadata.get(s,n)||{},l=new Set(c.collections||[]);l.add(e),c.collections=[...l],o.Metadata.set(s,n,c);const d=o.Metadata.get(s,t)||{},u=new Set(d.collections||[]);u.add(e),d.collections=[...u],o.Metadata.set(s,t,d);const h={...o.Metadata.get(s,r.DBKeys.TRANSIENT)||{},[a]:{}};o.Metadata.set(s,r.DBKeys.TRANSIENT,h)},r.on(r.DBOperations.ALL,ve,s,c),r.onCreate(Oe,{collections:e},{priority:95,group:a}),r.onRead(Se,{collections:e},{priority:95,group:a}),r.onUpdate(Me,{collections:e},{priority:95,group:a}),r.onDelete(Ie,{collections:e},{priority:95,group:a}))}return o.apply(...n)(i,a)}}function xe(e){return null===e||"object"!=typeof e?e:Array.isArray(e)?e.map(xe):e.constructor!==Object?e:Object.keys(e).sort().reduce((t,r)=>(t[r]=xe(e[r]),t),{})}class Te extends t.JSONSerializer{constructor(){super()}preSerialize(e){const r=Object.assign({},e);let i;try{i=o.Metadata.modelName(e.constructor)}catch(e){i=void 0}r[t.ModelKeys.ANCHOR]=i||e.constructor.name;const a=function e(t){const r=this;return"object"!=typeof t?t:Array.isArray(t)?t.map(t=>e.call(r,t)):this.preSerialize.call(this,t)}.bind(this);return t.Model.relations(e).forEach(e=>{r[e]=a(r[e])}),r}deserialize(e){const r=JSON.parse(e),i=r[t.ModelKeys.ANCHOR];if(!i)throw Error("Could not find class reference in serialized model");return t.Model.build(r,i)}serialize(e){return require("json-stringify-deterministic")(xe(this.preSerialize(e)))}}function Ne(e){const t=e.split("_");return 2>t.length||t.length>3?{table:void 0,event:e,owner:void 0}:{table:t[0],event:t[1],owner:t[2]}}class Fe extends t.JSONSerializer{constructor(){super()}deserialize(e,t){return JSON.parse(e)}serialize(e,t=!0){return require("json-stringify-deterministic")(xe(this.preSerialize(e,t)))}preSerialize(e,r=!0){const i=Object.assign({},e);let a;try{a=o.Metadata.modelName(e.constructor)}catch(e){a=void 0}function n(e){return"object"!=typeof e?e:Array.isArray(e)?e.map(n):this.preSerialize(e)}return r&&(i[t.ModelKeys.ANCHOR]=a||e.constructor.name),t.Model.relations(e).forEach(e=>{i[e]=n.call(this,i[e])}),i}}class Re extends a.ClientBasedService{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new r.InternalError("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(e,t){const i=t.logger.for(this.getUser),{caName:a,caCert:n,caKey:o,url:s,hsm:c}=e;i.info(`Creating CA user for ${a} at ${s}`),i.verbose("Retrieving CA certificate from "+n);const l=await Z.getFirstDirFileNameContent(n);let d;if(c)i.debug(`Using HSM configuration for CA ${a} with library ${c.library}`);else{if(!o)throw new r.InternalError(`Missing caKey configuration for CA ${a}. Provide a key directory or configure HSM support.`);i.debug("Retrieving CA key from "+o),d=await Z.getFirstDirFileNameContent(o)}return i.debug("Loading Admin user for ca "+a),this._user=await Z.getCAUser("admin",d,l,a,{hsm:c}),this._user}async initialize(...e){const{log:t,ctx:i}=(await this.logCtx(e,a.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),[n]=e;if(!n)throw new r.InternalError("Missing Fabric CA configuration");const{url:o,tls:c,caName:l}=n;t.info(`Initializing CA Client for CA ${n.caName} at ${n.url}`);const{trustedRoots:d,verify:u}=c,h=d[0];t.debug(`Retrieving CA certificate from ${h}. cwd: ${process.cwd()}`);const g=await Z.getFileContent(h);t.debug("CA Certificate: "+g.toString());const p=new s(o,{trustedRoots:Buffer.from(g),verify:u},l),f=await this.getUser(n,i);return t.debug("CA user loaded: "+f.getName()),{config:n,client:p}}async getCertificates(e,t=!0,...i){e instanceof a.Context?(i=[e],t=!0,e=void 0):"boolean"==typeof e?(t=e,e=void 0):"boolean"!=typeof t&&(i=[t,...i],t=!0);const{log:n}=(await this.logCtx(i,r.OperationKeys.READ,!0)).for(this.getCertificates);n.debug(`Retrieving certificates${e?" for "+e.id:""} for CA ${this.config.caName}`);const o=(await this.certificates.getCertificates(e||{},this.user)).result;return n.verbose(`Found ${o.certs.length} certificates`),n.debug(o.certs),t?o.certs.map(e=>e.PEM):o}async getIdentities(e){const t=e.logger.for(this.getIdentities);t.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return t.verbose(`Found ${r.identities.length} Identities`),t.debug(r.identities),r.identities}async getAffiliations(e){const t=e.logger.for(this.getAffiliations);t.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return t.verbose(`Found ${r.a.length} Affiliations`),t.debug(JSON.stringify(r)),r}parseError(e){const t=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(e.message);if(!t)return new T(e);const[,i,n]=t;switch(i){case"74":case"71":return new r.ConflictError(n);case"20":return new a.AuthorizationError(n);default:return new T(n)}}async read(e,...t){const{log:i}=(await this.logCtx(t,r.OperationKeys.READ,!0)).for(this.read);let a;i.verbose("Retrieving identity with enrollment ID "+e);try{a=await this.identities.getOne(e,this.user)}catch(t){throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${t}`)}if(!a.success)throw new r.NotFoundError(`Couldn't find enrollment with id ${e}: ${a.errors.join("\n")}`);return a.result}async register(e,t=!1,r="",i,a,n,...o){const{log:s}=(await this.logCtx(o,"register",!0)).for(this.register);let c;try{const{userName:o,password:l}=e,d={enrollmentID:o,enrollmentSecret:l,affiliation:r,userRole:i,attrs:a,maxEnrollments:n};c=await this.client.register(d,this.user),s.info(`Registration for ${o} created with user type ${i??"Undefined Role"} ${t?"as super user":""}`)}catch(e){throw this.parseError(e)}return c}static identityFromEnrollment(t,r,i){const a=i.logger.for(this.identityFromEnrollment),{certificate:n,key:o,rootCertificate:s}=t;a.verbose(`Generating Identity from certificate ${n} in msp ${r}`);const c=ce.fabricIdFromCertificate(n),l=ce.encode(c);return a.debug(`Identity ${c} and encodedId ${l}`),new e.Identity({id:l,credentials:{id:l,certificate:n,privateKey:o.toBytes(),rootCertificate:s},mspId:r})}async enroll(e,t,...r){const{log:i,ctx:a}=(await this.logCtx(r,"enroll",!0)).for(this.enroll);let n;try{i.debug("Enrolling "+e);const r=await this.client.enroll({enrollmentID:e,enrollmentSecret:t});n=Re.identityFromEnrollment(r,this.config.caName,a),i.info(`Successfully enrolled ${e} under ${this.config.caName} as ${n.id}`)}catch(e){throw this.parseError(e)}return n}async registerAndEnroll(e,t=!1,r="",i,a,n,...o){const{ctx:s}=(await this.logCtx(o,"register-enroll",!0)).for(this.registerAndEnroll),c=await this.register(e,t,r,i,a,n,s),{userName:l}=e;return this.enroll(l,c,s)}async updateIdentity(e,t,r,...i){const{log:a,ctx:n}=(await this.logCtx(i,"reenroll",!0)).for(this.updateIdentity);try{a.info("Renewing identity for "+e);const o=this.client.newIdentityService(),s=await o.getOne(e,this.user);await o.update(e,r,this.user);const c=d.User.createUser(e,"",this.user.getMspid(),t.certificate,t.privateKey);c.setCryptoSuite(this.user.getCryptoSuite());const l=(s.result.attrs||[]).map(({name:e})=>({name:e,optional:!1})),u=await this.client.reenroll(c,l),h=Re.identityFromEnrollment(u,this.config.caName,n);a.debug("Revoking previous certificates for "+e);const{aki:g,serial:p}=ee(t.certificate);return await this.revoke(e,{aki:g,serial:p},i),a.debug("Renew identity successful for "+e),h}catch(e){throw this.parseError(e)}}async revoke(e,t,...i){const{log:a}=(await this.logCtx(i,"revoke",!0)).for(this.revoke);a.verbose("Revoking identity with enrollment ID "+e);const n=await this.read(e);if(!n)throw new r.NotFoundError("Could not find enrollment with id "+e);let o;try{const e={reason:t.serial||t.aki?"Revoke User Certificate":"User Deletion",...t,enrollmentID:n.id};o=await this.client.revoke(e,this.user)}catch(t){throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${t}`)}if(!o.success)throw new r.InternalError(`Could not revoke enrollment with id ${e}: ${o.errors.join("\n")}`);return o}}var De;e.CA_ROLE=void 0,(De=e.CA_ROLE||(e.CA_ROLE={})).ADMIN="admin",De.USER="user",De.CLIENT="client";const Pe=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60,legacy:!1,allowManualEndorsingOrgs:!1,allowGatewayOverride:!1,allowContextTransientMap:!1,rebuildWithTransient:!0,encryptTransient:!1,syntheticEvents:!0}),$e=new c.MiniLogger("fabric-fs");async function Be(e,t){return e instanceof Uint8Array||e.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?e:await t(e)}async function Ke(e){return"string"!=typeof e?e:await(async e=>{const{promises:t}=await a.normalizeImport(import("fs"));return await t.readFile(e)})(e)}async function ke(e,t){return{mspId:e,credentials:await Be(t,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Le(e);return await t.readFile(r)})}}async function Le(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path"));return r(e,(await t.readdir(e))[0])}async function je(e){const{promises:t}=await a.normalizeImport(import("fs")),{join:r}=await a.normalizeImport(import("path")),i=await t.readdir(e);return(await t.readFile(r(e,i[0]))).toString()}async function ze(e){const t=await Be(e,async e=>{const{promises:t}=await a.normalizeImport(import("fs")),r=await Le(e);return await t.readFile(r)}),r=await Ue(t),i=r[Object.getOwnPropertySymbols(r)[0]];return l.signers.newPrivateKeySigner(i)}async function Ue(e){let t;if(c.isBrowser())t=globalThis.crypto.subtle;else{const e=await a.normalizeImport(import("crypto"));t=e.subtle||e.webcrypto.subtle}if(!t)throw Error("Could not load SubtleCrypto module");const i=e.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),n=(e=>{const t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let t=0,i=e.length;i>t;t++)r[t]=e.charCodeAt(t);return t})(Buffer.from(i,"base64").toString("binary"));try{return await t.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(e){throw new r.InternalError(e)}}const He=["allowGenerationOverride"];class Ge extends a.Context{constructor(e){super(e)}toOverrides(){const e={};for(const t of He){const r=this.getOrUndefined(t);void 0!==r&&(e[t]=r)}return e}}function qe(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class Ve extends a.Statement{constructor(e,t){super(e,t)}squash(e){const t=super.squash(e);if(!t)return t;const{method:i,params:n,args:o}=t,{direction:s,limit:c}=n;switch(i){case a.PreparedStatementKeys.FIND:break;case a.PreparedStatementKeys.PAGE:o.push(s,c);break;case a.PreparedStatementKeys.FIND_BY:break;case a.PreparedStatementKeys.LIST_BY:o.push(s);break;case a.PreparedStatementKeys.PAGE_BY:o.push(s,c);break;case a.PreparedStatementKeys.FIND_ONE_BY:break;default:throw new r.InternalError("Unsupported method "+i)}return t}async executePrepared(...e){const t=a.Repository.forModel(this.fromSelector,this.adapter.alias),{method:r,args:i}=this.prepared;return t.statement(r,...i,...e)}async prepare(e){if(!(e=e||await this.adapter.context(a.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector)))throw new r.InternalError("No context available for statement");if(this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],i={},n={class:this.fromSelector,args:t,params:i},o=[a.QueryClause.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);o.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&o.push(a.QueryClause.SELECT,this.selectSelector.join(` ${a.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length&&(o.push(a.QueryClause.ORDER_BY,this.orderBySelectors[0][0]),t.push(this.orderBySelectors[0][1])),n.method=c.toCamelCase(o.join(" ")),n.params=i,this.prepared=n,this}processRecord(e,n){const s=t.Model.pk(this.fromSelector),c=o.Metadata.get(this.fromSelector,o.Metadata.key(r.DBKeys.ID,s))?.type;if(e[i.CouchDBKeys.ID]){const[,...t]=e[i.CouchDBKeys.ID].split(i.CouchDBKeys.SEPARATOR),r=t.join("_");e[s]=a.Sequence.parseValue(c,r)}return super.processRecord(e,n)}async raw(e,...t){const{ctx:r}=this.logCtx(t,this.raw),i=e?.aggregateInfo;if(e?.aggregate&&i)return this.executeAggregate(i,r);const a=await this.adapter.raw(e,!0,this.fromSelector,r);if(!this.selectSelector){const e=a.map(e=>this.processRecord(e,r));return r.getOrUndefined("afterQueryHandlers")?await this.applyAfterHandlersToResult(e,r):e}return a}build(){const e=this.log.for(this.build),r=this.buildAggregateQuery();if(r)return r;const n={};n[i.CouchDBKeys.TABLE]={},n[i.CouchDBKeys.TABLE]=t.Model.tableName(this.fromSelector);const o={selector:n};if(this.selectSelector&&(o.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(a.Condition.and(this.whereCondition,a.Condition.attribute(i.CouchDBKeys.TABLE).eq(o.selector[i.CouchDBKeys.TABLE]))).selector,r=Object.keys(t);if(1===r.length&&-1!==Object.values(i.CouchDBGroupOperator).indexOf(r[0]))switch(r[0]){case i.CouchDBGroupOperator.AND:t[i.CouchDBGroupOperator.AND]=[...Object.values(t[i.CouchDBGroupOperator.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const a=r[0];return a===i.CouchDBGroupOperator.AND?e.push(...t[a]):e.push(t),e},[])],o.selector=t;break;case i.CouchDBGroupOperator.OR:{const e={};e[i.CouchDBGroupOperator.AND]=[t,...Object.entries(o.selector).map(([e,t])=>{const r={};return r[e]=t,r})],o.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{o.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${o.selector[t]} by ${r}`),o.selector[t]=r})}if(this.orderBySelectors?.length){o.sort=o.sort||[],o.selector=o.selector||{};for(const[e,t]of this.orderBySelectors){const r=e,a={};a[r]=t,o.sort.push(a),o.selector[r]||(o.selector[r]={},o.selector[r][i.CouchDBOperator.BIGGER]=null)}}return this.limitSelector?o.limit=this.limitSelector:(e.warn("No limit selector defined. Using default couchdb limit of "+i.CouchDBQueryLimit),o.limit=i.CouchDBQueryLimit),this.offsetSelector&&(o.skip=this.offsetSelector),o}parseCondition(e){const{attr1:t,operator:r,comparison:n}=e;if(r===a.Operator.STARTS_WITH){if("string"!=typeof t)throw new a.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("STARTS_WITH requires a string comparison");const e={start:o=n,end:qe(o)},r={};return r[t]={},r[t][i.CouchDBOperator.BIGGER_EQ]=e.start,r[t][i.CouchDBOperator.SMALLER]=e.end,{selector:r}}var o,s;if(r===a.Operator.ENDS_WITH){if("string"!=typeof t)throw new a.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof n)throw new a.QueryError("ENDS_WITH requires a string comparison");const e={};return e[t]={[i.CouchDBOperator.REGEXP]:(s=n,s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")},{selector:e}}if(r===a.Operator.BETWEEN){const e=t;if(!Array.isArray(n)||2!==n.length)throw new a.QueryError("BETWEEN operator requires [min, max] comparison");const[r,o]=n,s={};return s[e]={},s[e][i.translateOperators(a.Operator.BIGGER_EQ)]=r,s[e][i.translateOperators(a.Operator.SMALLER_EQ)]=o,{selector:s}}let c={};if(-1===[a.GroupOperator.AND,a.GroupOperator.OR,a.Operator.NOT].indexOf(r))c[t]={},c[t][i.translateOperators(r)]=n;else if(r===a.Operator.NOT)c=this.parseCondition(t).selector,c[i.translateOperators(a.Operator.NOT)]={},c[i.translateOperators(a.Operator.NOT)][t.attr1]=n;else{const e=this.parseCondition(t).selector,a=this.parseCondition(n).selector;c=((e,t,r)=>{const i={selector:{}};return i.selector[e]=[t,r],i})(i.translateOperators(r),e,a).selector}return{selector:c}}buildAggregateQuery(){if(!this.fromSelector)return;if(this.avgSelector){const e=this.avgSelector+"",t=this.createAggregateDescriptor("sum",e),r=this.createAggregateDescriptor("count",e);if(!t||!r)throw new a.QueryError("Avg operation requires sum and count views for attribute "+e);return this.createAggregateQuery({kind:"avg",attribute:e,sumDescriptor:t.descriptor,countDescriptor:r.descriptor})}if(void 0!==this.countDistinctSelector){const e=null==this.countDistinctSelector?void 0:this.countDistinctSelector+"",t=this.createAggregateDescriptor("distinct",e);if(t)return t.countDistinct=!0,this.createAggregateQuery(t)}const e=!!(void 0!==this.countSelector||void 0!==this.countDistinctSelector||this.minSelector||this.maxSelector||this.sumSelector||this.distinctSelector),r=[["count",this.countSelector??void 0],["max",this.maxSelector],["min",this.minSelector],["sum",this.sumSelector],["distinct",this.distinctSelector]];for(const[e,t]of r){const r=t?t+"":void 0,i=this.createAggregateDescriptor(e,r);if(i)return this.createAggregateQuery(i)}if(e)throw new a.QueryError(`No CouchDB view metadata found for table ${t.Model.tableName(this.fromSelector)} aggregator`)}createAggregateDescriptor(e,r){if(!this.fromSelector)return;const a=i.findViewMetadata(this.fromSelector,e,r);if(!a.length)return;const n=a[0],o=t.Model.tableName(this.fromSelector),s=i.generateViewName(o,n.attribute,e,n),c=n.ddoc||i.generateDesignDocName(o,s),l={reduce:void 0!==n.reduce||!n.returnDocs};return"distinct"!==e&&"groupBy"!==e||(l.group=!0),{kind:e,meta:n,descriptor:{ddoc:c,view:s,options:l}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}getFabricAdapter(){return this.adapter}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getFabricAdapter(),i=e,a=await r.view(i.descriptor.ddoc,i.descriptor.view,i.descriptor.options,t);return this.processViewResponse(e,a)}async handleAverage(e,t){if("avg"!==e.kind)throw new a.QueryError("Average descriptor is not valid");const r=this.getFabricAdapter(),[i,n]=[e.sumDescriptor,e.countDescriptor],[o,s]=await Promise.all([r.view(i.ddoc,i.view,i.options,t),r.view(n.ddoc,n.view,n.options,t)]),c=o.rows?.[0]?.value??0,l=s.rows?.[0]?.value??0;return l?c/l:0}processViewResponse(e,t){if("avg"===e.kind)throw new a.QueryError("Average results should be handled before processing rows");const r=t.rows||[],i=e,n=i.meta;return i.countDistinct?r.length||0:"distinct"===i.kind||"groupBy"===i.kind?r.map(e=>e.key??e.value):n.returnDocs?r.map(e=>e.value??e.doc??e):r.length?r[0].value??r[0].key??null:"count"===i.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}}var Ye;class Je extends a.Adapter{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new Y}static{this.log=c.Logging.for(Je)}get Context(){return Ge}constructor(e,t){super(Object.assign({},Pe,e),X,t),this.serializer=Je.serializer}chaincodeFor(e,...t){return Je.chaincodeFor(e,this.config,...t)}channelFor(e,...t){return Je.channelFor(e,this.config,...t)}contractFor(e,...t){return Je.contractFor(e,this.config,...t)}Statement(e){return new Ve(this,e)}Paginator(e,t,r){return new M(this,e,t,r)}async flags(e,t,r,...i){const a=Object.assign({},this.config,r);return Object.assign(await super.flags(e,t,a,...i))}async context(e,r,i,...n){this.log.for(this.context).silly(`creating new context for ${e} operation on ${i?Array.isArray(i)?i.map(e=>t.Model.tableName(e)):t.Model.tableName(i):"no"} table ${r&&Object.keys(r)?Object.keys(r).length:"no"} with flag overrides`);let o=n.pop();void 0===o||o instanceof a.Context||(n.push(o),o=void 0),r=o?Object.assign({},o.toOverrides(),r):r;const s=await this.flags("string"==typeof e?e:e.name,i,r,...[...n,o].filter(Boolean));if(o){if(!(o instanceof this.Context)){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}const t=o.getOrUndefined("operation"),r=o.getOrUndefined("affectedTables");if(!t||t!==e||i&&i!==r){const e=(new this.Context).accumulate({...o.cache,...s,parentContext:o});return o.accumulate({childContexts:[...o.getOrUndefined("childContexts")||[],e]}),e}return o.accumulate(s)}return(new this.Context).accumulate({...s})}decode(e){return Je.decoder.decode(e)}repository(){return H}createPrefix(e,r,a,...n){const{ctxArgs:o}=this.logCtx(n,this.createPrefix),s=t.Model.tableName(e),c={};return c[i.CouchDBKeys.TABLE]=s,Object.assign(c,a),[e,r,c,...o]}createAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.createAllPrefix),l=a.map((e,t)=>{const r={};return r[i.CouchDBKeys.TABLE]=s,Object.assign(r,n[t]),r});return[e,a,l,...c]}updateAllPrefix(e,a,n,...o){const s=t.Model.tableName(e);if(a.length!==n.length)throw new r.InternalError("Ids and models must have the same length");const{ctxArgs:c}=this.logCtx(o,this.updateAllPrefix),l=a.map(()=>{const e={};return e[i.CouchDBKeys.TABLE]=s,e});return[e,a,l,...c]}async createAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.createAll),d=t.Model.tableName(e);c.info(`adding ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=a.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,r.BulkCrudOperationKeys.CREATE_ALL,[JSON.stringify(g)],u?{[d]:s}:void 0,this.getEndorsingOrganizations(l),e);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,f[0][t.Model.pk(e)]||i[0])?this.readAll(e,W(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s?.[r]||{}),f[r])),i),l):f}async readAll(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.readAll),s=t.Model.tableName(e);n.info(`reading ${i.length} entries to ${s} table`),n.verbose("pks: "+i);const c=await this.evaluateTransaction(o,r.BulkCrudOperationKeys.READ_ALL,[JSON.stringify(i)],void 0,void 0,e);try{return JSON.parse(this.decode(c)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}async updateAll(e,i,a,...n){if(i.length!==a.length)throw new r.InternalError("Ids and models must have the same length");const o=[...n],s=o.shift(),{log:c,ctx:l}=this.logCtx(o,this.updateAll),d=t.Model.tableName(e);c.info(`updating ${i.length} entries to ${d} table`),c.verbose("pks: "+i);const u=s&&Object.keys(s).length>0,h=u||this.shouldForceGatewayHydration(l),g=a.map(t=>this.serializer.serialize(t,e.name)),p=await this.submitTransaction(l,r.BulkCrudOperationKeys.UPDATE_ALL,[JSON.stringify(g)],u?{[d]:s}:void 0,this.getEndorsingOrganizations(l),e);let f;try{f=JSON.parse(this.decode(p)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}return this.shouldRefreshAfterWrite(e,l,h,i[0])?this.readAll(e,W(e,a.map((e,r)=>t.Model.merge(Object.assign({},e,s?.[r]||{}),f[r])),i),l):f}async deleteAll(e,i,...a){const{log:n,ctx:o,ctxArgs:s}=this.logCtx(a,this.deleteAll),c=t.Model.tableName(e),l=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let d;const u=this.shouldRefreshAfterWrite(e,o,l,i[0]);u&&(d=await this.readAll(e,i,...s)),n.info(`deleting ${i.length} entries to ${c} table`),n.verbose("pks: "+i);const h=await this.submitTransaction(o,r.BulkCrudOperationKeys.DELETE_ALL,[JSON.stringify(i)],void 0,this.getEndorsingOrganizations(o),e);try{return u?d:JSON.parse(this.decode(h)).map(e=>JSON.parse(e))}catch(e){throw new r.SerializationError(e)}}prepare(e,...i){const{log:n,ctx:o}=this.logCtx(i,this.prepare),s=t.Model.segregate(e);e[a.PersistenceKeys.METADATA]&&(n.silly("Passing along persistence metadata for "+e[a.PersistenceKeys.METADATA]),Object.defineProperty(s.model,a.PersistenceKeys.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:e[a.PersistenceKeys.METADATA]}));const c=t.Model.mirroredAt(e);if(c){const e=c.mspId;if(!e)throw new r.InternalError("No mirror MSP could be found");let t=this.getEndorsingOrganizations(o)||[];t=Array.isArray(t)?t:[t];const i=[...new Set([...t,e])];o.accumulate({endorsingOrgs:i,endorsingOrganizations:i,legacy:!0})}return{record:s.model,model:s.model,id:e[t.Model.pk(e.constructor)],transient:s.transient,privates:s.privates,shared:s.shared}}revert(e,t,r,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.revert);return i&&this.shouldRebuildWithTransient(o,o.getOrUndefined("operation"))&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).filter(([,e])=>void 0!==e).forEach(([t,r])=>{t in e&&void 0!==e[t]&&n.warn(`overwriting existing ${t}. if this is not a default value, this may pose a problem`),e[t]=r})),new t(e)}shouldRebuildWithTransient(e,t){if(!e)return!1;if(e.getOrUndefined("rebuildWithTransient"))return!0;if("function"==typeof e.getFromChildren?e.getFromChildren("rebuildWithTransient"):void 0)return!0;const r=this.resolveOperation(e,t);if(!r)return!1;const i=r.toString().toLowerCase();return i.includes("read")||i.includes("find")||i.includes("query")||i.includes("statement")||i.includes("page")}resolveOperation(e,t){return t||("function"==typeof e.getFromChildren?e.getFromChildren("operation"):void 0)}shouldRefreshAfterWrite(e,r,i,a){if(!i)return!1;const n=t.Model.pk(e),o=t.Model.composed(e,n),s=t.Model.generated(e,n),c=null!=a;return!(c||!o)||(!c&&s?(r.logger.warn("Cannot refresh record with private generated primary key"),!1):c)}injectTransientOverrides(t,r){const i=this.hasMeaningfulTransientData(t),a=!!r.getOrUndefined("allowContextTransientMap");if(!i&&!a)return;const n=r.toOverrides(),o=i?Object.assign({},t):{};return a&&Object.keys(n).length&&(o[e.FabricModelKeys.OVERRIDES]=n),Object.keys(o).length?o:void 0}hasMeaningfulTransientData(e){if(null==e)return!1;if(Array.isArray(e))return e.some(e=>this.hasMeaningfulTransientData(e));if("object"!=typeof e)return!0;const t=Object.entries(e);return!!t.length&&t.some(([,e])=>this.hasMeaningfulTransientData(e))}getEndorsingOrganizations(e){const t=e.getOrUndefined("endorsingOrgs")||e.getOrUndefined("endorsingOrgs");return t&&t.length?t:e.getFromChildren("endorsingOrgs")||e.getFromChildren("endorsingOrgs")}shouldForceGatewayHydration(e){return!!this.config.allowGatewayOverride}async create(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.create),d=t.Model.tableName(e);c.verbose(`adding entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=await this.submitTransaction(l,r.OperationKeys.CREATE,[this.serializer.serialize(a,e.name)],u?{[d]:n}:void 0,this.getEndorsingOrganizations(l),e),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,W(e,t.Model.merge(Object.assign({},a,n||{}),p,e),i),l):p}async healthcheck(e,...r){const{log:i,ctx:a}=this.logCtx(r,this.healthcheck),n=t.Model.tableName(e);i.verbose(`reading entry from ${n} table`);const o=await this.evaluateTransaction(a,"healthcheck",[],void 0,void 0,e);return JSON.parse(this.decode(o))}async read(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.read),s=t.Model.tableName(e);n.verbose(`reading entry from ${s} table`),n.debug("pk: "+i);const c=await this.evaluateTransaction(o,r.OperationKeys.READ,[i.toString()],void 0,void 0,e);return this.serializer.deserialize(this.decode(c))}updatePrefix(e,r,a,...n){const o=t.Model.tableName(e),{ctxArgs:s}=this.logCtx(n,this.updatePrefix),c={};return c[i.CouchDBKeys.TABLE]=o,Object.assign(c,a),[e,r,c,...s]}async update(e,i,a,n={},...o){const s=[...o],{log:c,ctx:l}=this.logCtx(s,this.update);c.info("CLIENT UPDATE class : "+typeof e);const d=t.Model.tableName(e);c.verbose(`updating entry to ${d} table`),c.debug("pk: "+i);const u=n&&Object.keys(n).length>0,h=u||this.shouldForceGatewayHydration(l),g=await this.submitTransaction(l,r.OperationKeys.UPDATE,[this.serializer.serialize(a,e.name)],u?{[d]:n}:void 0,this.getEndorsingOrganizations(l),e),p=this.serializer.deserialize(this.decode(g));return this.shouldRefreshAfterWrite(e,l,h,i)?this.read(e,W(e,t.Model.merge(Object.assign({},a,n||{}),p,e),i),l):p}async delete(e,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.delete),s=t.Model.tableName(e),c=t.Model.isTransient(e)||this.shouldForceGatewayHydration(o);let l;const d=this.shouldRefreshAfterWrite(e,o,c,i);d&&(l=await this.read(e,i,o)),n.verbose(`deleting entry from ${s} table`),n.debug("pk: "+i);const u=await this.submitTransaction(o,r.OperationKeys.DELETE,[i.toString()],void 0,this.getEndorsingOrganizations(o),e);return d?l:this.serializer.deserialize(this.decode(u))}async raw(e,i=!0,a,...n){const{log:o,ctx:s}=this.logCtx(n,this.raw);let c,l;o.info("Performing raw statement on table "+t.Model.tableName(a));try{c=await this.evaluateTransaction(s,"raw",[JSON.stringify(e),i],void 0,void 0,a)}catch(e){throw this.parseError(e)}try{l=JSON.parse(this.decode(c))}catch(e){throw new r.SerializationError("Failed to process result: "+e)}if(Array.isArray(l)){if(!l.length)return l;const e=l[0];return t.Model.isModel(e)?l.map(e=>t.Model.build(e)):l}return d=l,t.Model.isModel(d)?t.Model.build(d):d;var d}async view(e,t,i,...a){const{log:n,ctx:o}=this.logCtx(a,this.view);let s,c;n.info(`Querying view ${e}/${t}`);try{s=await this.evaluateTransaction(o,"view",[e,t,JSON.stringify(i)],void 0,void 0,void 0)}catch(e){throw this.parseError(e)}try{c=JSON.parse(this.decode(s))}catch(e){throw new r.SerializationError("Failed to process view result: "+e)}return c}getClient(){return this._client||(this._client=Je.getClient(this.config)),this._client}async Gateway(e){return Je.getGateway(e,this.config,this.client)}async Contract(e,t){return Je.getContract(await this.Gateway(e),this.config,t,e)}async transaction(e,t,r=!0,i,a={},n,o){const s=this.log.for(this.transaction);if(a=this.injectTransientOverrides(a,e),r&&this.shouldUseLegacyGateway(e)){const r=this.prepareLegacyArgs(i),n=this.buildLegacyTransient(a),s=this.buildLegacyPeerConfigs(e);return await this.submitLegacyWithExplicitEndorsers(e,t,r,n,s,o)}const c=await this.Gateway(e);try{const c=await this.Contract(e,o);s.verbose(`${r?"Submit":"Evaluate"}ting transaction ${c.getContractName()}.${t}`),s.debug("args: "+(i?.map(e=>e.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate,d=(i||[]).map(e=>this.normalizeTransactionArgument(e)),u=Object.entries(a||{});n=n?.length?n:void 0;const h={arguments:d,transientData:u.length?u.reduce((e,[t,r])=>(e[t]=JSON.stringify(r),e),{}):void 0,endorsingOrganizations:e.getOrUndefined("allowManualEndorsingOrgs")&&n||void 0};return await l.call(c,t,h)}catch(e){throw this.parseError(e)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}normalizeTransactionArgument(e){return null==e||"string"==typeof e||"object"!=typeof e||e instanceof Uint8Array?e:JSON.stringify(e)}shouldUseLegacyGateway(e){return!!e.getOrUndefined("legacy")&&!!this.config.allowGatewayOverride}prepareLegacyArgs(e){return(e||[]).map(e=>"string"==typeof e?e:JSON.stringify(e))}buildLegacyTransient(e){if(!e)return;const t=Object.entries(e);if(!t.length)return;const r={};for(const[e,i]of t)r[e]=Buffer.from(JSON.stringify(i));return r}resolveLegacyMspCount(){const e=this.config.legacyMspCount??1,t=Number(e);return!Number.isFinite(t)||1>t?1:Math.floor(t)}pickLegacyCandidates(e,t){if(!e.length||0>=t)return[];const r=[...e],i=Math.min(t,r.length),a=[];for(;a.length<i&&r.length;){const e=Math.floor(Math.random()*r.length),[t]=r.splice(e,1);t&&a.push(t)}return a}buildLegacyPeerConfigs(e){const t=[{mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias,tlsCert:this.config.tlsCert}];let r=this.getEndorsingOrganizations(e)||[];r=Array.isArray(r)?r:[r];const i=(r.filter(e=>!!e)||[]).filter(e=>e!==this.config.mspId);if(!i.length)return t;const n=this.config.mspMap,o=this.resolveLegacyMspCount();for(const e of i){const r=n?.[e];if(!r?.length)throw new a.UnsupportedError(`No peer mapping available for MSP ${e}. Provide it via config.mspMap`);const i=this.pickLegacyCandidates(r,o);if(!i.length)throw new a.UnsupportedError(`No valid peer mapping available for MSP ${e}. Provide it via config.mspMap`);for(const r of i){if(!r.endpoint)throw new a.UnsupportedError(`Invalid peer mapping for MSP ${e}: missing endpoint`);t.push({mspId:e,peerEndpoint:r.endpoint,peerHostAlias:r.alias,tlsCert:r.tlsCert||this.config.tlsCert})}}return t}async submitLegacyWithExplicitEndorsers(e,t,i,a,n,o){const s=this.log.for(this.submitLegacyWithExplicitEndorsers),c=this.normalizeLegacyPeers(n),l=await this.resolveLegacyIdentityMaterial(),d=await f.Wallets.newInMemoryWallet(),u=this.config.mspId+"-legacy";await d.put(u,{credentials:{certificate:l.certificate,privateKey:l.privateKey},mspId:this.config.mspId,type:"X.509"});const h=await this.buildLegacyConnectionProfile(c),g=new f.Gateway;try{await g.connect(h,{identity:u,wallet:d,discovery:{enabled:!0,asLocalhost:this.shouldTreatPeersAsLocalhost(c)},tlsInfo:{certificate:l.certificate,key:l.privateKey}});let n=this.config.channel,p=this.config.chaincodeName,f=this.config.contractName;if(o)if("string"==typeof o)f=o;else{if(!e)throw new r.InternalError("No context received to determine chaincode config");n=await this.channelFor(o,e)||n,p=await this.chaincodeFor(o,e)||p,f=await this.contractFor(o,e)}const y=await g.getNetwork(n),m=y.getContract(p,f).createTransaction(t);a&&m.setTransient(a);const w=c.map(e=>y.getChannel().getEndorser(e.name)).filter(e=>!!e);w.length&&m.setEndorsingPeers(w),s.verbose(`Legacy submitting ${f}.${t} via peers ${c.map(e=>e.peerEndpoint).join(", ")}`);const b=await m.submit(...i);return Uint8Array.from(b)}catch(e){throw this.parseError(e)}finally{g.disconnect()}}normalizeLegacyPeers(e){const t=new Map,r=e=>{const r=`${e.peerEndpoint}|${e.peerHostAlias||""}`;if(t.has(r))return;const i=`peer-${e.mspId}-${t.size}`;t.set(r,{...e,name:i})};return e.forEach(r),r({mspId:this.config.mspId,peerEndpoint:this.config.peerEndpoint,peerHostAlias:this.config.peerHostAlias}),Array.from(t.values())}async resolveLegacyIdentityMaterial(){return{certificate:await this.readPemInput(this.config.certCertOrDirectoryPath),privateKey:await this.readPemInput(this.config.keyCertOrDirectoryPath)}}async buildLegacyConnectionProfile(e){const t={},r={},i={};for(const a of e){const e=await this.readPemInput(a.tlsCert||this.config.tlsCert),n=a.peerHostAlias||this.extractHost(a.peerEndpoint);t[a.name]={url:this.ensureGrpcUrl(a.peerEndpoint),tlsCACerts:{pem:e},grpcOptions:{"ssl-target-name-override":n,hostnameOverride:n}},r[a.name]={endorsingPeer:!0,chaincodeQuery:!0,ledgerQuery:!0,eventSource:!0},i[a.mspId]=i[a.mspId]||{mspid:a.mspId,peers:[]},i[a.mspId].peers.push(a.name)}return{name:"legacy-manual",version:"1.0.0",client:{organization:this.config.mspId},organizations:i,peers:t,orderers:{},channels:{[this.config.channel]:{peers:r}}}}shouldTreatPeersAsLocalhost(e){return e.every(e=>this.isLocalEndpoint(e.peerEndpoint))}isLocalEndpoint(e){const t=this.extractHost(e).toLowerCase();return"localhost"===t||"127.0.0.1"===t}extractHost(e){return e.replace(/^grpcs?:\/\//,"").split(":")[0]}ensureGrpcUrl(e){return/^grpcs?:\/\//i.test(e)?e:"grpcs://"+e}async readPemInput(e){if(!e)throw new r.InternalError("Missing certificate or key material");if(Buffer.isBuffer(e))return e.toString("utf8");const t=e.trim();if(/-----BEGIN [A-Z ]+-----/.test(t))return t;const i=await y.promises.stat(e).catch(()=>{});return i?.isDirectory()?await je(e):(await Ke(e)).toString()}parseError(e){return Je.parseError(e)}async submitTransaction(e,t,r,i,a,n){return this.transaction(e,t,!0,r,i,a,n)}async evaluateTransaction(e,t,r,i,a,n){return this.transaction(e,t,!1,r,i,a,n)}async migrate(e,...t){const r=t[t.length-1],i=r instanceof a.Context?r:void 0,n=i?t.slice(0,-1):t,o=i||await this.context(a.PersistenceKeys.MIGRATION,{},void 0);return this.submitTransaction(o,"migrate",[e,n],void 0,void 0,"MigrationContract")}async shutdown(...e){await super.shutdown(...e),this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static async getContract(e,t,i,a){const n=this.log.for(this.getContract);let o=t.channel,s=t.chaincodeName,c=t.contractName;if(i)if("string"==typeof i)c=i;else{if(!a)throw new r.InternalError("No context received to determine chaincode config");o=await this.channelFor(i,t,a)||o,s=await this.chaincodeFor(i,t,a)||s,c=await this.contractFor(i,t,a)}const l=this.getNetwork(e,o);let d;try{n.debug(`Retrieving chaincode ${s} contract ${c} from network ${o}`),d=l.getContract(s,c)}catch(e){throw this.parseError(e)}return d}static getNetwork(e,t){const r=c.Logging.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+t),i=e.getNetwork(t)}catch(e){throw this.parseError(e)}return i}static async getGateway(e,t,r){return await this.getConnection(r||await this.getClient(t),t,e)}static getClient(e){const t=this.log.for(this.getClient);t.debug("generating TLS credentials for msp "+e.mspId);let i=e.tlsCert;if("string"==typeof i)if(i.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))i=Buffer.from(i,"utf8");else try{i=Buffer.from(y.readFileSync(i,"utf8"))}catch(e){throw new r.InternalError(`Failed to read the tls certificate from ${i}: ${e}`)}const a=b.credentials.createSsl(i);return t.debug("generating Gateway Client for url "+e.peerEndpoint),new p.Client(e.peerEndpoint,a,{"grpc.max_receive_message_length":1024*(e.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(e.sizeLimit||15)*1024})}static async getConnection(e,t,r){const i=c.Logging.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${t.mspId} under ${t.certCertOrDirectoryPath}`);const n=await ke(t.mspId,t.certCertOrDirectoryPath);try{i.debug("preparing transaction signer for "+ce.fabricIdFromCertificate(n.credentials.toString()))}catch(e){i.error("Failed to extract Fabric ID from certificate",e)}let o;if(t.hsm)throw new a.UnsupportedError("HSM NOT IMPLEMENTED");o=await ze(t.keyCertOrDirectoryPath);const s={client:e,identity:n,signer:o,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+t.mspId);const d=l.connect(s);return t.hsm&&(d.close=new Proxy(d.close,{apply(e,t,r){Reflect.apply(e,t,r)}})),d}Dispatch(){return new Je._baseDispatch(this.client)}static chaincodeFor(e,r,...i){return t.Model.chaincodeOf(e,...i)||r.chaincodeName}static channelFor(e,r,...i){return t.Model.channelOf(e,...i)||r.channel}static contractFor(e,r,...i){return t.Model.contractOf(e,...i)||ue(e,...i)}static parseError(e){let t="string"==typeof e?e:e.message;return e instanceof l.GatewayError&&e.details.length&&10===e.code&&(t=""+e.details[0].message),e instanceof l.EndorseError&&e.details.length&&10===e.code&&e.details[0].message?.includes(a.UnsupportedError.name)&&(t=""+e.details[0].message),t.includes("MVCC_READ_CONFLICT")?new B(e):t.includes("DEADLINE_EXCEEDED")?new j(e):t.includes("chaincode stream terminated")||t.includes("RESOURCE_EXHAUSTED")||t.includes("received message larger than max")||t.includes("grpc: received message larger")?new U(e):t.includes("ENDORSEMENT_POLICY_FAILURE")?new k(e):t.includes("PHANTOM_READ_CONFLICT")?new K(e):e instanceof Error&&e.code&&9===e.code?new $(e):t.includes(r.ValidationError.name)?new r.ValidationError(e):t.includes(r.NotFoundError.name)?new r.NotFoundError(e):t.includes(r.ConflictError.name)?new r.ConflictError(e):t.includes(r.BadRequestError.name)?new r.BadRequestError(e):t.includes(a.QueryError.name)?new a.QueryError(e):t.includes(a.PagingError.name)?new a.PagingError(e):t.includes(a.UnsupportedError.name)?new a.UnsupportedError(e):t.includes(a.MigrationError.name)?new a.MigrationError(e):t.includes(a.ObserverError.name)?new a.ObserverError(e):t.includes(a.AuthorizationError.name)?new a.AuthorizationError(e):t.includes(a.ForbiddenError.name)?new a.ForbiddenError(e):t.includes(a.ConnectionError.name)?new a.ConnectionError(e):t.includes(r.SerializationError.name)?new r.SerializationError(e):new r.InternalError(e)}}n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"create",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"healthcheck",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"read",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"update",null),n.__decorate([c.debug(),c.final(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"delete",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[Object,"function"==typeof(Ye="undefined"!=typeof D&&D)?Ye:Object,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"raw",null),n.__decorate([c.debug(),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[String,String,Object,Ge]),n.__metadata("design:returntype",Promise)],Je.prototype,"view",null),Je.decoration(),a.Adapter.setCurrent(X);class We extends a.Dispatch{constructor(e){super(),this.client=e,this.decoder=new TextDecoder("utf8")}async close(...e){const{log:t,ctxArgs:r}=(await this.logCtx(e,a.PersistenceKeys.SHUTDOWN,!0)).for(this.close);try{await super.close(...r)}catch(e){t.error("Failed to close Fabric proxies event listener",e)}if(this.listeningStack)try{await this.listeningStack.close()}catch(e){t.error("Failed to close Fabric event listener",e)}finally{this.listeningStack=void 0}}parsePayload(e){const t=this.decoder.decode(e);return JSON.parse(t)}observe(e){if(!(e instanceof Je))throw new a.UnsupportedError("Only FabricClientAdapter can be observed by dispatch");return super.observe(e),()=>this.unObserve(e)}async updateObservers(e,i,n,...o){const{log:s,ctxArgs:c}=a.Adapter.logCtx(this.updateObservers,i,!1,...o);if(this.adapter)try{await this.adapter.refresh(e,i,n,...c)}catch(e){throw new r.InternalError("Failed to refresh dispatch: "+e)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof e?e:t.Model.tableName(e)}:${i}`)}async handleEvents(e){if(!this.listeningStack)throw new r.InternalError('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new r.InternalError("No adapter found. should be impossible");const i=e||await this.adapter.context(r.OperationKeys.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||t.Model),a=this.log.for(this.handleEvents);a.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const e of this.listeningStack){const{table:r,event:n,owner:o}=Ne(e.eventName);if(this.adapter.config?.mspEventOnly&&o&&o!==this.adapter.config?.mspId)continue;const s=this.parsePayload(e.payload);try{const e=(r?t.Model.get(r):t.Model.get(this.models[0].name))??(r||this.models[0]?.name),a=s.result?[s.result,i]:[i];await this.updateObservers(e,n,s.id,...a)}catch(e){a.error(`Failed update observables for table ${r} event ${n} id: ${s.id}: ${e}`)}}}catch(e){a.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${e}`),await this.close(i)}}async initialize(){if(!this.adapter)throw new r.InternalError("No adapter or config observed for dispatch");const e=!1!==this.adapter.config.syntheticEvents;if(!e){const e=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},t.Model),{ctx:i}=this.logCtx([e],this.initialize),a=(await Je.getGateway(i,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new r.InternalError("No adapter observed for dispatch");this.listeningStack=await a.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(i)}[r.OperationKeys.CREATE,r.OperationKeys.UPDATE,r.OperationKeys.DELETE,r.BulkCrudOperationKeys.CREATE_ALL,r.BulkCrudOperationKeys.UPDATE_ALL,r.BulkCrudOperationKeys.DELETE_ALL].forEach(i=>{if(!this.adapter)throw new r.InternalError("No adapter provided for the fallback of fully segregated models");if(!this.adapter[i])throw new r.InternalError(`Method ${i} not found in ${this.adapter.alias} adapter to bind Observables Dispatch`);let a=Object.getOwnPropertyDescriptor(this.adapter,i),n=this.adapter;for(;!a&&n!==Object.prototype;)n=Object.getPrototypeOf(n),a=Object.getOwnPropertyDescriptor(n,i);function o(e){switch(e){case r.BulkCrudOperationKeys.CREATE_ALL:return r.OperationKeys.CREATE;case r.BulkCrudOperationKeys.UPDATE_ALL:return r.OperationKeys.UPDATE;case r.BulkCrudOperationKeys.DELETE_ALL:return r.OperationKeys.DELETE;default:return e}}a&&a.writable?this.adapter[i]=new Proxy(this.adapter[i],{apply:async(r,a,n)=>{const s=await r.apply(a,n),c=n[0];if(!e&&!t.Model.isTransient(c))return s;const{log:l,ctxArgs:d,ctx:u}=a.logCtx(n.slice(n.length-1),r),h=n[1],g=[c,o(i),h];return u.getOrUndefined("observeFullResult")&&g.push(s),this.updateObservers(g[0],g[1],g[2],...g.slice(3),...d).catch(e=>l.error(`Failed to dispatch observer refresh for ${i} on ${c.name||c} for ${h}: ${e}`)),s}}):this.log.error(`Could not find method ${i} to bind Observables Dispatch`)})}}Je&&(Je._baseDispatch=We);const Qe="##VERSION##",Xe="##PACKAGE##";o.Metadata.registerLibrary(Xe,Qe),e.AllowanceError=x,e.BalanceError=_,e.BaseEncoder=se,e.COMMIT="56e76d3",e.ClientSerializer=Y,e.CoreUtils=Z,e.CryptoUtils=ce,e.DefaultContractResolver=ue,e.DefaultFabricClientFlags=Pe,e.DeterministicSerializer=Te,e.EndorsementError=$,e.EndorsementPolicyError=k,e.FULL_VERSION="0.13.29-56e76d3",e.FabricClientAdapter=Je,e.FabricClientContext=Ge,e.FabricClientDispatch=We,e.FabricClientRepository=H,e.FabricERC20ClientRepository=J,e.FabricEnrollmentService=le,e.FabricFlavour=X,e.FabricIdentityService=Re,e.ImplicitPrivateCollection=Ce,e.MissingContextError=N,e.MissingPKCSS11Lib=P,e.ModelCollection=(e,i)=>{const a=i||("function"!=typeof e?t.Model.ownerOf(e):void 0),n="function"==typeof e?e:e.constructor;if(!a)throw new r.InternalError(`Model ${n.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${c.toPascalCase(n.name)}${a?c.toPascalCase(a):""}`},e.MvccReadConflictError=B,e.NamespaceCollection=e=>(i,a)=>{const n=a||("function"!=typeof i?t.Model.ownerOf(i):void 0),o="function"==typeof i?i:i.constructor;if(!n)throw new r.InternalError(`Model ${o.name} is not owned by any organization. did you use @ownedBy() (or provide the name)?`);return`${e}${n?c.toPascalCase(n):""}`},e.NotInitializedError=R,e.OverflowError=I,e.Owner=function(){return function(e,t,i){const n=i.value;return i.value=async function(...e){const i=e[0],o=i.clientIdentity.getID(),s=await this.tokenRepository.select(),c=await s.execute(i);if(0==c.length)throw new r.NotFoundError("No tokens avaialble");if(c.length>1)throw new r.NotFoundError("To many token available : "+c.length);if(c[0].owner!=o)throw new a.AuthorizationError(`User not authorized to run ${t} on the token`);return await n.apply(this,e)},i}},e.PACKAGE_NAME=Xe,e.PhantomReadConflictError=K,e.QueryResultTooLargeError=U,e.RegistrationError=T,e.RegistrationRequestBuilder=de,e.SEGREGATED_COLLECTION_EXTRACTION_PRIORITY=35,e.SimpleDeterministicSerializer=Fe,e.TransactionBufferSizeError=z,e.TransactionLimitsError=L,e.TransactionTimeoutError=j,e.UnauthorizedPrivateDataAccess=F,e.VERSION=Qe,e.add=(e,t)=>{const r=e+t;if(e!==r-t||t!==r-e)throw new I(`Addition overflow: ${e} + ${t}`);return r},e.applyMirrorFlags=async(e,r,i)=>{if(!r)return;const a=t.Model.mirroredAt(e);if(!a)return;if(!(r===a.mspId||a.condition&&a.condition(r)))return;const n=await fe(new e,a.resolver,i);i.put("segregateRead",void 0),i.put("segregateReadStack",void 0),i.put("fullySegregated",!0),i.put("mirror",!0),i.put("mirrorCollection",n),i.readFrom(n)},e.applySegregationFlags=Ae,e.chaincode=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CHAINCODE,r)},e.channel=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CHANNEL,r)},e.collectionFor=v,e.contentOfLoadFile=Be,e.contract=t=>{const r={resolver:t};return o.metadata(e.FabricModelKeys.CONTRACT,r)},e.createMirrorHandler=ye,e.deleteMirrorHandler=we,e.evalMirrorMetadata=fe,e.extractCollections=async(e,i,a={},n=!1)=>{let{privateCols:o,sharedCols:s}=t.Model.collectionsFor(e);function c(t){try{return"string"==typeof t?t:t(e,i[0])}catch(e){throw new r.InternalError(e)}}o=o.map(c),s=s.map(c);const l=Object.assign({},{requiredPeerCount:0,maxPeerCount:0,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.privateCols||{}),d=Object.assign({},{requiredPeerCount:1,maxPeerCount:2,blockToLive:0,memberOnlyRead:!0,memberOnlyWrite:!0},a?.sharedCols||{}),u=n?t.Model.mirroredAt(e):void 0,h=i.map(e=>o.map(t=>{const{requiredPeerCount:r,maxPeerCount:i,blockToLive:a,memberOnlyRead:n}=l;return O(e,t,r,i,a,n,!1)})).flat();if(u&&u.mspId){const t="string"==typeof u.resolver?u.resolver:u.resolver(e,u.mspId);if(t&&!h.some(e=>e.name===t&&e.policy.includes(u.mspId))){const{requiredPeerCount:e,maxPeerCount:r,blockToLive:i,memberOnlyRead:a}=l;h.push(O(u.mspId,t,e,r,i,a,!1))}}return{privates:h,shared:s.map(e=>{const{requiredPeerCount:t,maxPeerCount:r,blockToLive:a,memberOnlyRead:n,memberOnlyWrite:o}=d;return S(i,e,t,r,a,n,o)})}},e.extractIds=W,e.extractMspId=he,e.extractPrivateKey=Ue,e.extractSegregatedCollections=ve,e.generateFabricEventName=(e,t,r)=>{const i=[e,t];return r&&i.push(r),i.join("_")},e.generateModelDesignDocs=(e,t)=>{const r=i.generateViews([e]),a=t||{};return r.forEach(e=>{a[e._id]=e}),r},e.generateModelIndexes=(e,r)=>{const a=i.generateIndexes([e]),n=((e,r)=>{try{return t.Model.pk(e)+""}catch{const t=`Skipping ${e.name} while extracting indexes: no primary key is defined`;return void r.verbose(t)}})(e,r);return((e,t)=>t?e.map(e=>{const r=e?.index?.fields;if(!e?.name||"string"!=typeof e.name||!e.name.includes("defaultQuery")||!Array.isArray(r)||0===r.length)return e;if(r.filter(e=>"object"==typeof e&&!Array.isArray(e)).length!==r.length)return e;if(r.some(e=>!(!e||"object"!=typeof e||Array.isArray(e))&&Object.prototype.hasOwnProperty.call(e,t)))return e;const i=r[r.length-1],a="desc"===((Object.values(i||{})[0]||"asc")+"").toLowerCase()?"desc":"asc";return Object.assign({},e,{index:Object.assign({},e.index,{fields:[...r,{[t]:a}]})})}):e)(a,n||"")},e.getAkiAndSerialFromCert=ee,e.getCAUser=async(e,t,r,i)=>{$e.debug(`Creating a CA ${i} user ${e} with certificate ${r}`);const a=new d.User(e),n=d.User.newCryptoSuite();a.setCryptoSuite(n);const o=n.createKeyFromRaw(t);return await a.setEnrollment(o,r,i),a},e.getFirstDirFileName=Le,e.getFirstDirFileNameContent=je,e.getIdentity=ke,e.getSigner=ze,e.mirror=(t,i,a)=>{const n="string"!=typeof i&&!!i,s=n?void 0:i,c=n?i:a;return o.Decoration.for(e.FabricModelKeys.MIRROR).define({decorator:(t,i,a)=>{const n={condition:a,mspId:i,resolver:t};return o.apply(o.metadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.MIRROR),n),r.onRead(Ee,n,{priority:30}),r.onCreate(be,n,{priority:20}),r.onUpdate(be,n,{priority:20}),r.onDelete(be,n,{priority:20}),r.onCreate(ye,n,{priority:100}),r.onUpdate(me,n,{priority:100}),r.onDelete(we,n,{priority:100}))},args:[t,s,c]}).apply()},e.mirrorWriteGuard=be,e.ownedBy=()=>o.Decoration.for(e.FabricModelKeys.OWNED_BY).define({decorator:()=>(i,a)=>o.apply(t.required(),r.generated(),r.readonly(),r.onCreate(ge),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,e.FabricModelKeys.OWNED_BY),a))(i,a),args:[]}).apply(),e.ownedByOnCreate=ge,e.parseEventName=Ne,e.privateCollectionFor=O,e.privateData=(t=Ce)=>o.Decoration.for(e.FabricModelKeys.PRIVATE).define({decorator:t=>_e(t,e.FabricModelKeys.PRIVATE),args:[t]}).apply(),e.readFile=Ke,e.readMirrorHandler=Ee,e.readModelFile=C,e.readModelFolders=async(...e)=>{const t=require("fs"),r=require("path"),i=[];for(const a of e){const e=r.resolve(a),n=t.readdirSync(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()&&e.name.endsWith("js"));for(const e of n)i.push(...C(e))}return i},e.safeParseInt=e=>{if(!/^\d+$/.test(e))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string contains digits"));const i=parseInt(e);if(isNaN(i))throw new r.ValidationError(t.stringFormat("Failed to parse: {0}","string is not a parsable integer"));return i},e.segregatedDataOnCreate=Oe,e.segregatedDataOnDelete=Ie,e.segregatedDataOnRead=Se,e.segregatedDataOnUpdate=Me,e.sharedCollectionFor=S,e.sharedData=t=>o.Decoration.for(e.FabricModelKeys.SHARED).define({decorator:t=>_e(t,e.FabricModelKeys.SHARED),args:[t]}).apply(),e.sortKeysOnlyRecursive=xe,e.sub=(e,t)=>{const r=e-t;if(e!==r+t||t!==e-r)throw new I(`Subtraction overflow: ${e} - ${t}`);return r},e.transactionId=()=>o.Decoration.for(e.FabricModelKeys.TRANSACTION_ID).define({decorator:()=>(i,a)=>o.apply(t.required(),r.readonly(),r.onCreate(pe),r.onUpdate(pe),o.propMetadata(o.Metadata.key(e.FabricModelKeys.FABRIC,a,e.FabricModelKeys.TRANSACTION_ID),a))(i,a),args:[]}).apply(),e.transactionIdOnCreate=pe,e.updateMirrorHandler=me,e.writeCollectionDesignDocs=(e,t=process.cwd(),r)=>{e?.length&&A(e,t,r)},e.writeCollections=(e,t=process.cwd(),r="collections_config")=>{const i=require("fs"),a=require("path"),n=a.resolve(a.join(t,`./META-INF/${r}.json`));!function e(t){const r=a.dirname(t);if(i.existsSync(r))return!0;e(r),i.mkdirSync(r)}(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))},e.writeDesignDocs=A,e.writeIndexes=(e,t=process.cwd(),r)=>{const i=require("fs"),a=require("path");e.forEach(e=>{const n=a.resolve(a.join(t,`./META-INF/statedb/couchdb/${r?`collections/${r}/`:""}indexes/${e.name}.json`));E(n),i.writeFileSync(n,JSON.stringify(e,void 0,2))})}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decorator-validation"),require("@decaf-ts/db-decorators"),require("@decaf-ts/for-couchdb"),require("@decaf-ts/core"),require("tslib"),require("@decaf-ts/decoration"),require("fabric-ca-client"),require("@decaf-ts/logging"),require("@hyperledger/fabric-gateway"),require("fabric-common"),require("crypto"),require("@peculiar/x509"),require("@peculiar/webcrypto"),require("@grpc/grpc-js"),require("fabric-network"),require("fs")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decorator-validation","@decaf-ts/db-decorators","@decaf-ts/for-couchdb","@decaf-ts/core","tslib","@decaf-ts/decoration","fabric-ca-client","@decaf-ts/logging","@hyperledger/fabric-gateway","fabric-common","crypto","@peculiar/x509","@peculiar/webcrypto","@grpc/grpc-js","fabric-network","fs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-fabric"]={},e.decafTsDecoratorValidation,e.decafTsDbDecorators,e.decafTsForCouchdb,e.decafTsCore,e.tslib,e.decafTsDecoration,e.fabricCaClient,e.decafTsLogging,e.hyperledgerFabricGateway,e.fabricCommon,e.crypto,e.peculiarX509,e.peculiarWebcrypto,e.grpcGrpcJs,e.fabricNetwork,e.fs);
|
|
2
2
|
//# sourceMappingURL=for-fabric.cjs.map
|