@decaf-ts/for-fabric 0.1.59 → 0.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/for-fabric.cjs +1 -1
- package/dist/for-fabric.cjs.map +1 -1
- package/dist/for-fabric.js +1 -1
- package/dist/for-fabric.js.map +1 -1
- package/lib/cli-module.cjs +7 -6
- package/lib/cli-module.js.map +1 -1
- package/lib/contracts/ContractAdapter.cjs +13 -13
- package/lib/contracts/ContractAdapter.d.ts +1 -1
- package/lib/contracts/ContractAdapter.js.map +1 -1
- package/lib/contracts/FabricContractPaginator.cjs +6 -8
- package/lib/contracts/FabricContractPaginator.js.map +1 -1
- package/lib/esm/cli-module.js +7 -6
- package/lib/esm/cli-module.js.map +1 -1
- package/lib/esm/contracts/ContractAdapter.d.ts +1 -1
- package/lib/esm/contracts/ContractAdapter.js +13 -13
- package/lib/esm/contracts/ContractAdapter.js.map +1 -1
- package/lib/esm/contracts/FabricContractPaginator.js +6 -8
- package/lib/esm/contracts/FabricContractPaginator.js.map +1 -1
- package/lib/esm/index.d.ts +2 -1
- package/lib/esm/index.js +3 -3
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/index.cjs +3 -3
- package/lib/index.d.ts +2 -1
- package/lib/index.js.map +1 -1
- package/lib/version.cjs +1 -1
- package/lib/version.d.ts +1 -1
- package/package.json +2 -2
package/dist/for-fabric.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Model as t,JSONSerializer as e,ModelKeys as r,ValidationKeys as i,required as n,model as s}from"@decaf-ts/decorator-validation";import{Metadata as a,Decoration as o,propMetadata as c,description as l,uses as u}from"@decaf-ts/decoration";import{DBKeys as p,OperationKeys as d,BulkCrudOperationKeys as g,BaseError as h,InternalError as y,NotFoundError as w,ConflictError as f,SerializationError as m,BadRequestError as b,onCreate as x,onCreateUpdate as S,version as v,ValidationError as A}from"@decaf-ts/db-decorators";import{PersistenceKeys as C,Context as k,ObserverHandler as O,Adapter as N,Repository as R,QueryError as P,PreparedStatementKeys as E,Condition as z,Sequence as $,UUID as T,SequenceModel as I,Serial as B,PagingError as D,UnsupportedError as F,MigrationError as j,ObserverError as _,AuthorizationError as L,ForbiddenError as q,ConnectionError as J,column as M,createdAt as U,updatedAt as V,createdBy as Q,updatedBy as H,pk as Y,BaseModel as K,oneToOne as X,Cascade as G,index as W,OrderDirection as Z,table as tt}from"@decaf-ts/core";import{CouchDBStatement as et,CouchDBKeys as rt,CouchDBGroupOperator as it,CouchDBOperator as nt,CouchDBPaginator as st,CouchDBAdapter as at}from"@decaf-ts/for-couchdb";import{Property as ot,Object as ct,Contract as lt,Transaction as ut,Context as pt}from"fabric-contract-api";import{Logging as dt,MiniLogger as gt,NumericLogLevels as ht,LogLevel as yt}from"@decaf-ts/logging";import{__decorate as wt,__metadata as ft}from"tslib";var mt,bt;(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric.",t.OWNEDBY="owned-by",t.TRANSACTION_ID="transaction-id"})(mt||(mt={})),(t=>{t.X509="X.509"})(bt||(bt={}));const xt="hlf-fabric";t.prototype.isShared=function(){return t.isShared(this.constructor)},t.prototype.isPrivate=function(){return t.isPrivate(this.constructor)},t.prototype.segregate=function(){return t.segregate(this)},t.segregate=(e=>{if(!t.isTransient(e))return{model:e};const r=a.validatableProperties(e.constructor),i=a.get(e.constructor,p.TRANSIENT),n=a.get(e.constructor,mt.PRIVATE),s=a.get(e.constructor,mt.PRIVATE),o={model:{},transient:{},private:{},shared:{}},c=Object.keys(i),l=Object.keys(n),u=Object.keys(s);for(const t of r){const r=c.includes(t),i=l.includes(t),n=u.includes(t);r?(o.transient=o.transient||{},o.transient[t]=e[t],i&&(o.private=o.private||{},o.private[t]=e[t]),n&&(o.shared=o.shared||{},o.shared[t]=e[t])):(o.model=o.model||{},o.model[t]=e[t])}return o.model=t.build(o.model,e.constructor.name),o}).bind(t),t.tableName=e=>{const r=e instanceof t?e.constructor:e;return a.get(r,C.TABLE)||(e instanceof t?e.constructor.name:e.name)},t.isPrivate=(t=>!!a.get("function"!=typeof t?t.constructor:t,mt.PRIVATE)).bind(t),a.isShared=(t=>!!a.get("function"!=typeof t?t.constructor:t,mt.SHARED)).bind(a);class St extends k{constructor(){super()}get stub(){return this.get("stub")}get timestamp(){return this.stub.getDateTimestamp()}get identity(){return this.get("identity")}toString(){return"fabric ctx"+(this.stub?" with stub":"without stub")}}class vt extends O{constructor(t=[d.CREATE,d.UPDATE,d.DELETE,g.CREATE_ALL,g.UPDATE_ALL,g.DELETE_ALL]){super(),this.supportedEvents=t}async updateObservers(t,e,r,...i){const{log:n,ctx:s}=N.logCtx(this.updateObservers,e,!1,...i),{stub:a}=s,[o,c]=i,l="string"==typeof t?t:t.name;if(-1!==this.supportedEvents.indexOf(e)){n.debug(`Emitting ${e} event`);const t=((t,e,r)=>{const i=[t,e];return r&&i.push(r),i.join("_")})(l,e,o);a.setEvent(t,Buffer.from(JSON.stringify({id:r})))}else a.setEvent(e,Buffer.from(JSON.stringify(c)))}}class At extends R{constructor(t,e,r){super(t,e),this.trackedEvents=r,this._overrides=Object.assign({},super._overrides,{ignoreValidation:!1,ignoreHandlers:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1})}async paginateBy(e,r,i={offset:1,limit:10},...n){let{offset:s,bookmark:a,limit:o}=i;if(!s&&!a)throw new P("PaginateBy needs a page or a bookmark");const{log:c,ctxArgs:l}=(await this.logCtx(n,E.PAGE_BY,!0)).for(this.paginateBy);let u;if(c.verbose(`paginating ${t.tableName(this.class)} with page size ${o}`),a)u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where(this.attr(t.pk(this.class)).gt(a)).orderBy([e,r]).paginate(o,...l),s=1;else{if(!s)throw new P("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,r]).paginate(o,...l)}const p=await u.page(s,a,...l);return u.serialize(p)}async statement(t,...e){const{log:r,ctx:i,ctxArgs:n}=(await this.logCtx(e,C.STATEMENT,!0)).for(this.statement);if(!R.statements(this,t))throw new P("Invalid prepared statement requested "+t);let s;i.logger&&i.logger.info(`Repo statement: ${t} + ${e}`),r.verbose(`Executing prepared statement ${t} with args ${n}`);try{s=await this[t](...n)}catch(e){if(e instanceof h)throw e;throw new y(`Failed to execute prepared statement ${t} with args ${n}: ${e}`)}return s}ObserverHandler(){return new vt}async updateObservers(t,e,r,...i){if(!this.trackedEvents||-1!==this.trackedEvents.indexOf(e))return await super.updateObservers(t,e,r,...i)}}class Ct extends et{constructor(t){super(t)}async executionPrefix(t,...e){const r=e.filter(Boolean);if(e.length!==r.length)throw new y(`Received an undefined in the paginator for ${t}: ${e}`);return super.executionPrefix(t,...e)}async raw(e,...r){const{ctx:i}=this.logCtx(r,this.raw),n=await this.adapter.raw(e,!0,i),s=t.pk(this.fromSelector),o=a.get(this.fromSelector,a.key(p.ID,s))?.type;return this.selectSelector?n:n.map(t=>this.processRecord(t,s,o,i))}build(){const e={};e[rt.TABLE]={},e[rt.TABLE]=t.tableName(this.fromSelector);const r={selector:e};if(this.selectSelector&&(r.fields=this.selectSelector),this.whereCondition){const t=this.parseCondition(z.and(this.whereCondition,z.attribute(rt.TABLE).eq(r.selector[rt.TABLE]))).selector,e=Object.keys(t);if(1===e.length&&-1!==Object.values(it).indexOf(e[0]))switch(e[0]){case it.AND:t[it.AND]=[...Object.values(t[it.AND]).reduce((t,e)=>{const r=Object.keys(e);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const i=r[0];return i===it.AND?t.push(...e[i]):t.push(e),t},[])],r.selector=t;break;case it.OR:{const e={};e[it.AND]=[t,...Object.entries(r.selector).map(([t,e])=>{const r={};return r[t]=e,r})],r.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,e])=>{r.selector[t],r.selector[t]=e})}if(this.orderBySelector){r.sort=r.sort||[],r.selector=r.selector||{};const[t,e]=this.orderBySelector,i={};i[t]=e,r.sort.push(i),r.selector[t]||(r.selector[t]={},r.selector[t][nt.BIGGER]=null)}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),r}}class kt extends ${constructor(t,e){super(t,e)}async current(...t){const{ctx:e,log:r}=(await this.logCtx(t,d.READ,!0)).for(this.current),{name:i,startWith:n}=this.options;try{const t=await this.repo.read(i,e);return this.parse(t.current)}catch(t){if(t instanceof w){let t;try{r.debug(`Trying to resolve current sequence ${i} value from context`),t=e.get(i),r.debug(`Retrieved cached current value for sequence ${i}: ${t}`)}catch(e){r.info(`No cached value for sequence ${i} in context`),t=n}try{return this.parse(t)}catch(t){throw new y(`Failed to parse initial value for sequence ${n}: ${t}`)}}throw new y(`Failed to retrieve current value for sequence ${i}: ${t}`)}}async increment(t,e){const r=e.logger.for(this.increment),{type:i,incrementBy:n,name:s}=this.options;if(!s)throw new y("Sequence name is required");return r.info("Obtaining sequence lock for sequence "+s),kt.lock.execute(async()=>{const a=t||n;if(a%n!==0)throw new y("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(e);async function l(t){return t instanceof Promise&&(t=await t),r.for(l).info(`Storing new ${s} seq value in cache: ${t.current}`),e.cache.put(s,t.current),t}const u=async t=>{try{return await l(this.repo.update(new I({id:s,current:t}),e))}catch(i){if(i instanceof w)return r.debug(`Sequence create ${s} current=${c} next=${t}`),l(this.repo.create(new I({id:s,current:t}),e));throw i}};if("uuid"===o)for(;;){const t=T.instance.generate(c);try{const e=await u(t);return r.debug(`Sequence uuid increment ${s} current=${c} next=${t}`),e.current}catch(t){if(t instanceof f)continue;throw t}}const p=(t=>{switch(o){case Number.name:return this.parse(t)+a;case BigInt.name:return this.parse(t)+BigInt(a);case String.name:return this.parse(t);case"serial":return B.instance.generate(t);default:throw new y("Should never happen")}})(c),d=await u(p);return r.debug(`Sequence.increment ${s} current=${c} next=${p}`),d.current},s)}}class Ot extends e{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t,e)))}preSerialize(e,i=!0){const n=Object.assign({},e);let s;try{s=a.modelName(e.constructor)}catch(t){s=void 0}function o(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(o):this.preSerialize(t)}return i&&(n[r.ANCHOR]=s||e.constructor.name),t.relations(e).forEach(t=>{n[t]=o.call(this,n[t])}),n}}class Nt extends st{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){const e=Object.assign({},t);return e.limit&&(this.limit=e.limit),e.limit=this.size,e}async page(e=1,r,...i){const{ctxArgs:n,ctx:s,log:o}=this.adapter.logCtx([r,...i],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...n);const c=Object.assign({},this.statement);if(this._recordCount&&this._totalPages)e=this.validatePage(e),c.skip=(e-1)*this.size;else{this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...c,limit:Number.MAX_VALUE},!0,...n)||[];if(this._recordCount=t.length,this._recordCount>0){const t=c?.limit||this.size;return this._totalPages=Math.ceil(this._recordCount/t),await this.page(e,...n)}}if(1!==e){if(!this._bookmark)throw new D("No bookmark. Did you start in the first page?");c.bookmark=this._bookmark}const l=await this.adapter.raw(c,!0,...n),{docs:u,bookmark:d,warning:g}=l;if(g&&o.warn(g),!this.clazz)throw new D("No statement target defined");const h=t.pk(this.clazz),y=a.get(this.clazz,a.key(p.ID,h))?.type,w=c.fields&&c.fields.length?l:l.map(t=>this.adapter.revert(t,this.clazz,$.parseValue(y,t[h]),void 0,s));return this._bookmark=d,this._currentPage=e,w}}class Rt extends y{constructor(t){super(t,Rt.name)}}class Pt extends y{constructor(t){super(t,Pt.name)}}class Et extends y{constructor(t){super(t,Et.name)}}class zt extends y{constructor(t){super(t,zt.name,500)}}class $t extends h{constructor(t){super($t.name,t,409)}}async function Tt(t,e,r,i){try{const e=t.get("identity");i[r]=e.getID()}catch(t){throw new F("No User found in context. Please provide a user in the context")}}class It extends at{getClient(){throw new F("Client is not supported in Fabric contracts")}static{this.textDecoder=new TextDecoder("utf8")}static{this.serializer=new Ot}get Context(){return St}repository(){return At}Paginator(t,e,r){return new Nt(this,t,e,r)}async Sequence(t){return new kt(t,this)}constructor(t,e){super(t,xt,e)}for(t,...e){return super.for(t,...e)}async create(e,r,i,...n){const{ctx:s,log:a}=this.logCtx(n,this.create);a.info("in ADAPTER create with args "+n);const o=t.tableName(e);try{a.info(`adding entry to ${o} table with pk ${r}`);const t=s.stub.createCompositeKey(o,[r+""]);i=await this.putState(t,i,s)}catch(t){throw this.parseError(t)}return i}async read(e,r,...i){const{ctx:n,log:s}=this.logCtx(i,this.read);s.info("in ADAPTER read with args "+i);const a=t.tableName(e);let o;try{const t=n.stub.createCompositeKey(a,[r+""]);o=await this.readState(t,n)}catch(t){throw this.parseError(t)}return o}async update(e,r,i,...n){const{ctx:s,log:a}=this.logCtx(n,this.update),o=t.tableName(e);try{a.verbose(`updating entry to ${o} table with pk ${r}`);const t=s.stub.createCompositeKey(o,[r+""]);i=await this.putState(t,i,s)}catch(t){throw this.parseError(t)}return i}async delete(e,r,...i){const{ctx:n,log:s,ctxArgs:a}=this.logCtx(i,this.delete),o=t.tableName(e);let c;try{const t=n.stub.createCompositeKey(o,[r+""]);c=await this.read(e,r,...a),s.verbose(`deleting entry with pk ${r} from ${o} table`),await this.deleteState(t,n)}catch(t){throw this.parseError(t)}return c}async deleteState(t,e){const{ctx:r}=this.logCtx([e],this.deleteState);await r.stub.deleteState(t)}forPrivate(t){const e=[this.putState,this.readState,this.deleteState,this.queryResult,this.queryResultPaginated].map(t=>t.name);return new Proxy(this,{get:(r,i,n)=>e.includes(i)?new Proxy(r[i],{async apply(e,r,n){switch(i){case"putState":{const[e,r,i]=n;return await e.putPrivateData(t,r.toString(),i),i}case"deleteState":{const[e,r]=n;return e.deletePrivateData(t,r)}case"readState":{const[e,r]=n;return e.getPrivateData(t,r)}case"queryResult":{const[e,r]=n;return e.getPrivateDataQueryResult(t,r)}case"queryResultPaginated":{const[e,r,i,s]=n,a=await e.getPrivateDataQueryResult(t,r),o=[];let c=0,l=!s,u=null;for(;;){const t=await a.next();if(t.value&&t.value.value.toString()){const e=t.value.key,r=t.value.value.toString("utf8");if(!l){e===s?.toString()&&(l=!0);continue}if(o.push({Key:e,Record:JSON.parse(r)}),u=e,c++,c>=i)return await a.close(),{iterator:o,metadata:{fetchedRecordsCount:o.length,bookmark:u}}}if(t.done)return await a.close(),{iterator:o,metadata:{fetchedRecordsCount:o.length,bookmark:""}}}}default:throw new y("Unsupported method override "+i)}}}):Reflect.get(r,i,n)})}async putState(t,e,r){let i;const{log:n}=this.logCtx([r],this.putState);try{i=Buffer.from(It.serializer.serialize(e,!1))}catch(e){throw new m(`Failed to serialize record with id ${t}: ${e}`)}const s=r.get("segregated");return s?await r.stub.putPrivateData(s,t.toString(),i):await r.stub.putState(t.toString(),i),n.silly(`state stored${s?` in ${s} collection`:""} under id ${t}`),e}async readState(t,e){let r;const{log:i}=this.logCtx([e],this.readState);let n;const s=e.get("segregated");if(n=s?(await e.stub.getPrivateData(s,t.toString())).toString():(await e.stub.getState(t.toString())).toString(),!n)throw new w(`Record with id ${t}${s?` in ${s} collection`:""} not found`);i.silly(`state retrieved from${s?` ${s} collection`:""} under id ${t}`);try{r=It.serializer.deserialize(n.toString())}catch(t){throw new m("Failed to parse record: "+t)}return r}async queryResult(t,e,...r){const{ctx:i}=this.logCtx(r,this.queryResult);let n;const s=i.get("segregated");return n=s?await i.stub.getPrivateDataQueryResult(s,JSON.stringify(e)):await t.getQueryResult(JSON.stringify(e)),n}async queryResultPaginated(t,e,r=250,i,...n){const{ctx:s}=this.logCtx(n,this.readState);let a;const o=s.get("segregated");return o?(e.selector={...e.selector,_id:i?{$gt:i.toString()}:{$gte:""}},a={iterator:await t.getPrivateDataQueryResult(o,JSON.stringify(e)),metadata:{fetchedRecordsCount:r,bookmark:""}}):a=await t.getQueryResultWithPagination(JSON.stringify(e),r,i?.toString()),a}mergeModels(t){const e=t=>Object.entries(t).reduce((t,[e,r])=>(void 0!==r&&(t[e]=r),t),{});let r=t.pop();for(const i of t)r=Object.assign({},e(r),e(i));return r}decode(t){return It.textDecoder.decode(t)}async flags(t,e,r){let i=Object.assign({segregated:!1},r);return r instanceof St||(r.stub?Object.assign(i,{stub:r.stub,identity:r.clientIdentity,cert:r.clientIdentity.getIDBytes().toString(),roles:r.clientIdentity.getAttributeValue("roles"),logger:dt.for(t,{logLevel:!1,timestamp:!1,correlationId:r.stub.getTxID()},r),correlationId:r.stub.getTxID()}):i=Object.assign(i,r||{})),await super.flags(t,e,i)}index(t){return Promise.resolve(void 0)}async resultIterator(t,e,r=!1){const i=[];let n=await e.next();for(;!n.done;){if(n.value&&n.value.value.toString()){let e={};if(t.debug(n.value.value.toString("utf8")),r){e.TxId=n.value.txId,e.Timestamp=n.value.timestamp;try{e.Value=JSON.parse(n.value.value.toString("utf8"))}catch(r){t.error(r),e.Value=n.value.value.toString("utf8")}}else try{e=JSON.parse(n.value.value.toString("utf8"))}catch(r){t.error(r),e=n.value.value.toString("utf8")}i.push(e)}n=await e.next()}return t.debug(`Closing iterator after ${i.length} results`),e.close(),i}async raw(t,e=!0,...r){const{log:i,ctx:n}=this.logCtx(r,this.raw),{skip:s,limit:a}=t;let o;a||s?(delete t.limit,delete t.skip,i.debug(`Retrieving paginated iterator: limit: ${a}/ skip: ${s}`),o=(await this.queryResultPaginated(n.stub,t,a||Number.MAX_VALUE,s?.toString(),n)).iterator):(i.debug("Retrieving iterator"),o=await this.queryResult(n.stub,t,n)),i.debug("Iterator acquired");const c=await this.resultIterator(i,o);return i.debug(`returning ${Array.isArray(c)?c.length:1} results`),c}Statement(){return new Ct(this)}async createAll(e,r,i,...n){if(r.length!==i.length)throw new y("Ids and models must have the same length");const{log:s,ctxArgs:a}=this.logCtx(n,this.createAll),o=t.tableName(e);return s.debug(`Creating ${r.length} entries ${o} table`),Promise.all(r.map((t,r)=>this.create(e,t,i[r],...a)))}async updateAll(e,r,i,...n){if(r.length!==i.length)throw new y("Ids and models must have the same length");const{log:s,ctxArgs:a}=this.logCtx(n,this.updateAll),o=t.tableName(e);return s.debug(`Updating ${r.length} entries ${o} table`),Promise.all(r.map((t,r)=>this.update(e,t,i[r],...a)))}prepare(e,...r){const{log:i}=this.logCtx(r,this.prepare),n=t.tableName(e.constructor),s=t.pk(e.constructor),a=t.segregate(e),o=Object.entries(a.model).reduce((r,[i,n])=>{if(void 0===n)return r;const s=t.columnName(e,i);if(this.isReserved(s))throw new y(`Property name ${s} is reserved`);return r[s]=n,r},{});return i.silly(`Preparing record for ${n} table with pk ${e[s]}`),{record:o,id:e[s],transient:a.transient}}revert(e,r,i,n,...s){const{log:a}=this.logCtx(s,this.revert),o={};o[t.pk(r)]=i;const c="string"==typeof r?t.build(o,r):new r(o);a.silly(`Rebuilding model ${c.constructor.name} id ${i}`);const l=Object.keys(c).reduce((r,i)=>(r[i]=e[t.columnName(r,i)],r),c);return n&&(a.debug("re-adding transient properties: "+Object.keys(n).join(", ")),Object.entries(n).forEach(([t,e])=>{if(t in l&&void 0!==l[t])throw new y(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);l[t]=e})),l}createPrefix(e,r,i,...n){const{ctxArgs:s}=this.logCtx(n,this.createPrefix),a={};return a[rt.TABLE]=t.tableName(e),Object.assign(a,i),[e,r,a,...s]}updatePrefix(e,r,i,...n){const{ctxArgs:s}=this.logCtx(n,this.updatePrefix),a={};return a[rt.TABLE]=t.tableName(e),Object.assign(a,i),[e,r,a,...s]}createAllPrefix(e,r,i,...n){if(r.length!==i.length)throw new y("Ids and models must have the same length");const s=n.pop(),a=r.map((r,n)=>{const s={};return s[rt.TABLE]=t.tableName(e),Object.assign(s,i[n]),s});return[e,r,a,s]}updateAllPrefix(e,r,i,...n){if(r.length!==i.length)throw new y("Ids and models must have the same length");const s=n.pop(),a=r.map((r,n)=>{const s={};return s[rt.TABLE]=t.tableName(e),Object.assign(s,i[n]),s});return[e,r,a,s]}parseError(t,e){return It.parseError(e||t)}logCtx(t,e,r=!1,i){return r?super.logCtx.call(this,t,e,r,i).then(t=>{if(!(t.ctx instanceof St))throw new y("Invalid context binding");if(!t.ctx.stub)throw new y("Missing Stub");if(!t.ctx.identity)throw new y("Missing Identity");return Object.assign(t,{stub:t.ctx.stub,identity:t.ctx.identity})}):super.logCtx(t,e,r,i)}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes(w.name)?new w(t):e.includes(f.name)?new f(t):e.includes(b.name)?new b(t):e.includes(P.name)?new P(t):e.includes(D.name)?new D(t):e.includes(F.name)?new F(t):e.includes(j.name)?new j(t):e.includes(_.name)?new _(t):e.includes(L.name)?new L(t):e.includes(q.name)?new q(t):e.includes(J.name)?new J(t):e.includes(m.name)?new m(t):e.includes("no ledger context")?new zt("No context found. this can be caused by debugging: "+e):new y(t)}static decoration(){super.decoration(),o.flavouredAs(xt).for(C.CREATED_BY).define(x(Tt),c(C.CREATED_BY,{})).apply(),o.flavouredAs(xt).for(C.UPDATED_BY).define(S(Tt),c(C.UPDATED_BY,{})).apply(),o.flavouredAs(xt).for(C.COLUMN).extend(ot()).apply(),o.flavouredAs(xt).for(i.DATE).extend(()=>(t,e)=>{ot(e,"string:date")(t,e)}),o.flavouredAs(xt).for(C.TABLE).extend(t=>{const e=[];let r="function"==typeof t?a.constr(t):a.constr(t.constructor);for(;r&&r!==Object&&r.prototype;)e.push(r),r=Object.getPrototypeOf(r);for(;e.length>0;){const t=e.pop();ct()(t)}return ct()(t)}).apply()}}It.decoration(),N.setCurrent(xt);class Bt extends e{constructor(){super()}preSerialize(e){const i=Object.assign({},e);let n;try{n=a.modelName(e.constructor)}catch(t){n=void 0}i[r.ANCHOR]=n||e.constructor.name;const s=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return t.relations(e).forEach(t=>{i[t]=s(i[t])}),i}deserialize(e){const i=JSON.parse(e),n=i[r.ANCHOR];if(!n)throw Error("Could not find class reference in serialized model");return t.build(i,n)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}var Dt;(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(Dt||(Dt={}));let Ft=class extends t{constructor(t){super(t)}};wt([l("Stores the original timestamp of creation"),M(),U(),ft("design:type",Date)],Ft.prototype,"createdAt",void 0),wt([l("Stores the timestamp of the last update"),M(),V(),ft("design:type",Date)],Ft.prototype,"updatedAt",void 0),wt([l("Stores the version of the model"),M(),v(),ft("design:type",Number)],Ft.prototype,"version",void 0),Ft=wt([u(xt),ft("design:paramtypes",[Object])],Ft);let jt=class extends Ft{constructor(t){super(t)}};wt([l("Stores the creator"),M(),Q(),ft("design:type",String)],jt.prototype,"createdBy",void 0),wt([l("Stores the user that last updated the model"),M(),H(),ft("design:type",String)],jt.prototype,"updatedBy",void 0),jt=wt([u(xt),ft("design:paramtypes",[Object])],jt);let _t=class extends K{constructor(t){super(t)}};wt([l("Unique identifier of the credentials record"),M(),Y(),ft("design:type",String)],_t.prototype,"id",void 0),wt([l("PEM-encoded X.509 certificate for the identity"),M(),n(),ft("design:type",String)],_t.prototype,"certificate",void 0),wt([l("PEM-encoded root or intermediate certificate"),M(),n(),ft("design:type",String)],_t.prototype,"rootCertificate",void 0),wt([l("PEM-encoded private key"),M(),n(),ft("design:type",String)],_t.prototype,"privateKey",void 0),_t=wt([s(),ft("design:paramtypes",[Object])],_t);let Lt=class extends K{constructor(t){super(t),this.type=bt.X509}};function qt(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],n=r.clientIdentity.getID(),s=await this.tokenRepository.select(),a=await s.execute(r);if(0==a.length)throw new w("No tokens avaialble");if(a.length>1)throw new w("To many token available : "+a.length);if(a[0].owner!=n)throw new L(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}function Jt(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new Rt(`Addition overflow: ${t} + ${e}`);return r}function Mt(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new Rt(`Subtraction overflow: ${t} - ${e}`);return r}wt([l("Unique identifier of the identity"),Y(),ft("design:type",String)],Lt.prototype,"id",void 0),wt([X(_t,{update:G.CASCADE,delete:G.CASCADE}),ft("design:type",_t)],Lt.prototype,"credentials",void 0),wt([M(),n(),W(),ft("design:type",String)],Lt.prototype,"mspId",void 0),wt([M(),n(),ft("design:type",String)],Lt.prototype,"type",void 0),Lt=wt([s(),ft("design:paramtypes",[Object])],Lt),ct()(Date);class Ut extends lt{static{this.adapter=new It}static{this.serializer=new Bt}constructor(t,e){super(t),this.clazz=e,this.initialized=!1,this.repo=R.forModel(e)}async listBy(t,e,r,...i){const{ctxArgs:n,log:s}=(await this.logCtx([...i,t],E.LIST_BY,!0)).for(this.listBy);return s.info(`Running listBy key ${e}, order ${r} and args ${n}`),this.repo.listBy(e,r,...n)}async paginateBy(t,e,r,i={offset:1,limit:10},...n){const{ctxArgs:s,log:a}=(await this.logCtx([...n,t],E.PAGE_BY,!0)).for(this.paginateBy);return a.info(`Running paginateBy key ${e}, order ${r} with size ${i.limit} and args ${s}`),this.repo.paginateBy(e,r,i,...s)}async findOneBy(t,e,r,...i){const{ctxArgs:n,log:s}=(await this.logCtx([...i,t],E.FIND_ONE_BY,!0)).for(this.findOneBy);return s.info(`Running findOneBy key ${e}, value: ${r} with args ${n}`),this.repo.findOneBy(e,r,...n)}async statement(t,e,...r){const{ctxArgs:i,log:n}=(await this.logCtx([...r,t],C.STATEMENT,!0)).for(this.statement);return n.info(`Running statement ${e} with args ${i}`),this.repo.statement(e,...i)}async create(e,r,...i){const{log:n,ctxArgs:s}=(await this.logCtx([...i,e],d.CREATE,!0)).for(this.create);n.info("CONTRACT CREATE, "+s),"string"==typeof r&&(r=this.deserialize(r)),n.info("Creating model: "+JSON.stringify(r));const a=this.getTransientData(e);return n.info("Merging transient data..."),r=t.merge(r,a,this.clazz),this.repo.create(r,...s)}async read(t,e,...r){const{log:i,ctxArgs:n}=(await this.logCtx([...r,t],d.READ,!0)).for(this.create);return i.info(`reading entry with pk ${e} `),this.repo.read(e,...n)}getTransientData(t){const e=t.stub.getTransient();let r={};return e.has(this.repo.tableName)&&(r=JSON.parse(e.get(this.repo.tableName)?.toString("utf8"))),r}async update(e,r,...i){const{log:n,ctxArgs:s}=(await this.logCtx([...i,e],d.UPDATE,!0)).for(this.update);"string"==typeof r&&(r=this.deserialize(r)),n.info("Updating model: "+JSON.stringify(r));const a=this.getTransientData(e);return n.info("Merging transient data..."),r=t.merge(r,a,this.clazz),this.repo.update(r,...s)}async delete(t,e,...r){const{log:i,ctxArgs:n}=(await this.logCtx([...r,t],d.DELETE,!0)).for(this.delete);return i.info(`deleting entry with pk ${e} `),this.repo.delete(e+"",...n)}async deleteAll(t,e,...r){const{ctxArgs:i}=(await this.logCtx([...r,t],g.DELETE_ALL,!0)).for(this.deleteAll);return"string"==typeof e&&(e=JSON.parse(e)),this.repo.deleteAll(e,...i)}async readAll(t,e,...r){const{ctxArgs:i}=(await this.logCtx([...r,t],g.READ_ALL,!0)).for(this.create);return"string"==typeof e&&(e=JSON.parse(e)),this.repo.readAll(e,...i)}async updateAll(t,e,...r){const{log:i,ctxArgs:n}=(await this.logCtx([...r,t],g.UPDATE_ALL,!0)).for(this.updateAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`updating ${e.length} entries to the table`),this.repo.updateAll(e,...n)}async query(t,e,r,i=Z.ASC,n,s,...a){const{ctxArgs:o}=(await this.logCtx([...a,t],C.QUERY,!0)).for(this.create);return this.repo.query(e,r,i,n,s,...o)}async raw(t,e,r,...i){const{ctxArgs:n}=(await this.logCtx([...i,t],"raw",!0)).for(this.raw);return Ut.adapter.raw(e,r,...n)}serialize(t){return Ut.serializer.serialize(t)}deserialize(t){return Ut.serializer.deserialize(t)}async init(t){const{log:e,ctxArgs:r}=(await this.logCtx([t],C.INITIALIZATION,!0)).for(this.init);e.info(`Running contract ${this.getName()} initialization...`),this.initialized=!0,e.info("Contract initialization completed.")}async healthcheck(t){const{log:e}=(await this.logCtx([t],"healthcheck",!0)).for(this.healthcheck);return e.info(`Running Healthcheck: ${this.initialized}...`),{healthcheck:this.initialized}}async createAll(t,e,...r){const{log:i,ctxArgs:n}=(await this.logCtx([...r,t],g.CREATE_ALL,!0)).for(this.createAll);return"string"==typeof e&&(e=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t))),i.info(`adding ${e.length} entries to the table`),this.repo.createAll(e,...n)}logCtx(t,e,r=!1){const i=t.pop();if(!i||!i.stub)throw new zt("No valid context provided...");const n=Ut.adapter.logCtx([this.clazz,...t],e,r,i);function s(t){return t.ctxArgs.shift(),t}return n instanceof Promise?n.then(s):s(n)}}class Vt extends Ut{constructor(t,e){super(t,e)}async create(t,e){return this.serialize(await super.create(t,e))}async read(t,e){return this.serialize(await super.read(t,e))}async update(t,e){return this.serialize(await super.update(t,e))}async delete(t,e){return this.serialize(await super.delete(t,e))}async deleteAll(t,e){const r=JSON.parse(e);return JSON.stringify((await super.deleteAll(t,r)).map(t=>this.serialize(t)))}async readAll(t,e){const r=JSON.parse(e);return JSON.stringify((await super.readAll(t,r)).map(t=>this.serialize(t)))}async updateAll(t,e){const r=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t));return JSON.stringify((await super.updateAll(t,r)).map(t=>this.serialize(t)))}async statement(t,e,r){try{r=JSON.parse(r)}catch(t){throw new m("Invalid args: "+t)}if(!Array.isArray(r))throw new m(`Invalid args: ${JSON.stringify(r)}. must be an array`);return JSON.stringify(await super.statement(t,e,...r))}async listBy(t,e,r){return JSON.stringify(await super.listBy(t,e,r))}async paginateBy(t,e,r,i){try{i=JSON.parse(i)}catch(t){throw new m("Failed to deserialize paginateBy reference: "+t)}return JSON.stringify(await super.paginateBy(t,e,r,i))}async findOneBy(t,e,r){return JSON.stringify(await super.findOneBy(t,e,r))}async query(t,e,r,i,n,s){let a;try{a=z.from(JSON.parse(e))}catch(t){throw new m("Invalid condition: "+t)}return JSON.stringify(await super.query(t,a,r,i,n,s))}async init(t){await super.init(t)}async healthcheck(t){return JSON.stringify(await super.healthcheck(t))}async createAll(t,e){const r=JSON.parse(e).map(t=>this.deserialize(t)).map(t=>new this.clazz(t)),i=await super.createAll(t,r);return JSON.stringify(i.map(t=>this.serialize(t)))}}wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"create",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"read",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"update",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"delete",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"deleteAll",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"readAll",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"updateAll",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String,String]),ft("design:returntype",Promise)],Vt.prototype,"statement",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String,String]),ft("design:returntype",Promise)],Vt.prototype,"listBy",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String,String,String]),ft("design:returntype",Promise)],Vt.prototype,"paginateBy",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String,String]),ft("design:returntype",Promise)],Vt.prototype,"findOneBy",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Vt.prototype,"init",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Vt.prototype,"healthcheck",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Vt.prototype,"createAll",null);let Qt=class extends K{constructor(t){super(t)}};wt([Y({type:String}),ft("design:type",String)],Qt.prototype,"name",void 0),wt([M(),n(),ft("design:type",String)],Qt.prototype,"owner",void 0),wt([M(),n(),ft("design:type",String)],Qt.prototype,"symbol",void 0),wt([M(),n(),ft("design:type",Number)],Qt.prototype,"decimals",void 0),Qt=wt([tt("erc20_tokens"),s(),ft("design:paramtypes",[Object])],Qt);let Ht=class extends K{constructor(t){super(t)}};wt([Y({type:String}),ft("design:type",String)],Ht.prototype,"id",void 0),wt([M(),n(),ft("design:type",String)],Ht.prototype,"token",void 0),wt([M(),n(),ft("design:type",Number)],Ht.prototype,"balance",void 0),wt([M(),ft("design:type",String)],Ht.prototype,"captive",void 0),Ht=wt([tt("erc20_wallets"),s(),ft("design:paramtypes",[Object])],Ht);let Yt=class extends K{constructor(t){super(t)}};wt([Y({type:String}),M(),n(),ft("design:type",String)],Yt.prototype,"owner",void 0),wt([M(),n(),ft("design:type",String)],Yt.prototype,"spender",void 0),wt([M(),n(),ft("design:type",Number)],Yt.prototype,"value",void 0),Yt=wt([tt("erc20_allowances"),s(),ft("design:paramtypes",[Object])],Yt);class Kt extends Ut{constructor(t){super(t,Ht),Kt.adapter=Kt.adapter||new It,this.walletRepository=At.forModel(Ht,Kt.adapter.alias),this.tokenRepository=At.forModel(Qt,Kt.adapter.alias),this.allowanceRepository=At.forModel(Yt,Kt.adapter.alias)}async TokenName(t){const{ctx:e}=await this.logCtx([t],this.TokenName);await this.CheckInitialized(e);const r=this.tokenRepository.select();return(await r.execute(e))[0].name}async Symbol(t){const{ctx:e}=await this.logCtx([t],this.TokenName);await this.CheckInitialized(e);const r=this.tokenRepository.select();return(await r.execute(e))[0].symbol}async Decimals(t){const{ctx:e}=await this.logCtx([t],this.TokenName);await this.CheckInitialized(e);const r=this.tokenRepository.select();return(await r.execute(e))[0].decimals}async TotalSupply(t){const{ctx:e}=await this.logCtx([t],this.TokenName);await this.CheckInitialized(e);const r=this.walletRepository.select(),i=await r.execute(e);if(0==i.length)throw new w(`The token ${this.getName()} does not exist`);let n=0;return i.forEach(t=>{n+=t.balance}),n}async BalanceOf(t,e){const{ctx:r}=await this.logCtx([t],this.TokenName);return await this.CheckInitialized(r),(await this.walletRepository.read(e,r)).balance}async Transfer(t,e,r){const{ctx:i}=await this.logCtx([t],this.Transfer);await this.CheckInitialized(i);const n=i.identity.getID();if(!await this._transfer(n,e,r,i))throw new y("Failed to transfer");return!0}async TransferFrom(t,e,r,i){const{ctx:n}=await this.logCtx([t],this.BurnFrom);await this.CheckInitialized(n);const s=n.identity.getID(),a=await this._getAllowance(e,s,n);if(!a||0>a.value)throw new Et(`spender ${s} has no allowance from ${e}`);const o=a.value;if(i>o)throw new Pt("The spender does not have enough allowance to spend.");const c=Mt(o,i),l=Object.assign({},a,{value:c});if(await this.allowanceRepository.update(l,n),!await this._transfer(e,r,i,n))throw new y("Failed to transfer");return!0}async _transfer(t,e,r,i){const n=i.logger;if(t===e)throw new L("cannot transfer to and from same client account");if(0>r)throw new Pt("transfer amount cannot be negative");const s=await this.walletRepository.read(t,i),a=s.balance;if(r>a)throw new Pt(`client account ${t} has insufficient funds.`);let o,c=!1;try{o=await this.walletRepository.read(e,i)}catch(t){if(!(t instanceof h))throw new y(t);if(404!==t.code)throw new y(t.message);o=new Ht({id:e,balance:0,token:await this.TokenName(i)}),c=!0}const l=o.balance,u=Mt(a,r),p=Jt(l,r),d=Object.assign({},s,{balance:u});await this.walletRepository.update(d,i);const g=Object.assign({},o,{balance:p});c?await this.walletRepository.create(g,i):await this.walletRepository.update(g,i);const w={from:t,to:e,value:r};return this.repo.refresh(Qt,Dt.TRANSFER,"",w,i).catch(t=>n.error("Failed to notify transfer: "+t)),!0}async Approve(t,e,r){const{ctx:i,ctxArgs:n}=await this.logCtx([t],this.Approve);await this.CheckInitialized(i);const s=i.identity.getID();let a=await this._getAllowance(s,e,i);if((await this.walletRepository.read(s,...n)).balance<r)throw new Pt(`client account ${s} has insufficient funds.`);a?(a.value=r,await this.allowanceRepository.update(a,...n)):(a=new Yt({owner:s,spender:e,value:r}),await this.allowanceRepository.create(a,...n));const o={owner:s,spender:e,value:r};return this.repo.refresh(Qt,Dt.APPROVAL,"",o,i),!0}async Allowance(t,e,r){const{ctx:i}=await this.logCtx([t],this.Allowance);await this.CheckInitialized(i);const n=await this._getAllowance(e,r,i);if(!n)throw new Et(`spender ${r} has no allowance from ${e}`);return n.value}async _getAllowance(t,e,r){const i=z.and(z.attribute("owner").eq(t),z.attribute("spender").eq(e)),n=await this.allowanceRepository.select().where(i).execute(r);return n?.[0]}async Initialize(t,e){const{ctx:r}=await this.logCtx([t],this.Initialize);if((await this.tokenRepository.select().execute(r)).length>0)throw new L("contract options are already set, client is not authorized to change them");return e.owner=r.identity.getID(),await this.tokenRepository.create(e,r),!0}async CheckInitialized(t){const{ctx:e}=await this.logCtx([t],this.CheckInitialized);if(0==(await this.tokenRepository.select().execute(e)).length)throw new $t("contract options need to be set before calling any function, call Initialize() to initialize contract")}async Mint(t,e){const{ctx:r}=await this.logCtx([t],this.Mint);await this.CheckInitialized(r);const i=r.identity.getID();if(0>=e)throw new A("mint amount must be a positive integer");let n;try{n=await this.walletRepository.read(i,r);const t=Jt(n.balance,e),s=Object.assign({},n,{balance:t});await this.walletRepository.update(s,r)}catch(n){if(!(n instanceof h))throw new y(n);if(404!==n.code)throw new y(n.message);{const n=new Ht({id:i,balance:e,token:await this.TokenName(t)});await this.walletRepository.create(n,r)}}const s={from:"0x0",to:i,value:e};this.repo.ObserverHandler().updateObservers(Qt,Dt.TRANSFER,"",s,r)}async Burn(t,e){const{log:r,ctx:i}=await this.logCtx([t],this.Burn);await this.CheckInitialized(i);const n=i.identity.getID(),s=await this.walletRepository.read(n,i),a=s.balance;if(e>a)throw new Pt("Minter has insufficient funds.");const o=Mt(a,e),c=Object.assign({},s,{balance:o});await this.walletRepository.update(c,i),r.info(e+" tokens were burned");const l={from:n,to:"0x0",value:e};this.repo.ObserverHandler().updateObservers(Qt,Dt.TRANSFER,"",l,i)}async BurnFrom(t,e,r){const{log:i,ctx:n}=await this.logCtx([t],this.BurnFrom);await this.CheckInitialized(n);const s=await this.walletRepository.read(e,n),a=s.balance;if(r>a)throw new Pt(e+" has insufficient funds.");const o=Mt(a,r),c=Object.assign({},s,{balance:o});await this.walletRepository.update(c,n),i.info(`${r} tokens were burned from ${e}`);const l={from:e,to:"0x0",value:r};this.repo.ObserverHandler().updateObservers(Qt,Dt.TRANSFER,"",l,n)}async ClientAccountBalance(t){const{ctx:e}=await this.logCtx([t],this.TokenName);await this.CheckInitialized(e);const r=e.identity.getID(),i=await this.walletRepository.read(r,e);if(!i)throw new Pt(`The account ${r} does not exist`);return i.balance}async ClientAccountID(t){const{ctx:e}=await this.logCtx([t],this.ClientAccountID);return await this.CheckInitialized(e),e.identity.getID()}}wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"TokenName",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"Symbol",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"Decimals",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"TotalSupply",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String]),ft("design:returntype",Promise)],Kt.prototype,"BalanceOf",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String,Number]),ft("design:returntype",Promise)],Kt.prototype,"Transfer",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String,String,Number]),ft("design:returntype",Promise)],Kt.prototype,"TransferFrom",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String,Number]),ft("design:returntype",Promise)],Kt.prototype,"Approve",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt,String,String]),ft("design:returntype",Promise)],Kt.prototype,"Allowance",null),wt([ut(),ft("design:type",Function),ft("design:paramtypes",[pt,Qt]),ft("design:returntype",Promise)],Kt.prototype,"Initialize",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"CheckInitialized",null),wt([qt(),ut(),ft("design:type",Function),ft("design:paramtypes",[pt,Number]),ft("design:returntype",Promise)],Kt.prototype,"Mint",null),wt([qt(),ut(),ft("design:type",Function),ft("design:paramtypes",[pt,Number]),ft("design:returntype",Promise)],Kt.prototype,"Burn",null),wt([qt(),ut(),ft("design:type",Function),ft("design:paramtypes",[pt,String,Number]),ft("design:returntype",Promise)],Kt.prototype,"BurnFrom",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"ClientAccountBalance",null),wt([ut(!1),ft("design:type",Function),ft("design:paramtypes",[pt]),ft("design:returntype",Promise)],Kt.prototype,"ClientAccountID",null);const Xt=[Kt];class Gt extends gt{constructor(t,e,r){super(t,e),r?(this.logger=r.logging.getLogger(t),r.logging.setLevel(e?.level||dt.getConfig().level)):this.logger=new gt(t,e)}log(t,e,r){if(ht[this.config("level")]<ht[t])return;let i;switch(t){case yt.benchmark:i=this.logger.verbose;break;case yt.info:i=this.logger.info;break;case yt.verbose:i=this.logger.verbose;break;case yt.debug:i=this.logger.debug;break;case yt.error:i=this.logger.error;break;case yt.trace:i=this.logger.trace;break;case yt.warn:i=this.logger.warn;break;case yt.silly:i=this.logger.silly;break;default:throw new y("Invalid log level")}i.call(this.logger,this.createLog(t,e,r))}}dt.setFactory((t,e,r)=>new Gt(t||Gt.name,e||{},r));const Wt="##VERSION##",Zt="##PACKAGE##";a.registerLibrary(Zt,Wt);export{Gt as ContractLogger,It as FabricContractAdapter,St as FabricContractContext,Nt as FabricContractPaginator,At as FabricContractRepository,vt as FabricContractRepositoryObservableHandler,Ut as FabricCrudContract,Ct as FabricStatement,Zt as PACKAGE_NAME,Vt as SerializedCrudContract,Wt as VERSION,Xt as contracts,Tt as createdByOnFabricCreateUpdate};
|
|
1
|
+
import{Repository as t,PreparedStatementKeys as e,PersistenceKeys as r,Paginator as i,pk as s,column as n,table as a,BaseModel as o,Sequence as c,Context as l,oneToOne as d,Cascade as h,index as u,normalizeImport as p,AuthorizationError as g,createdAt as f,updatedAt as m,createdBy as y,updatedBy as w,UnsupportedError as b,ClientBasedService as C,DefaultAdapterFlags as A,Statement as v,QueryClause as S,Adapter as E,QueryError as x,PagingError as N,MigrationError as T,ObserverError as I,ForbiddenError as O,ConnectionError as $,Dispatch as R}from"@decaf-ts/core";import{Model as F,required as k,model as B,JSONSerializer as P,ModelKeys as _,stringFormat as j,minlength as K,min as L}from"@decaf-ts/decorator-validation";import{OperationKeys as z,enforceDBDecorators as H,reduceErrorsToPrint as M,ValidationError as U,SerializationError as Y,InternalError as G,BaseError as V,ConflictError as J,NotFoundError as q,version as X,DBKeys as W,readonly as Q,onCreate as Z,onUpdate as tt,transient as et,onRead as rt,onDelete as it,BulkCrudOperationKeys as st,BadRequestError as nt}from"@decaf-ts/db-decorators";import{CouchDBKeys as at}from"@decaf-ts/for-couchdb";import{__decorate as ot,__metadata as ct}from"tslib";import{Metadata as lt,description as dt,uses as ht,Decoration as ut,apply as pt,propMetadata as gt,metadata as ft}from"@decaf-ts/decoration";import mt from"fabric-ca-client";import{MiniLogger as yt,isBrowser as wt,LoggedClass as bt,Logging as Ct,toCamelCase as At,debug as vt,final as St}from"@decaf-ts/logging";import{signers as Et,connect as xt}from"@hyperledger/fabric-gateway";import{User as Nt}from"fabric-common";import Tt,{X509Certificate as It}from"crypto";import*as Ot from"@peculiar/x509";import{Crypto as $t}from"@peculiar/webcrypto";import*as Rt from"@grpc/grpc-js";import{Client as Dt}from"@grpc/grpc-js";import Ft from"pkcs11js";import kt from"fs";import Bt from"path";import{p256 as Pt}from"@noble/curves/nist";class _t extends t{constructor(t,e){super(t,e),this._overrides=Object.assign({},super._overrides,{ignoreValidation:!0,ignoreHandlers:!0,allowRawStatements:!1,forcePrepareSimpleQueries:!0,forcePrepareComplexQueries:!0,allowGenerationOverride:!1})}async paginateBy(t,r,i={offset:1,limit:10},...s){const{log:n,ctxArgs:a}=(await this.logCtx(s,e.PAGE_BY,!0)).for(this.paginateBy);return n.verbose(`paginating ${F.tableName(this.class)} with page size ${i.limit}`),this.statement(this.paginateBy.name,t,r,{limit:i.limit,offset:i.offset,bookmark:i.bookmark},...a)}async listBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${F.tableName(this.class)} by ${t} ${r}`),await this.statement(this.listBy.name,t,r,...n)}async findBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding all ${F.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findBy.name,t,r,...n)}async findOneBy(t,r,...i){const{log:s,ctxArgs:n}=(await this.logCtx(i,e.FIND_ONE_BY,!0)).for(this.findOneBy);return s.verbose(`finding One ${F.tableName(this.class)} with ${t} ${r}`),await this.statement(this.findOneBy.name,t,r,...n)}async statement(t,...e){const{log:s,ctx:n,ctxArgs:a}=(await this.logCtx(e,r.STATEMENT,!0)).for(this.statement);s.verbose("Executing prepared statement "+t);const o=a.slice(0,-1),c=JSON.parse(this.adapter.decode(await this.adapter.evaluateTransaction(n,r.STATEMENT,[t,JSON.stringify(o)],void 0,void 0,this.class.name)));return Array.isArray(c)?c.map(t=>t[at.TABLE]&&t[at.TABLE]===F.tableName(this.class)?new this.class(t):t):c[at.TABLE]&&c[at.TABLE]===F.tableName(this.class)?new this.class(c):i.isSerializedPage(c)?Object.assign(c,{data:c.data.map(t=>new this.class(t))}):c}async create(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.create);i.debug(`Creating new ${this.class.name} in table ${F.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,o,...s),this.adapter.revert(n,this.class,a,o,r)}async update(t,...e){const{ctxArgs:r,log:i,ctx:s}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,s);return i.debug(`updating ${this.class.name} in table ${F.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,o,...r),this.adapter.revert(n,this.class,a,o,s)}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:i}=(await this.logCtx(e,z.CREATE,!0)).for(this.createAllPrefix),s=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(!t.length)return[t,...i];if(t=await Promise.all(t.map(async t=>(t=new this.class(t),s||await H(this,r,t,z.CREATE,z.ON),t))),!n){const e=r.get("ignoredValidationProperties")||[],i=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),s=M(i);if(s)throw new U(s)}return[t,...i]}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.createAll);i.debug(`Creating ${t.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);const c=n.map(t=>t.transient);return o=await this.adapter.createAll(this.class,a,o,c,...s),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAll(t,...e){const{ctx:r,log:i,ctxArgs:s}=this.logCtx(e,this.updateAll);i.debug(`Updating ${t.length} new ${this.class.name} in table ${F.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),n.map(t=>t.transient),...s)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}}let jt=class extends o{constructor(t){super(t)}};ot([s({type:String}),ct("design:type",String)],jt.prototype,"name",void 0),ot([n(),k(),ct("design:type",String)],jt.prototype,"owner",void 0),ot([n(),k(),ct("design:type",String)],jt.prototype,"symbol",void 0),ot([n(),k(),ct("design:type",Number)],jt.prototype,"decimals",void 0),jt=ot([a("erc20_tokens"),B(),ct("design:paramtypes",[Object])],jt);let Kt=class extends o{constructor(t){super(t)}};ot([s({type:String}),ct("design:type",String)],Kt.prototype,"id",void 0),ot([n(),k(),ct("design:type",String)],Kt.prototype,"token",void 0),ot([n(),k(),ct("design:type",Number)],Kt.prototype,"balance",void 0),ot([n(),ct("design:type",String)],Kt.prototype,"captive",void 0),Kt=ot([a("erc20_wallets"),B(),ct("design:paramtypes",[Object])],Kt);let Lt=class extends o{constructor(t){super(t)}};ot([s({type:String}),n(),k(),ct("design:type",String)],Lt.prototype,"owner",void 0),ot([n(),k(),ct("design:type",String)],Lt.prototype,"spender",void 0),ot([n(),k(),ct("design:type",Number)],Lt.prototype,"value",void 0),Lt=ot([a("erc20_allowances"),B(),ct("design:paramtypes",[Object])],Lt);class zt extends P{constructor(){super()}preSerialize(t,e){const r=Object.assign({},t);let i=lt.modelName(t.constructor);if(!i||"Object"===i){if(!e)throw new Y("Could not find metadata for "+t.constructor.name);i=e}return r[_.ANCHOR]=i,r}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return F.build(e,r)}serialize(t,e){return JSON.stringify(this.preSerialize(t,e))}}class Ht extends _t{static{this.serializer=new zt}static{this.decoder=new TextDecoder("utf8")}async updateObservers(t,e,r,...i){if(!this.observerHandler)throw new G("ObserverHandler not initialized. Did you register any observables?");const{log:s,ctxArgs:n}=this.logCtx(i,this.updateObservers);let a;s.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),t="string"==typeof t?F.get(t):t,a=void 0===r?void 0:Array.isArray(r)?r.map(e=>c.parseValue(F.sequenceFor(t).type,e)):c.parseValue(F.sequenceFor(t).type,r),await this.observerHandler.updateObservers(t,e,a,...n)}decode(t){return Ht.decoder.decode(t)}constructor(t){super(t,Kt),this.serializer=Ht.serializer}async tokenName(...t){const{ctx:e}=(await this.logCtx(t,"tokenName",!0)).for(this.tokenName),r=await this.adapter.evaluateTransaction(e,"TokenName");return this.decode(r)}async symbol(...t){const{ctx:e}=(await this.logCtx(t,"symbol",!0)).for(this.symbol),r=await this.adapter.evaluateTransaction(e,"Symbol");return this.decode(r)}async decimals(...t){const{ctx:e}=(await this.logCtx(t,"decimals",!0)).for(this.decimals),r=await this.adapter.evaluateTransaction(e,"Decimals");return Number(this.decode(r))}async totalSupply(...t){const{ctx:e}=(await this.logCtx(t,"totalSupply",!0)).for(this.totalSupply),r=await this.adapter.evaluateTransaction(e,"TotalSupply");return Number(this.decode(r))}async balanceOf(t,...e){const{ctx:r}=(await this.logCtx(e,"balance",!0)).for(this.balanceOf),i=await this.adapter.evaluateTransaction(r,"BalanceOf",[t]);return Number(this.decode(i))}async transfer(t,e,...r){const{ctx:i}=(await this.logCtx(r,"transfer",!0)).for(this.transfer),s=await this.adapter.submitTransaction(i,"Transfer",[t,e.toString()]);return"true"===this.decode(s)}async transferFrom(t,e,r){const i=await l.args("transferFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:s}=this.logCtx(i.args,this.transferFrom),n=await this.adapter.submitTransaction(s,"TransferFrom",[t,e,r.toString()]);return"true"===this.decode(n)}async approve(t,e){const r=await l.args("approve",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.approve),s=await this.adapter.submitTransaction(i,"Approve",[t,e.toString()]);return"true"===this.decode(s)}async allowance(t,e){const r=await l.args("allowance",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.allowance),s=await this.adapter.submitTransaction(i,"Allowance",[t,e]);return Number(this.decode(s))}async initialize(t){const e=await l.args("initialize",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.initialize),i=await this.adapter.submitTransaction(r,"Initialize",[Ht.serializer.serialize(t)]);return"true"===this.decode(i)}async checkInitialized(){const t=await l.args("checkInitialized",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.checkInitialized);await this.adapter.evaluateTransaction(e,"CheckInitialized")}async mint(t){const e=await l.args("mint",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.mint);await this.adapter.submitTransaction(r,"Mint",[t.toString()])}async burn(t){const e=await l.args("burn",this.class,[],this.adapter,this._overrides||{}),{ctx:r}=this.logCtx(e.args,this.burn);await this.adapter.submitTransaction(r,"Burn",[t.toString()])}async burnFrom(t,e){const r=await l.args("burnFrom",this.class,[],this.adapter,this._overrides||{}),{ctx:i}=this.logCtx(r.args,this.burnFrom);await this.adapter.submitTransaction(i,"BurnFrom",[t,e.toString()])}async clientAccountBalance(){const t=await l.args("accountBalance",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountBalance),r=await this.adapter.evaluateTransaction(e,"ClientAccountBalance");return Number(this.decode(r))}async clientAccountID(){const t=await l.args("accountId",this.class,[],this.adapter,this._overrides||{}),{ctx:e}=this.logCtx(t.args,this.clientAccountID),r=await this.adapter.evaluateTransaction(e,"ClientAccountID");return this.decode(r)}}function Mt(t,e,r){return[...t.map(t=>t===at.TABLE?"table":t),...r||[],...e?[e]:[],"index"].join(lt.splitter)}function Ut(t,e,r,i){const s=Mt(e,r,i);let n=[...e,...i||[]];r&&(n=n.reduce((t,e)=>{const i={};return i[e]=r,t.push(i),t},[]));const a={index:{fields:n},name:s,ddoc:s,type:"json"};t[s]=a}function Yt(t,e){const r=Mt([at.TABLE]),i=e||{};i[r]={index:{fields:[at.TABLE]},name:r,ddoc:r,type:"json"};const s={},n=F.indexes(t);for(const t of Object.keys(n))for(const[,e]of Object.entries(n[t])){const r=e.directions,i=e.compositions,n=[t,at.TABLE];Ut(s,n),i&&i.length&&Ut(s,n,void 0,i),r&&r.length&&r.forEach(t=>{Ut(s,n,t),i&&i.length&&Ut(s,n,t,i)})}return Object.entries(s).forEach(([t,e])=>{i[t]=e}),Object.values(s)}function Gt(t){const e=require("path"),r=require(e.join(process.cwd(),t.parentPath,t.name));return Object.values(r).filter(t=>{try{return new t instanceof F}catch(t){return!1}})}async function Vt(...t){const e=require("fs");require("path");const r=[];for(const i of t){const t=e.readdirSync(i,{withFileTypes:!0,recursive:!0}).filter(t=>t.isFile()&&t.name.endsWith("js"));for(const e of t)r.push(...Gt(e))}return r}function Jt(t,e=process.cwd()){const r=require("fs"),i=require("path");function s(t){const e=i.dirname(t);if(r.existsSync(e))return!0;s(e),r.mkdirSync(e)}t.forEach(t=>{const n=i.resolve(i.join(e,`./META-INF/statedb/couchdb/indexes/${t.name}.json`));s(n),r.writeFileSync(n,JSON.stringify(t,void 0,2))})}let qt=class extends o{constructor(t){super(t)}};var Xt,Wt;ot([dt("Unique identifier of the credentials record"),n(),s(),ct("design:type",String)],qt.prototype,"id",void 0),ot([dt("PEM-encoded X.509 certificate for the identity"),n(),k(),ct("design:type",String)],qt.prototype,"certificate",void 0),ot([dt("PEM-encoded root or intermediate certificate"),n(),k(),ct("design:type",String)],qt.prototype,"rootCertificate",void 0),ot([dt("PEM-encoded private key"),n(),k(),ct("design:type",String)],qt.prototype,"privateKey",void 0),qt=ot([B(),ct("design:paramtypes",[Object])],qt),(t=>{t.PRIVATE="private",t.SHARED="shared",t.FABRIC="fabric.",t.OWNEDBY="owned-by",t.TRANSACTION_ID="transaction-id"})(Xt||(Xt={})),(t=>{t.X509="X.509"})(Wt||(Wt={}));const Qt="hlf-fabric";let Zt=class extends o{constructor(t){super(t),this.type=Wt.X509}};ot([dt("Unique identifier of the identity"),s(),ct("design:type",String)],Zt.prototype,"id",void 0),ot([d(qt,{update:h.CASCADE,delete:h.CASCADE}),ct("design:type",qt)],Zt.prototype,"credentials",void 0),ot([n(),k(),u(),ct("design:type",String)],Zt.prototype,"mspId",void 0),ot([n(),k(),ct("design:type",String)],Zt.prototype,"type",void 0),Zt=ot([B(),ct("design:paramtypes",[Object])],Zt);class te{static{this.logger=new yt(te.name)}constructor(){}static async contentOfLoadFile(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}static async readFile(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}static async getCAUser(t,e,r,i,s){this.logger.debug(j("Creating CA {0} user {1} with certificate {2}",i,t,r));const n=new Nt(t),a=s?.hsm?{software:!1,lib:s.hsm.library,slot:s.hsm.slot,label:s.hsm.tokenLabel,pin:s.hsm.pin+""}:void 0,o=this.getCryptoSuite(a);n.setCryptoSuite(o);const c=s?.hsm?await this.getHSMEnrollmentKey(o,r,s.hsm):this.getSoftwareEnrollmentKey(o,e);return await n.setEnrollment(c,r,i),n}static getCryptoSuite(t){return t?(te.cryptoSuite||(te.cryptoSuite=Nt.newCryptoSuite(t)),te.cryptoSuite):Nt.newCryptoSuite()}static getSoftwareEnrollmentKey(t,e){if(!e)throw Error("Private key must be provided when HSM configuration is not supplied");return t.createKeyFromRaw(e)}static async getHSMEnrollmentKey(t,e,r){const i=r.keyIdHex&&r.keyIdHex.trim().length>0?Buffer.from(r.keyIdHex,"hex"):await this.getCertificateSKI(e),s=await t.getKey(i);if(!s||"function"==typeof s.isPrivate&&!s.isPrivate())throw Error("Unable to resolve private key from HSM");return s}static async getCertificateSKI(t){const e=new It(t).publicKey.export({format:"jwk"}),r=Buffer.from([4]),i=Buffer.from(e.x||"","base64url"),s=Buffer.from(e.y||"","base64url");return Tt.createHash("sha256").update(Buffer.concat([r,i,s])).digest()}static async getIdentity(t,e){const r=await this.contentOfLoadFile(e,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)});return{mspId:t,credentials:r}}static async getFirstDirFileName(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}static async getFirstDirFileNameContent(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}static async getFileContent(t){const{promises:e}=await p(import("fs"));return(await e.readFile(t)).toString()}static async getSigner(t){const e=await this.contentOfLoadFile(t,async t=>{const{promises:e}=await p(import("fs")),r=await this.getFirstDirFileName(t);return await e.readFile(r)}),r=await this.extractPrivateKey(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Et.newPrivateKeySigner(i)}static async extractPrivateKey(t){let e;if(globalThis.window&&globalThis.window.Crypto)e=globalThis.Crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}}const ee=new $t;var re,ie,se,ne,ae;Ot.cryptoProvider.set(ee),(t=>{t.BASE2="01",t.BASE8="01234567",t.BASE11="0123456789a",t.BASE16="0123456789abcdef",t.BASE32="0123456789ABCDEFGHJKMNPQRSTVWXYZ",t.BASE32_Z="ybndrfg8ejkmcpqxot1uwisza345h769",t.BASE36="0123456789abcdefghijklmnopqrstuvwxyz",t.BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",t.BASE62="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t.BASE67="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~"})(re||(re={})),(t=>{t.HASH="SHA-256",t[t.ITERATIONS=1e3]="ITERATIONS",t[t.KEYLENGTH=48]="KEYLENGTH",t[t.DERIVED_IV_LENGTH=16]="DERIVED_IV_LENGTH",t[t.DERIVED_KEY_LENGTH=32]="DERIVED_KEY_LENGTH",t.ALGORYTHM="AES-GCM",t.KEY_ALGORYTHM="PBKDF2"})(ie||(ie={}));class oe{constructor(t){if(this.alphabet=t,this.baseMap=new Uint8Array(256),this.alphabet.length>=255)throw Error("Alphabet too long");for(let t=0;t<this.baseMap.length;t++)this.baseMap[t]=255;for(let e=0;e<t.length;e++){const r=t.charAt(e),i=r.charCodeAt(0);if(255!==this.baseMap[i])throw Error(r+" is ambiguous");this.baseMap[i]=e}this.base=this.alphabet.length,this.leader=this.alphabet.charAt(0),this.factor=Math.log(this.base)/Math.log(256),this.iFactor=Math.log(256)/Math.log(this.base)}encode(t){if("string"==typeof t?t=Buffer.from(t):ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t)),0===t.length)return"";let e=0,r=0,i=0;const s=t.length;for(;i!==s&&0===t[i];)i++,e++;const n=(s-i)*this.iFactor+1>>>0,a=new Uint8Array(n);for(;i!==s;){let e=t[i],s=0;for(let t=n-1;(0!==e||r>s)&&-1!==t;t--,s++)e+=256*a[t]>>>0,a[t]=e%this.base>>>0,e=e/this.base>>>0;if(0!==e)throw Error("Non-zero carry");r=s,i++}let o=n-r;for(;o!==n&&0===a[o];)o++;let c=this.leader.repeat(e);for(;n>o;++o)c+=this.alphabet.charAt(a[o]);return c}decodeUnsafe(t){if(0===t.length)return new Uint8Array(0);let e=0,r=0,i=0;for(;t[e]===this.leader;)r++,e++;const s=(t.length-e)*this.factor+1>>>0,n=new Uint8Array(s);for(;t[e];){let r=this.baseMap[t.charCodeAt(e)];if(255===r)return;let a=0;for(let t=s-1;(0!==r||i>a)&&-1!==t;t--,a++)r+=this.base*n[t]>>>0,n[t]=r%256>>>0,r=r/256>>>0;if(0!==r)throw Error("Non-zero carry");i=a,e++}let a=s-i;for(;a!==s&&0===n[a];)a++;const o=new Uint8Array(r+(s-a));let c=r;for(;a!==s;)o[c++]=n[a++];return o}decode(t){const e=this.decodeUnsafe(t);if(e)return e;throw Error("Non-base"+this.base+" character")}}class ce{static{this.b58encoder=new oe(re.BASE58)}static{this.logger=new yt(ce.name)}constructor(){}static fabricIdFromCertificate(t){this.logger.debug(j("Parsing certificate: {0}",t));const e=new Ot.X509Certificate(t),{subject:r,issuer:i}=e;return this.logger.debug(j("Certificate parsed with subject {0} and issuer {1}",r,i)),`x509::/${r.replaceAll(", ","/")}::/${i.replaceAll(", ","/")}`}static encode(t){return this.b58encoder.encode(t)}static decode(t){const e=this.b58encoder.decode(t);return(new TextDecoder).decode(e)}static stringToArrayBuffer(t){const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e}static async extractKey(t,e,r){const i=ee.subtle,s=e.toString("utf8").replace(RegExp(`-----BEGIN (${t.toUpperCase()} KEY|CERTIFICATE)-----`),"").replaceAll("\n","").replace(RegExp(`-----END (${t.toUpperCase()} KEY|CERTIFICATE)-----`),""),n=Buffer.from(s,"base64").toString("binary"),a=this.stringToArrayBuffer(n);return await i.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!0,r||["sign"])}static async extractPrivateKey(t,e){return this.extractKey("private",t,e)}static async extractPublicKey(t,e){return this.extractKey("public",t,e)}static async sign(t,e){const r=await this.extractPrivateKey(t),i=await ee.subtle.sign({name:"ECDSA",hash:"SHA-256"},r,e);return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}static async verify(t,e,r){const i=new Ot.X509Certificate(t),s=await i.publicKey.export();return e="string"==typeof e?Buffer.from(e,"hex"):e,r="string"==typeof r?Buffer.from(r):r,ee.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,e,r)}static async encrypt(t,e){const r=new Ot.X509Certificate(t),i=await r.publicKey.export();e="string"==typeof e?Buffer.from(e):e;const s=await this.getSubtleCrypto().encrypt({name:"ECDSA"},i,e);return Array.from(new Uint8Array(s)).map(t=>t.toString(16).padStart(2,"0")).join("")}static getSubtleCrypto(){return wt()?globalThis.window.crypto.subtle:ee.subtle}static async decrypt(t,e){const r=await this.extractPrivateKey(t);return e="string"==typeof e?Buffer.from(e,"hex"):e,this.getSubtleCrypto().decrypt({name:"ECDSA"},r,e)}static async getMaster(t){const e=new TextEncoder;if(void 0===t){const r=ee.randomUUID();t=e.encode(r).buffer}return{key:await this.getSubtleCrypto().importKey("raw",t,ie.KEY_ALGORYTHM,!1,["deriveBits"]),iv:t}}static async getDerivationKey(t,e){const r=(new TextEncoder).encode(t),i=await this.getSubtleCrypto().digest("SHA-256",r),s={name:ie.KEY_ALGORYTHM,hash:ie.HASH,salt:i,iterations:ie.ITERATIONS},n=await this.getSubtleCrypto().deriveBits(s,e,8*ie.KEYLENGTH);return this.getKey(n)}static async getKey(t){const e=t.slice(0,32),r=t.slice(32);return{key:await this.getSubtleCrypto().importKey("raw",e,{name:ie.ALGORYTHM},!1,["encrypt","decrypt"]),iv:r}}static async encryptPin(t,e){const r=(new TextEncoder).encode(t);return await this.getSubtleCrypto().encrypt({name:ie.ALGORYTHM,iv:e.iv},e.key,r)}static async decryptPin(t,e){const r=new TextDecoder,i=await this.getSubtleCrypto().decrypt({name:ie.ALGORYTHM,iv:e.iv},e.key,t);return r.decode(i)}}class le extends G{constructor(t){super(t,le.name)}}class de extends G{constructor(t){super(t,de.name)}}class he extends G{constructor(t){super(t,he.name)}}class ue extends g{constructor(t){super(t,ue.name)}}class pe extends G{constructor(t){super(t,pe.name,500)}}class ge extends V{constructor(t="MISSING_PRIVATE_DATA_ERROR_MESSAGE"){super(ge.name,t,403)}}class fe extends V{constructor(t){super(fe.name,t,409)}}class me extends G{constructor(t){super(t,me.name,500)}}class ye extends G{constructor(t){super(t,ye.name,500)}}class we extends G{constructor(t){super(t,we.name,500)}}class be extends G{constructor(t){super(t,be.name,500)}}class Ce extends G{constructor(t){super(t,Ce.name,500)}}(t=>{t.PEER="peer",t.ORDERER="orderer",t.CLIENT="client",t.USER="user",t.ADMIN="admin"})(se||(se={})),(t=>{t.HFREGISTRARROLES="hf.Registrar.Roles",t.HFREGISTRARDELEGATEROLES="hf.Registrar.DelegateRoles",t.HFREGISTRARATTRIBUTES="hf.Registrar.Attributes",t.HFINTERMEDIATECA="hf.IntermediateCA",t.HFREVOKER="hf.Revoker",t.HFAFFILIATIONMGR="hf.AffiliationMgr",t.HFGENCRL="hf.GenCRL"})(ne||(ne={}));class Ae extends bt{constructor(t){te.getCryptoSuite(t.hsm?{software:!1,lib:t.hsm.library,slot:t.hsm.slot,label:t.hsm.tokenLabel,pin:t.hsm.pin+""}:void 0),super(),this.caConfig=t}async User(){if(this.user)return this.user;const{caName:t,caCert:e,caKey:r,url:i,hsm:s}=this.caConfig,n=this.log.for(this.User);n.debug(`Creating CA user for ${t} at ${i}`),n.debug("Retrieving CA certificate from "+e);const a=await te.getFirstDirFileNameContent(e);let o;if(s)n.debug(`Using HSM configuration for CA ${t} with library ${s.library}`);else{if(!r)throw new G(`Missing caKey configuration for CA ${t}. Provide a key directory or configure HSM support.`);n.debug("Retrieving CA key from "+r),o=await te.getFirstDirFileNameContent(r)}return n.debug("Loading Admin user for ca "+t),this.user=await te.getCAUser("admin",o,a,t,{hsm:s}),this.user}async CA(){if(this.ca)return this.ca;const t=this.log.for(this.CA),{url:e,tls:r,caName:i}=this.caConfig;let{trustedRoots:s,verify:n}=r;const a=s[0];t.debug(`Retrieving CA certificate from ${a}. cwd: ${process.cwd()}`);const o=await te.getFileContent(a);return t.debug(`Creating CA Client for CA ${i} under ${e}`),this.ca=new mt(e,{trustedRoots:Buffer.from(o),verify:n},i),this.ca}async Client(){if(this.client)return this.client;const t=await this.CA();return this.client=t._FabricCAServices,this.client}async Certificate(){return this.certificateService||(this.certificateService=(await this.Client()).newCertificateService()),this.certificateService}async Affiliations(){return this.affiliationService||(this.affiliationService=(await this.CA()).newAffiliationService()),this.affiliationService}async Identities(){return this.identityService||(this.identityService=(await this.CA()).newIdentityService()),this.identityService}async getCertificates(t,e=!0){const r=await this.Certificate(),i=await this.User(),s=this.log.for(this.getCertificates);s.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.caConfig.caName}`);const n=(await r.getCertificates(t||{},i)).result;return s.debug(`Found ${n.certs.length} certificates: ${JSON.stringify(n)}`),e?n.certs.map(t=>t.PEM):n}async getIdentities(){const t=await this.Identities(),e=this.log.for(this.getIdentities);e.debug("Retrieving Identities under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.identities.length} Identities: ${JSON.stringify(r)}`),r.identities}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new ue(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ue(i)}}async getAffiliations(){const t=await this.Affiliations(),e=this.log.for(this.getAffiliations);e.debug("Retrieving Affiliations under CA "+this.caConfig.caName);const r=(await t.getAll(await this.User())).result;return e.debug(`Found ${r.a.length} Affiliations: ${JSON.stringify(r)}`),r}async read(t){const e=await this.CA(),r=await this.User();let i;try{i=await e.newIdentityService().getOne(t,r)}catch(e){throw new q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n){let a;const o=this.log.for(this.register);try{const{userName:c,password:l}=t,d=await this.CA(),h=await this.User(),u={enrollmentID:c,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};a=await d.register(u,h),o.info(`Registration for ${c} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return a}static identityFromEnrollment(t,e){const{certificate:r,key:i,rootCertificate:s}=t,n=Ct.for(Ae,{}).for(this.identityFromEnrollment);n.debug(`Generating Identity from certificate ${r} in msp ${e}`);const a=ce.fabricIdFromCertificate(r),o=ce.encode(a);n.debug(`Identity ${a} and encodedId ${o}`);const c=new Date;return new Zt({id:o,credentials:{id:o,certificate:r,privateKey:i.toBytes(),rootCertificate:s,createdOn:c,updatedOn:c},mspId:e,createdOn:c,updatedOn:c})}async enroll(t,e){let r;const i=this.log.for(this.enroll);try{const s=await this.CA();i.debug("Enrolling "+t);const n=await s.enroll({enrollmentID:t,enrollmentSecret:e});r=Ae.identityFromEnrollment(n,this.caConfig.caName),i.info(`Successfully enrolled ${t} under ${this.caConfig.caName} as ${r.id}`)}catch(t){throw this.parseError(t)}return r}async registerAndEnroll(t,e=!1,r="",i,s,n){const a=await this.register(t,e,r,i,s,n),{userName:o}=t;return this.enroll(o,a)}async revoke(t){const e=await this.CA(),r=await this.User(),i=await this.read(t);if(!i)throw new q("Could not find enrollment with id "+t);let s;try{s=await e.revoke({enrollmentID:i.id,reason:"User Deletation"},r)}catch(e){throw new G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}class ve extends F{constructor(){super(...arguments),this.affiliation=""}build(){const t=this.hasErrors();if(t)throw new U(t.toString());const e={enrollmentID:this.enrollmentID,enrollmentSecret:this.enrollmentSecret,role:this.role,affiliation:this.affiliation};return void 0!==this.maxEnrollments&&(e.maxEnrollments=this.maxEnrollments),this.attrs&&(e.attrs=this.attrs),e}setAffiliation(t){return this.affiliation=t,this}addAttr(t){return this.attrs=this.attrs||[],this.attrs.push(t),this}setAttrs(t){return this.attrs=t,this}setEnrollmentID(t){return this.enrollmentID=t,this}setEnrollmentSecret(t){return this.enrollmentSecret=t,this}setMaxEnrollments(t){return this.maxEnrollments=t,this}setRole(t){return this.role=t,this}}ot([k(),ct("design:type",String)],ve.prototype,"affiliation",void 0),ot([K(1),ct("design:type",Array)],ve.prototype,"attrs",void 0),ot([k(),ct("design:type",String)],ve.prototype,"enrollmentID",void 0),ot([k(),ct("design:type",String)],ve.prototype,"enrollmentSecret",void 0),ot([L(0),ct("design:type",Number)],ve.prototype,"maxEnrollments",void 0),ot([k(),ct("design:type",String)],ve.prototype,"role",void 0),(t=>{t.TRANSFER="Transfer",t.APPROVAL="Approval"})(ae||(ae={}));let Se=class extends F{constructor(t){super(t)}};ot([dt("Stores the original timestamp of creation"),n(),f(),ct("design:type",Date)],Se.prototype,"createdAt",void 0),ot([dt("Stores the timestamp of the last update"),n(),m(),ct("design:type",Date)],Se.prototype,"updatedAt",void 0),ot([dt("Stores the version of the model"),n(),X(),ct("design:type",Number)],Se.prototype,"version",void 0),Se=ot([ht(Qt),ct("design:paramtypes",[Object])],Se);let Ee=class extends Se{constructor(t){super(t)}};function xe(){return function(t,e,r){const i=r.value;return r.value=async function(...t){const r=t[0],s=r.clientIdentity.getID(),n=await this.tokenRepository.select(),a=await n.execute(r);if(0==a.length)throw new q("No tokens avaialble");if(a.length>1)throw new q("To many token available : "+a.length);if(a[0].owner!=s)throw new g(`User not authorized to run ${e} on the token`);return await i.apply(this,t)},r}}async function Ne(t,e,r,i){const{stub:s}=t,n=(await s.getCreator()).mspid;Object.defineProperty(i,r,{enumerable:!0,writable:!1,configurable:!0,value:n})}function Te(){const t=$e(Xt.OWNEDBY);return ut.for(t).define({decorator:()=>(t,e)=>pt(k(),Q(),Z(Ne),gt($e(Xt.OWNEDBY),e))(t,e),args:[]}).apply()}async function Ie(t,e,r,i){const{stub:s}=t;i[r]=s.getTxID()}function Oe(){return ut.for(Xt.TRANSACTION_ID).define({decorator:()=>(t,e)=>pt(k(),Q(),Z(Ie),tt(Ie),gt(lt.key(Xt.FABRIC,e,Xt.TRANSACTION_ID),e))(t,e),args:[]}).apply()}function $e(t){return lt.key(Xt.FABRIC+t)}ot([dt("Stores the creator"),n(),y(),ct("design:type",String)],Ee.prototype,"createdBy",void 0),ot([dt("Stores the user that last updated the model"),n(),w(),ct("design:type",String)],Ee.prototype,"updatedBy",void 0),Ee=ot([ht(Qt),ct("design:paramtypes",[Object])],Ee),F.prototype.isShared=function(){return F.isShared(this.constructor)},F.prototype.isPrivate=function(){return F.isPrivate(this.constructor)},F.prototype.segregate=function(){return F.segregate(this)},F.segregate=(t=>{if(!F.isTransient(t))return{model:t};const e=lt.validatableProperties(t.constructor),r=lt.get(t.constructor,W.TRANSIENT),i=lt.get(t.constructor,Xt.PRIVATE),s=lt.get(t.constructor,Xt.PRIVATE),n={model:{},transient:{},private:{},shared:{}},a=Object.keys(r),o=Object.keys(i),c=Object.keys(s);for(const r of e){const e=a.includes(r),i=o.includes(r),s=c.includes(r);e?(n.transient=n.transient||{},n.transient[r]=t[r],i&&(n.private=n.private||{},n.private[r]=t[r]),s&&(n.shared=n.shared||{},n.shared[r]=t[r])):(n.model=n.model||{},n.model[r]=t[r])}return n.model=F.build(n.model,t.constructor.name),n}).bind(F),F.tableName=t=>{const e=t instanceof F?t.constructor:t;return lt.get(e,r.TABLE)||(t instanceof F?t.constructor.name:t.name)},F.isPrivate=(t=>!!lt.get("function"!=typeof t?t.constructor:t,Xt.PRIVATE)).bind(F),lt.isShared=(t=>!!lt.get("function"!=typeof t?t.constructor:t,Xt.SHARED)).bind(lt);const Re=t=>`__${t.constructor.name}PrivateCollection`;async function De(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=e[0].collections,n="string"==typeof s?s:s(i),a=r.reduce((t,r,s)=>{const a="string"==typeof e[s].collections?e[s].collections:e[s].collections(i);if(a!==n)throw new b(`Segregated data collection mismatch: ${a} vs ${n}`);return t[r]=i[r],t},{}),o=new this.class(a),c=await this.override({segregated:n}).create(o,t);Object.assign(i,c)}async function Fe(t,e,r,i){if(r.length!==e.length)throw new G("Segregated data keys and metadata length mismatch");const s=e[0].collections,n="string"==typeof s?s:s(i),a=r.reduce((t,r,s)=>{const a="string"==typeof e[s].collections?e[s].collections:e[s].collections(i);if(a!==n)throw new b(`Segregated data collection mismatch: ${a} vs ${n}`);return t[r]=i[r],t},{}),o=new this.class(a),c=await this.override({segregated:n}).create(o,t);Object.assign(i,c)}async function ke(t,e,r,i,s){}async function Be(t,e,r,i){}function Pe(t,e){return(r,i)=>{const s=[];return i?(s.push(et(),(r,i)=>{if(!i){const i=lt.properties(r)||[];for(const s of i)Pe(t,e)(r,s);return r}const s=lt.key(e,i),n=r.constructor,a=lt.get(n,s)||{},o=new Set(a.collections||[]);o.add(t),a.collections=[...o],lt.set(n,s,a)},Z(De,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),rt(Fe,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),tt(ke,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()}),it(Be,{collections:t},{priority:95,group:"string"==typeof t?t:t.toString()})),pt(...s)(r,i)):(lt.properties(r)?.forEach(i=>Pe(t,e)(r,i)),ft(e,!0)(r))}}function _e(t=Re){return ut.for(Xt.PRIVATE).define({decorator:t=>Pe(t,Xt.PRIVATE),args:[t]}).apply()}function je(t){return ut.for(Xt.SHARED).define({decorator:t=>Pe(t,Xt.SHARED),args:[t]}).apply()}class Ke extends P{constructor(){super()}preSerialize(t){const e=Object.assign({},t);let r;try{r=lt.modelName(t.constructor)}catch(t){r=void 0}e[_.ANCHOR]=r||t.constructor.name;const i=function t(e){const r=this;return"object"!=typeof e?e:Array.isArray(e)?e.map(e=>t.call(r,e)):this.preSerialize.call(this,e)}.bind(this);return F.relations(t).forEach(t=>{e[t]=i(e[t])}),e}deserialize(t){const e=JSON.parse(t),r=e[_.ANCHOR];if(!r)throw Error("Could not find class reference in serialized model");return F.build(e,r)}serialize(t){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t)))}}function Le(t,e,r){const i=[t,e];return r&&i.push(r),i.join("_")}function ze(t){const e=t.split("_");return 2>e.length||e.length>3?{table:void 0,event:t,owner:void 0}:{table:e[0],event:e[1],owner:e[2]}}function He(t,e){const r=t+e;if(t!==r-e||e!==r-t)throw new le(`Addition overflow: ${t} + ${e}`);return r}function Me(t,e){const r=t-e;if(t!==r+e||e!==t-r)throw new le(`Subtraction overflow: ${t} - ${e}`);return r}function Ue(t){if(!/^\d+$/.test(t))throw new U(j("Failed to parse: {0}","string contains digits"));const e=parseInt(t);if(isNaN(e))throw new U(j("Failed to parse: {0}","string is not a parsable integer"));return e}class Ye extends P{constructor(){super()}deserialize(t,e){return JSON.parse(t)}serialize(t,e=!0){return require("json-stringify-deterministic")(require("sort-keys-recursive")(this.preSerialize(t,e)))}preSerialize(t,e=!0){const r=Object.assign({},t);let i;try{i=lt.modelName(t.constructor)}catch(t){i=void 0}function s(t){return"object"!=typeof t?t:Array.isArray(t)?t.map(s):this.preSerialize(t)}return e&&(r[_.ANCHOR]=i||t.constructor.name),F.relations(t).forEach(t=>{r[t]=s.call(this,r[t])}),r}}class Ge extends C{constructor(){super()}get rootClient(){return this.client._FabricCaServices}get user(){if(!this._user)throw new G("Fabric identity service not properly setup: missing user");return this._user}get certificates(){return this.rootClient.newCertificateService()}get affiliations(){return this.client.newAffiliationService()}get identities(){return this.client.newIdentityService()}async getUser(t,e){const r=e.logger.for(this.getUser),{caName:i,caCert:s,caKey:n,url:a,hsm:o}=t;r.info(`Creating CA user for ${i} at ${a}`),r.verbose("Retrieving CA certificate from "+s);const c=await te.getFirstDirFileNameContent(s);let l;if(o)r.debug(`Using HSM configuration for CA ${i} with library ${o.library}`);else{if(!n)throw new G(`Missing caKey configuration for CA ${i}. Provide a key directory or configure HSM support.`);r.debug("Retrieving CA key from "+n),l=await te.getFirstDirFileNameContent(n)}return r.debug("Loading Admin user for ca "+i),this._user=await te.getCAUser("admin",l,c,i,{hsm:o}),this._user}async initialize(...t){const{log:e,ctx:r}=await this.logCtx(t,this.initialize,!0),[i]=t;if(!i)throw new G("Missing Fabric CA configuration");const{url:s,tls:n,caName:a}=i;e.info(`Initializing CA Client for CA ${i.caName} at ${i.url}`);const{trustedRoots:o,verify:c}=n,l=o[0];e.debug(`Retrieving CA certificate from ${l}. cwd: ${process.cwd()}`);const d=await te.getFileContent(l);e.debug("CA Certificate: "+d.toString());const h=new mt(s,{trustedRoots:Buffer.from(d),verify:c},a),u=await this.getUser(i,r);return e.debug("CA user loaded: "+u.getName()),{config:i,client:h}}async getCertificates(t,e=!0,...r){t instanceof l?(r=[t],e=!0,t=void 0):"boolean"==typeof t?(e=t,t=void 0):"boolean"!=typeof e&&(r=[e,...r],e=!0);const{log:i}=await this.logCtx(r,this.getCertificates,!0);i.debug(`Retrieving certificates${t?" for "+t.id:""} for CA ${this.config.caName}`);const s=(await this.certificates.getCertificates(t||{},this.user)).result;return i.verbose(`Found ${s.certs.length} certificates`),i.debug(s.certs),e?s.certs.map(t=>t.PEM):s}async getIdentities(t){const e=t.logger.for(this.getIdentities);e.verbose("Retrieving Identities under CA "+this.config.caName);const r=(await this.identities.getAll(this.user)).result;return e.verbose(`Found ${r.identities.length} Identities`),e.debug(r.identities),r.identities}async getAffiliations(t){const e=t.logger.for(this.getAffiliations);e.verbose("Retrieving Affiliations under CA "+this.config.caName);const r=(await this.affiliations.getAll(this.user)).result;return e.verbose(`Found ${r.a.length} Affiliations`),e.debug(JSON.stringify(r)),r}parseError(t){const e=/.*code:\s(\d+).*?message:\s["'](.+)["']/gs.exec(t.message);if(!e)return new ue(t);const[,r,i]=e;switch(r){case"74":case"71":return new J(i);case"20":return new g(i);default:return new ue(i)}}async read(t,...e){const{log:r}=await this.logCtx(e,this.read,!0);let i;r.verbose("Retrieving identity with enrollment ID "+t);try{i=await this.identities.getOne(t,this.user)}catch(e){throw new q(`Couldn't find enrollment with id ${t}: ${e}`)}if(!i.success)throw new q(`Couldn't find enrollment with id ${t}: ${i.errors.join("\n")}`);return i.result}async register(t,e=!1,r="",i,s,n,...a){const{log:o}=await this.logCtx(a,this.register,!0);let c;try{const{userName:a,password:l}=t,d={enrollmentID:a,enrollmentSecret:l,affiliation:r,userRole:i,attrs:s,maxEnrollments:n};c=await this.client.register(d,this.user),o.info(`Registration for ${a} created with user type ${i??"Undefined Role"} ${e?"as super user":""}`)}catch(t){throw this.parseError(t)}return c}static identityFromEnrollment(t,e,r){const i=r.logger.for(this.identityFromEnrollment),{certificate:s,key:n,rootCertificate:a}=t;i.verbose(`Generating Identity from certificate ${s} in msp ${e}`);const o=ce.fabricIdFromCertificate(s),c=ce.encode(o);return i.debug(`Identity ${o} and encodedId ${c}`),new Zt({id:c,credentials:{id:c,certificate:s,privateKey:n.toBytes(),rootCertificate:a},mspId:e})}async enroll(t,e,...r){const{log:i,ctx:s}=await this.logCtx(r,this.enroll,!0);let n;try{i.debug("Enrolling "+t);const r=await this.client.enroll({enrollmentID:t,enrollmentSecret:e});n=Ge.identityFromEnrollment(r,this.config.caName,s),i.info(`Successfully enrolled ${t} under ${this.config.caName} as ${n.id}`)}catch(t){throw this.parseError(t)}return n}async registerAndEnroll(t,e=!1,r="",i,s,n,...a){const{ctx:o}=await this.logCtx(a,this.registerAndEnroll,!0),c=await this.register(t,e,r,i,s,n,o),{userName:l}=t;return this.enroll(l,c,o)}async revoke(t,...e){const{log:r}=await this.logCtx(e,this.revoke,!0);r.verbose("Revoking identity with enrollment ID "+t);const i=await this.read(t);if(!i)throw new q("Could not find enrollment with id "+t);let s;try{s=await this.client.revoke({enrollmentID:i.id,reason:"User Deletion"},this.user)}catch(e){throw new G(`Could not revoke enrollment with id ${t}: ${e}`)}if(!s.success)throw new G(`Could not revoke enrollment with id ${t}: ${s.errors.join("\n")}`);return s}}const Ve=Object.assign({evaluateTimeout:5,endorseTimeout:15,submitTimeout:5,commitTimeout:60},A),Je=new yt("fabric-fs");async function qe(t,e){return t instanceof Uint8Array||t.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms)?t:await e(t)}async function Xe(t){return"string"!=typeof t?t:await(async t=>{const{promises:e}=await p(import("fs"));return await e.readFile(t)})(t)}async function We(t,e,r,i){Je.debug(`Creating a CA ${i} user ${t} with certificate ${r}`);const s=new Nt(t),n=Nt.newCryptoSuite();s.setCryptoSuite(n);const a=n.createKeyFromRaw(e);return await s.setEnrollment(a,r,i),s}async function Qe(t,e){const r=await qe(e,async t=>{const{promises:e}=await p(import("fs")),r=await Ze(t);return await e.readFile(r)});return{mspId:t,credentials:r}}async function Ze(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path"));return r(t,(await e.readdir(t))[0])}async function tr(t){const{promises:e}=await p(import("fs")),{join:r}=await p(import("path")),i=await e.readdir(t);return(await e.readFile(r(t,i[0]))).toString()}async function er(t){const e=await qe(t,async t=>{const{promises:e}=await p(import("fs")),r=await Ze(t);return await e.readFile(r)}),r=await rr(e),i=r[Object.getOwnPropertySymbols(r)[0]];return Et.newPrivateKeySigner(i)}async function rr(t){let e;if(wt())e=globalThis.crypto.subtle;else{const t=await p(import("crypto"));e=t.subtle||t.webcrypto.subtle}if(!e)throw Error("Could not load SubtleCrypto module");const r=t.toString("utf8").replace("-----BEGIN PRIVATE KEY-----","").replaceAll("\n","").replace("-----END PRIVATE KEY-----",""),i=(t=>{const e=new ArrayBuffer(t.length),r=new Uint8Array(e);for(let e=0,i=t.length;i>e;e++)r[e]=t.charCodeAt(e);return e})(Buffer.from(r,"base64").toString("binary"));try{return await e.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"])}catch(t){throw new G(t)}}class ir{static#t=null;static#e=!1;constructor(t){if(ir.#t||(ir.#t=new Ft.PKCS11,ir.#t.load(this.findHSMPKCS11Lib(t))),!ir.#e){try{ir.#t.C_Initialize()}catch(t){if(t.code!==Ft.CKR_CRYPTOKI_ALREADY_INITIALIZED)throw t}ir.#e=!0}}findHSMPKCS11Lib(t){const e=["/usr/lib/softhsm/libsofthsm2.so","/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so","/usr/local/lib/softhsm/libsofthsm2.so","/usr/lib/libacsp-pkcs11.so","/opt/homebrew/lib/softhsm/libsofthsm2.so"];t&&e.push(t);for(const t of e)if(kt.existsSync(t))return t;throw new me("Unable to find PKCS11 library")}dispose(){ir.#t.C_Finalize()}sanitizeOptions(t){const e=Object.assign({userType:Ft.CKU_USER},t);return this.assertNotEmpty(e.label,"label"),this.assertNotEmpty(e.pin,"pin"),this.assertNotEmpty(e.identifier,"identifier"),e}assertNotEmpty(t,e){if(!t||0===t.toString().trim().length)throw Error(e+" property must be provided")}findSlotForLabel(t){const e=ir.#t.C_GetSlotList(!0);if(0===e.length)throw Error("No pkcs11 slots can be found");const r=e.find(e=>ir.#t.C_GetTokenInfo(e).label.trim()===t);if(!r)throw Error(`label ${t} cannot be found in the pkcs11 slot list`);return r}login(t,e,r){try{ir.#t.C_Login(t,e,r)}catch(t){if(t.code!==Ft.CKR_USER_ALREADY_LOGGED_IN)throw t}}findObjectInHSM(t,e,r){const i=[{type:Ft.CKA_ID,value:r},{type:Ft.CKA_CLASS,value:e},{type:Ft.CKA_KEY_TYPE,value:Ft.CKK_EC}];ir.#t.C_FindObjectsInit(t,i);const s=ir.#t.C_FindObjects(t,1)[0];if(!s)throw ir.#t.C_FindObjectsFinal(t),Error("Unable to find object in HSM with ID "+r.toString());return ir.#t.C_FindObjectsFinal(t),s}newSigner(t){const e=this.sanitizeOptions(t),r=ir.#t,i=this.findSlotForLabel(e.label),s=r.C_OpenSession(i,Ft.CKF_SERIAL_SESSION);let n;try{this.login(s,e.userType,e.pin),n=this.findObjectInHSM(s,Ft.CKO_PRIVATE_KEY,e.identifier)}catch(t){throw ir.#t.C_CloseSession(s),t}return{signer:async t=>{ir.#t.C_SignInit(s,{mechanism:Ft.CKM_ECDSA},n);const e=await ir.#t.C_SignAsync(s,Buffer.from(t),Buffer.alloc(2*Pt.Point.Fn.BYTES));return Pt.Signature.fromBytes(e,"compact").normalizeS().toBytes("der")},close:()=>{ir.#t.C_CloseSession(s)}}}assertDefined(t){if(void 0===t)throw Error("required value was undefined");return t}getUncompressedPointOnCurve(t){const e=t.export({format:"jwk"}),r=Buffer.from(this.assertDefined(e.x),"base64url"),i=Buffer.from(this.assertDefined(e.y),"base64url"),s=Buffer.from("04","hex");return Buffer.concat([s,r,i])}getSKIFromCertificatePath(t){const e=t.endsWith(".pem")?t:Bt.join(t,"cert.pem"),r=kt.readFileSync(e);return this.getSKIFromCertificate(r)}getSKIFromCertificate(t){const e=new Tt.X509Certificate(t),r=this.getUncompressedPointOnCurve(e.publicKey);return Tt.createHash("sha256").update(r).digest()}}class sr extends v{constructor(t,e){super(t,e)}squash(t){const r=super.squash(t);if(!r)return r;const{method:i,params:s,args:n}=r,{direction:a,limit:o}=s;switch(i){case e.FIND_BY:break;case e.LIST_BY:n.push(a);break;case e.PAGE_BY:n.push(a,o);break;case e.FIND_ONE_BY:break;default:throw new G("Unsupported method "+i)}return r}async executePrepared(...e){const r=t.forModel(this.fromSelector,this.adapter.alias),{method:i,args:s}=this.prepared;return r.statement(i,...s,...e)}async prepare(t){if(t=t||await this.adapter.context(r.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],i={},s={class:this.fromSelector,args:e,params:i},n=[S.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);n.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&n.push(S.SELECT,this.selectSelector.join(` ${S.AND.toLowerCase()} `)),this.orderBySelector&&(n.push(S.ORDER_BY,this.orderBySelector[0]),e.push(this.orderBySelector[1])),s.method=At(n.join(" ")),s.params=i,this.prepared=s,this}build(){throw new b("This method is only called is prepared statements are not used. If so, a dedicated implementation for the native queries used is required")}parseCondition(t,...e){throw new b("This method is only called is prepared statements are not used. Is so, a dedicated implementation for the native queries used is required")}}class nr extends i{constructor(t,e,r,i){super(t,e,r,i)}prepare(t){throw new b("Raw query access must be implemented by a subclass. only prepared statements are natively available")}page(t=1,...e){return super.page(t,...e)}}var ar;class or extends E{static{this.decoder=new TextDecoder("utf8")}static{this.serializer=new zt}static{this.log=Ct.for(or)}constructor(t,e){super(t,Qt,e),this.serializer=or.serializer}Statement(t){return new sr(this,t)}Paginator(t,e,r){return new nr(this,t,e,r)}flags(t,e,r,...i){return super.flags(t,e,r,...i)}async context(t,e,r,...i){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>F.tableName(t)):F.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let s=i.pop();void 0===s||s instanceof l||(i.push(s),s=void 0),e=s?Object.assign({},e,s.toOverrides()):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...i,s);if(s){if(!(s instanceof this.Context))return(new this.Context).accumulate({...s.cache,...n,parentContext:s});const e=s.get("operation"),i=s.get("affectedTables");return e!==t||r!==i?(new this.Context).accumulate({...s.cache,...n,parentContext:s}):s.accumulate(n)}return(new this.Context).accumulate({...Ve,...n})}decode(t){return or.decoder.decode(t)}repository(){return _t}createPrefix(t,e,r,...i){const{ctxArgs:s}=this.logCtx(i,this.createPrefix),n=F.tableName(t),a={};return a[at.TABLE]=n,Object.assign(a,r),[t,e,a,...s]}createAllPrefix(t,e,r,...i){const s=F.tableName(t);if(e.length!==r.length)throw new G("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.createAllPrefix),a=e.map((t,e)=>{const i={};return i[at.TABLE]=s,Object.assign(i,r[e]),i});return[t,e,a,...n]}updateAllPrefix(t,e,r,...i){const s=F.tableName(t);if(e.length!==r.length)throw new G("Ids and models must have the same length");const{ctxArgs:n}=this.logCtx(i,this.updateAllPrefix),a=e.map(()=>{const t={};return t[at.TABLE]=s,t});return[t,e,a,...n]}async createAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.createAll),c=F.tableName(t);a.info(`adding ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,st.CREATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new Y(t)}}async readAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=F.tableName(t);i.info(`reading ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.evaluateTransaction(s,st.READ_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new Y(t)}}async updateAll(t,e,r,...i){if(e.length!==r.length)throw new G("Ids and models must have the same length");const s=[...i],n=s.shift(),{log:a,ctx:o}=this.logCtx(s,this.updateAll),c=F.tableName(t);a.info(`updating ${e.length} entries to ${c} table`),a.verbose("pks: "+e);const l=await this.submitTransaction(o,st.UPDATE_ALL,[JSON.stringify(r.map(e=>this.serializer.serialize(e,t.name)))],n,void 0,t.name);try{return JSON.parse(this.decode(l)).map(t=>JSON.parse(t))}catch(t){throw new Y(t)}}async deleteAll(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.deleteAll),n=F.tableName(t);i.info(`deleting ${e.length} entries to ${n} table`),i.verbose("pks: "+e);const a=await this.submitTransaction(s,st.DELETE_ALL,[JSON.stringify(e)],void 0,void 0,t.name);try{return JSON.parse(this.decode(a)).map(t=>JSON.parse(t))}catch(t){throw new Y(t)}}prepare(t,...e){const{log:i}=this.logCtx(e,this.prepare),s=F.segregate(t);return t[r.METADATA]&&(i.silly("Passing along persistence metadata for "+t[r.METADATA]),Object.defineProperty(s.model,r.METADATA,{enumerable:!1,writable:!1,configurable:!0,value:t[r.METADATA]})),{record:s.model,model:s.model,id:t[F.pk(t.constructor)],transient:s.transient,private:s.private,shared:s.shared}}revert(t,e,r,i,...s){const{log:n}=this.logCtx(s,this.revert);return i&&(n.verbose("re-adding transient properties: "+Object.keys(i).join(", ")),Object.entries(i).forEach(([r,i])=>{if(r in t)throw new G(`Transient property ${r} already exists on model ${"string"==typeof e?e:e.name}. should be impossible`);t[r]=i})),new e(t)}async create(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.create),c=F.tableName(t);a.verbose(`adding entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.CREATE,[this.serializer.serialize(r,t.name)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async read(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.readAll),n=F.tableName(t);i.verbose(`reading entry from ${n} table`),i.debug("pk: "+e);const a=await this.evaluateTransaction(s,z.READ,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}updatePrefix(t,e,r,...i){const s=F.tableName(t),{ctxArgs:n}=this.logCtx(i,this.updatePrefix),a={};return a[at.TABLE]=s,Object.assign(a,r),[t,e,a,...n]}async update(t,e,r,i={},...s){const n=[...s],{log:a,ctx:o}=this.logCtx(n,this.updateAll);a.info("CLIENT UPDATE class : "+typeof t);const c=F.tableName(t);a.verbose(`updating entry to ${c} table`),a.debug("pk: "+e);const l=await this.submitTransaction(o,z.UPDATE,[this.serializer.serialize(r,t.name||t)],i,void 0,t.name);return this.serializer.deserialize(this.decode(l))}async delete(t,e,...r){const{log:i,ctx:s}=this.logCtx(r,this.delete),n=F.tableName(t);i.verbose(`deleting entry from ${n} table`),i.debug("pk: "+e);const a=await this.submitTransaction(s,z.DELETE,[e.toString()],void 0,void 0,t.name);return this.serializer.deserialize(this.decode(a))}async raw(t,e=!0,r,...i){const{log:s,ctx:n}=this.logCtx(i,this.raw),a=r.name;let o,c;s.info("Performing raw statement on table "+F.tableName(r));try{o=await this.evaluateTransaction(n,"raw",[JSON.stringify(t),e],void 0,void 0,a)}catch(t){throw this.parseError(t)}try{c=JSON.parse(this.decode(o))}catch(t){throw new Y("Failed to process result: "+t)}if(Array.isArray(c)){if(!c.length)return c;const t=c[0];return F.isModel(t)?c.map(t=>F.build(t)):c}return l=c,F.isModel(l)?F.build(l):l;var l}getClient(){return this._client||(this._client=or.getClient(this.config)),this._client}async Gateway(t){return or.getGateway(t,this.config,this.client)}getContractName(t){if(t)return t+"Contract"}async Contract(t,e){return or.getContract(await this.Gateway(t),this.config,e)}async transaction(t,e,r=!0,i,s,n,a){const o=this.log.for(this.transaction),c=await this.Gateway(t);try{const c=await this.Contract(t,this.getContractName(a));o.verbose(`${r?"Submit":"Evaluate"}ting transaction ${this.getContractName(a)||this.config.contractName}.${e}`),o.debug("args: "+(i?.map(t=>t.toString()).join("\n")||"none"));const l=r?c.submit:c.evaluate;n=n?.length?n:void 0;const d={arguments:i||[],transientData:s};return await l.call(c,e,d)}catch(t){if(10===t.code)throw Error(""+t.details[0].message);throw this.parseError(t)}finally{this.log.debug(`Closing ${this.config.mspId} gateway connection`),c.close()}}parseError(t){return or.parseError(t)}async submitTransaction(t,e,r,i,s,n){return this.transaction(t,e,!0,r,i,s,n)}async evaluateTransaction(t,e,r,i,s,n){return this.transaction(t,e,!1,r,i,s,n)}async close(){this.client&&(this.log.verbose(`Closing ${this.config.mspId} gateway client`),this.client.close())}static getContract(t,e,r){const i=this.log.for(this.getContract),s=this.getNetwork(t,e.channel);let n;try{i.debug(`Retrieving chaincode ${e.chaincodeName} contract ${r||e.contractName} from network ${e.channel}`),r=r||e.contractName,n=s.getContract(e.chaincodeName,r)}catch(t){throw this.parseError(t)}return n}static getNetwork(t,e){const r=Ct.for(this.getNetwork);let i;try{r.debug("Connecting to channel "+e),i=t.getNetwork(e)}catch(t){throw this.parseError(t)}return i}static async getGateway(t,e,r){return await this.getConnection(r||await this.getClient(e),e,t)}static getClient(t){const e=this.log.for(this.getClient);e.debug("generating TLS credentials for msp "+t.mspId);let r=t.tlsCert;if("string"==typeof r)if(r.match(/-----BEGIN (CERTIFICATE|KEY|PRIVATE KEY)-----.+?-----END \1-----$/gms))r=Buffer.from(r,"utf8");else try{r=Buffer.from(kt.readFileSync(r,"utf8"))}catch(t){throw new G(`Failed to read the tls certificate from ${r}: ${t}`)}const i=Rt.credentials.createSsl(r);return e.debug("generating Gateway Client for url "+t.peerEndpoint),new Dt(t.peerEndpoint,i,{"grpc.max_receive_message_length":1024*(t.sizeLimit||15)*1024,"grpc.max_send_message_length":1024*(t.sizeLimit||15)*1024})}static async getConnection(t,e,r){const i=Ct.for(this.getConnection);i.debug(`Retrieving Peer Identity for ${e.mspId} under ${e.certCertOrDirectoryPath}`);const s=await Qe(e.mspId,e.certCertOrDirectoryPath);i.debug("Retrieving signer key from "+e.keyCertOrDirectoryPath);let n,a=()=>{};if(e.hsm){const t=new ir(e.hsm.library),r=t.getSKIFromCertificatePath(e.certCertOrDirectoryPath),i=t.newSigner({label:e.hsm.tokenLabel,pin:e.hsm.pin+"",identifier:r});n=i.signer,a=i.close}else n=await er(e.keyCertOrDirectoryPath);const o={client:t,identity:s,signer:n,evaluateOptions:()=>({deadline:Date.now()+1e3*r.get("evaluateTimeout")}),endorseOptions:()=>({deadline:Date.now()+1e3*r.get("endorseTimeout")}),submitOptions:()=>({deadline:Date.now()+1e3*r.get("submitTimeout")}),commitStatusOptions:()=>({deadline:Date.now()+1e3*r.get("commitTimeout")})};i.debug("Connecting to "+e.mspId);const c=xt(o);return e.hsm&&(c.close=new Proxy(c.close,{apply(t,e,r){Reflect.apply(t,e,r),a()}})),c}Dispatch(){return new or._baseDispatch}static parseError(t){const e="string"==typeof t?t:t.message;return e.includes("MVCC_READ_CONFLICT")?new we(t):e.includes("ENDORSEMENT_POLICY_FAILURE")?new Ce(t):e.includes("PHANTOM_READ_CONFLICT")?new be(t):t instanceof Error&&t.code&&9===t.code?new ye(t):e.includes(q.name)?new q(t):e.includes(J.name)?new J(t):e.includes(nt.name)?new nt(t):e.includes(x.name)?new x(t):e.includes(N.name)?new N(t):e.includes(b.name)?new b(t):e.includes(T.name)?new T(t):e.includes(I.name)?new I(t):e.includes(g.name)?new g(t):e.includes(O.name)?new O(t):e.includes($.name)?new $(t):e.includes(Y.name)?new Y(t):new G(t)}}ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"create",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"read",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"update",null),ot([vt(),St(),ct("design:type",Function),ct("design:paramtypes",[Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"delete",null),ot([vt(),ct("design:type",Function),ct("design:paramtypes",[Object,"function"==typeof(ar="undefined"!=typeof D&&D)?ar:Object,Object,l]),ct("design:returntype",Promise)],or.prototype,"raw",null),or.decoration(),E.setCurrent(Qt);class cr extends R{constructor(t){super(),this.client=t,this.decoder=new TextDecoder("utf8")}async close(){this.listeningStack&&this.listeningStack.close()}parsePayload(t){const e=this.decoder.decode(t);return JSON.parse(e)}observe(t){if(!(t instanceof or))throw new b("Only FabricClientAdapter can be observed by dispatch");super.observe(t)}async updateObservers(t,e,r,...i){const{log:s,ctxArgs:n}=E.logCtx(this.updateObservers,e,!1,...i);if(this.adapter)try{await this.adapter.refresh(t,e,r,...n)}catch(t){throw new G("Failed to refresh dispatch: "+t)}else s.verbose(`No adapter observed for dispatch; skipping observer update for ${"string"==typeof t?t:F.tableName(t)}:${e}`)}async handleEvents(t){if(!this.listeningStack)throw new G('Event stack not initialized. Ensure that "startListening" is called before attempting this operation.');if(!this.adapter||!this.adapter.config)throw new G("No adapter found. should be impossible");const e=t||await this.adapter.context(z.READ,{correlationId:this.adapter.config.chaincodeName},this.models&&this.models[0]||F),r=this.log.for(this.handleEvents);r.info(`Listening for incoming events on chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}"...`);try{for await(const t of this.listeningStack){const{table:i,event:s,owner:n}=ze(t.eventName);if(n&&n!==this.adapter.config?.mspId)continue;const a=this.parsePayload(t.payload);try{const t=(i?F.get(i):F.get(this.models[0].name))??(i||this.models[0]?.name);await this.updateObservers(t,s,a.id,e)}catch(t){r.error(`Failed update observables for table ${i} event ${s} id: ${a.id}: ${t}`)}}}catch(t){r.error(`Failed to read event for chaincode "${this.adapter.config.chaincodeName}" on channel "${this.adapter.config.channel}": ${t}`),await this.close()}}async initialize(){if(!this.adapter)throw new G("No adapter or config observed for dispatch");const t=await this.adapter.context("dispatch",{correlationId:this.adapter.config.chaincodeName},F),{ctx:e}=this.logCtx([t],this.initialize),r=(await or.getGateway(e,this.adapter.config,this.client)).getNetwork(this.adapter.config.channel);if(!this.adapter)throw new G("No adapter observed for dispatch");this.listeningStack=await r.getChaincodeEvents(this.adapter.config.chaincodeName),this.handleEvents(e)}}or&&(or._baseDispatch=cr);const lr="##VERSION##",dr="##PACKAGE##";lt.registerLibrary(dr,lr);export{he as AllowanceError,re as BASE_ALPHABET,de as BalanceError,oe as BaseEncoder,ie as CRYPTO,zt as ClientSerializer,te as CoreUtils,ce as CryptoUtils,Ve as DefaultFabricClientFlags,Ke as DeterministicSerializer,ae as ERC20Events,ye as EndorsementError,Ce as EndorsementPolicyError,Se as FabricBaseModel,or as FabricClientAdapter,cr as FabricClientDispatch,_t as FabricClientRepository,Ht as FabricERC20ClientRepository,Ae as FabricEnrollmentService,Qt as FabricFlavour,Ee as FabricIdentifiedBaseModel,Ge as FabricIdentityService,Xt as FabricModelKeys,ne as HFCAIdentityAttributes,se as HFCAIdentityType,Zt as Identity,qt as IdentityCredentials,Wt as IdentityType,Re as ImplicitPrivateCollection,pe as MissingContextError,me as MissingPKCSS11Lib,we as MvccReadConflictError,fe as NotInitializedError,le as OverflowError,xe as Owner,dr as PACKAGE_NAME,be as PhantomReadConflictError,ue as RegistrationError,ve as RegistrationRequestBuilder,Ye as SimpleDeterministicSerializer,ge as UnauthorizedPrivateDataAccess,lr as VERSION,He as add,qe as contentOfLoadFile,rr as extractPrivateKey,Le as generateFabricEventName,Yt as generateModelIndexes,We as getCAUser,$e as getFabricModelKey,Ze as getFirstDirFileName,tr as getFirstDirFileNameContent,Qe as getIdentity,er as getSigner,Te as ownedBy,Ne as ownedByOnCreate,ze as parseEventName,_e as privateData,Xe as readFile,Gt as readModelFile,Vt as readModelFolders,Ue as safeParseInt,De as segregatedDataOnCreate,Be as segregatedDataOnDelete,Fe as segregatedDataOnRead,ke as segregatedDataOnUpdate,je as sharedData,Me as sub,Oe as transactionId,Ie as transactionIdOnCreate,Jt as writeIndexes};
|
|
2
2
|
//# sourceMappingURL=for-fabric.js.map
|