ofcore 0.2.0-alpha.1 → 0.2.0-alpha.2
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/contracts/CompliancePrimitives.d.ts +104 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +1 -1
- package/package.json +5 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { ScopeRef } from './CrossDomainPrimitives';
|
|
2
|
+
export interface ComplianceScopeRef extends ScopeRef {
|
|
3
|
+
domainId?: string;
|
|
4
|
+
ledgerProfileId?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ComplianceProfileContract<TConfig = Record<string, unknown>> {
|
|
7
|
+
id: string;
|
|
8
|
+
scopeRef: ComplianceScopeRef;
|
|
9
|
+
profileType: string;
|
|
10
|
+
regulatorKey?: string | null;
|
|
11
|
+
isActive: boolean;
|
|
12
|
+
effectiveFrom: string;
|
|
13
|
+
config: TConfig;
|
|
14
|
+
rulesetRef?: string | null;
|
|
15
|
+
createdAt?: string;
|
|
16
|
+
updatedAt?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface ResolveEffectiveComplianceProfileInput {
|
|
19
|
+
scopeRef: ComplianceScopeRef;
|
|
20
|
+
profileType?: string;
|
|
21
|
+
regulatorKey?: string | null;
|
|
22
|
+
effectiveAt?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface ComplianceEvidenceArtifactRef {
|
|
25
|
+
artifactId?: string | null;
|
|
26
|
+
uri?: string | null;
|
|
27
|
+
fileName?: string | null;
|
|
28
|
+
contentType?: string | null;
|
|
29
|
+
checksum?: string | null;
|
|
30
|
+
}
|
|
31
|
+
export type ComplianceEvidenceStatus = 'draft' | 'ready' | 'rejected' | 'archived';
|
|
32
|
+
export interface ComplianceEvidenceItemContract<TMeta = Record<string, unknown>> {
|
|
33
|
+
id: string;
|
|
34
|
+
profileId?: string | null;
|
|
35
|
+
scopeRef: ComplianceScopeRef;
|
|
36
|
+
evidenceType: string;
|
|
37
|
+
sourceDomain: string;
|
|
38
|
+
sourceReferenceType: string;
|
|
39
|
+
sourceReferenceId: string;
|
|
40
|
+
status: ComplianceEvidenceStatus;
|
|
41
|
+
artifactRef?: ComplianceEvidenceArtifactRef | null;
|
|
42
|
+
payloadRef?: Record<string, unknown> | null;
|
|
43
|
+
recordedAt: string;
|
|
44
|
+
tags?: string[];
|
|
45
|
+
metadata?: TMeta;
|
|
46
|
+
}
|
|
47
|
+
export type ComplianceArtifactStatus = 'ready' | 'superseded' | 'revoked';
|
|
48
|
+
export interface ComplianceExportArtifactFileInput {
|
|
49
|
+
key: string;
|
|
50
|
+
fileName: string;
|
|
51
|
+
contentType?: string;
|
|
52
|
+
payload: string;
|
|
53
|
+
recordCount?: number | null;
|
|
54
|
+
}
|
|
55
|
+
export interface ComplianceExportArtifactFileDescriptor {
|
|
56
|
+
key: string;
|
|
57
|
+
fileName: string;
|
|
58
|
+
contentType: string;
|
|
59
|
+
checksum: string;
|
|
60
|
+
byteLength: number;
|
|
61
|
+
recordCount: number | null;
|
|
62
|
+
}
|
|
63
|
+
export interface ComplianceExportArtifactContract<TSummary = Record<string, unknown>> {
|
|
64
|
+
artifactId: string;
|
|
65
|
+
scopeRef: ComplianceScopeRef;
|
|
66
|
+
artifactType: string;
|
|
67
|
+
sourceDomain: string;
|
|
68
|
+
contractVersion: string;
|
|
69
|
+
status: ComplianceArtifactStatus;
|
|
70
|
+
generatedAt: string;
|
|
71
|
+
sourceReferenceType?: string | null;
|
|
72
|
+
sourceReferenceId?: string | null;
|
|
73
|
+
profileId?: string | null;
|
|
74
|
+
files: ComplianceExportArtifactFileDescriptor[];
|
|
75
|
+
summary?: TSummary;
|
|
76
|
+
tags?: string[];
|
|
77
|
+
}
|
|
78
|
+
export interface ComplianceExportArtifactBundle<TSummary = Record<string, unknown>> {
|
|
79
|
+
contract: ComplianceExportArtifactContract<TSummary>;
|
|
80
|
+
files: Record<string, string>;
|
|
81
|
+
}
|
|
82
|
+
export declare function normalizeComplianceScopeRef(scopeRef: ComplianceScopeRef): ComplianceScopeRef;
|
|
83
|
+
export declare function countComplianceScopeSpecificity(scopeRef: ComplianceScopeRef): number;
|
|
84
|
+
export declare function matchesComplianceScopeRef(candidate: ComplianceScopeRef, requested: ComplianceScopeRef): boolean;
|
|
85
|
+
export declare function assertValidComplianceProfileContract<TConfig = Record<string, unknown>>(profile: ComplianceProfileContract<TConfig>): void;
|
|
86
|
+
export declare function assertValidComplianceEvidenceItemContract<TMeta = Record<string, unknown>>(evidence: ComplianceEvidenceItemContract<TMeta>): void;
|
|
87
|
+
export declare function assertValidComplianceExportArtifactContract<TSummary = Record<string, unknown>>(artifact: ComplianceExportArtifactContract<TSummary>): void;
|
|
88
|
+
export declare function assertComplianceExportArtifactBundleIntegrity<TSummary = Record<string, unknown>>(bundle: ComplianceExportArtifactBundle<TSummary>): void;
|
|
89
|
+
export declare function buildComplianceExportArtifactBundle<TSummary = Record<string, unknown>>(params: {
|
|
90
|
+
artifactId: string;
|
|
91
|
+
scopeRef: ComplianceScopeRef;
|
|
92
|
+
artifactType: string;
|
|
93
|
+
sourceDomain: string;
|
|
94
|
+
contractVersion: string;
|
|
95
|
+
generatedAt?: string;
|
|
96
|
+
sourceReferenceType?: string | null;
|
|
97
|
+
sourceReferenceId?: string | null;
|
|
98
|
+
profileId?: string | null;
|
|
99
|
+
status?: ComplianceArtifactStatus;
|
|
100
|
+
summary?: TSummary;
|
|
101
|
+
tags?: string[];
|
|
102
|
+
files: ComplianceExportArtifactFileInput[];
|
|
103
|
+
}): ComplianceExportArtifactBundle<TSummary>;
|
|
104
|
+
export declare function resolveEffectiveComplianceProfile<TConfig = Record<string, unknown>>(profiles: ComplianceProfileContract<TConfig>[], input: ResolveEffectiveComplianceProfileInput): ComplianceProfileContract<TConfig> | null;
|
package/dist/index.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var H=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var et=(i,t)=>{for(var e in t)H(i,e,{get:t[e],enumerable:!0})},rt=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Z(t))!tt.call(i,n)&&n!==e&&H(i,n,{get:()=>t[n],enumerable:!(r=Y(t,n))||r.enumerable});return i};var nt=i=>rt(H({},"__esModule",{value:!0}),i);var wt={};et(wt,{ConsoleLoggerAdapter:()=>V,CoreAdapterRegistry:()=>P,CoreRuntime:()=>D,CoreRuntimeBuilder:()=>I,DefaultExportAdapter:()=>z,DefaultHttpAdapter:()=>L,DefaultPlatformAdapter:()=>F,ExponentialBackoffHttpPolicy:()=>$,InMemoryDbAdapter:()=>O,InMemorySocketAdapter:()=>_,MemoryActivitySink:()=>U,MemoryStorageAdapter:()=>q,NoRetryHttpPolicy:()=>T,NoopActivitySink:()=>E,NoopChecksumAdapter:()=>R,NoopEncryptionAdapter:()=>j,NoopNotificationAdapter:()=>N,applyPendingMigrations:()=>dt,areChecksumsEqual:()=>st,asReadonlyStore:()=>ft,cloneValue:()=>vt,createStore:()=>gt,executeHttpRequestWithRetry:()=>ot,isContractVersionCompatible:()=>ct,isFailureEnvelope:()=>K,makeIdFactory:()=>bt,migrations:()=>B,normalizeChecksum:()=>M,nowIso:()=>yt,runDbAdapterContractHarness:()=>ht,toAndFilter:()=>At,unwrap:()=>at});module.exports=nt(wt);var F=class{constructor(t){}getEnvVar(t){let e=globalThis.process;if(typeof e!="undefined"&&e.env)return e.env[t]}isOnline(){return typeof globalThis.navigator!="undefined"&&typeof globalThis.navigator.onLine!="undefined"?!!globalThis.navigator.onLine:!0}async hashPin(t){return`sha256:${t}`}async verifyPin(t,e){return await this.hashPin(t)===e}};async function it(i){i<=0||await new Promise(t=>setTimeout(t,i))}async function ot(i,t,e={}){var s;let r=e.policy,n=(s=e.sleep)!=null?s:it,o=1;for(;;)try{let a=await i.request(t);if(!r)return a;let c={request:t,attempt:o,response:a};if(!r.shouldRetry(c))return a;let l=Math.max(0,r.nextDelayMs(c));await n(l),o+=1}catch(a){if(!r)throw a;let c={request:t,attempt:o,error:a};if(!r.shouldRetry(c))throw a;let l=Math.max(0,r.nextDelayMs(c));await n(l),o+=1}}function M(i){return String(i||"").trim().toLowerCase()}function st(i,t){return M(i)===M(t)}function K(i){return typeof(i==null?void 0:i.error)=="object"&&i!==null}function at(i){if(K(i))throw new Error(i.error.message||i.error.code);return i.data}function ct(i,t,e){return e===i?!0:t.includes(e)}var O=class{constructor(){this.schema={version:0,tables:[]};this.data={};this.tableNameResolver=t=>t;this.transactionDepth=0;this.snapshots=[]}setTableNameResolver(t){this.tableNameResolver=t}resolveTableName(t){return this.tableNameResolver(t)}async setUpWithSchema(t){this.schema={...t},this.data={},t.tables.forEach(e=>{this.data[e.name]=[]})}normalizeForComparison(t){if(t instanceof Date)return t.getTime();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t==null)return t;if(Array.isArray(t))return t.map(e=>this.normalizeForComparison(e));if(typeof t=="object"&&t!==null)try{return JSON.stringify(t)}catch{return String(t)}return t}evalValueExpr(t,e,r,n="t0"){if(r.type==="column"){let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}if(r.type==="literal")return this.normalizeForComparison(r.value);throw new Error(`Unsupported ValueExpression type: ${r.type}`)}buildFieldCondition(t,e){if("field"in t){let n={type:"column",tableAlias:t.alias||e,field:t.field},o={type:"literal",value:t.value};return{left:n,operator:t.operator||"=",right:o,...t.operator==="BETWEEN"?{}:{likeMode:t.likeMode}}}if("left"in t)return t;throw new Error("Invalid FieldCondition")}matchFilterExpression(t,e,r,n="t0"){if(r&&typeof r=="object"&&!Array.isArray(r)&&"and"in r)return r.and.every(o=>this.matchFilterExpression(t,e,o,n));if(r&&typeof r=="object"&&!Array.isArray(r)&&"or"in r)return r.or.some(o=>this.matchFilterExpression(t,e,o,n));if(r!==null&&typeof r=="object"&&!Array.isArray(r)){if("left"in r||"field"in r){let o=this.buildFieldCondition(r,n),s=this.evalValueExpr(t,e,o.left,n),a=this.evalValueExpr(t,e,o.right,n);if(o.operator==="IS NULL")return s==null;if(o.operator==="IS NOT NULL")return s!=null;if(o.operator==="IN"||o.operator==="NOT IN"){if(!Array.isArray(a))throw new Error("IN/NOT IN requires array on right side");let c=a.includes(s);return o.operator==="IN"?c:!c}switch(o.operator){case"=":return s===a;case"!=":return s!==a;case"<":return s<a;case"<=":return s<=a;case">":return s>a;case">=":return s>=a;case"LIKE":{if(typeof s!="string"||typeof a!="string")return!1;let c=a.replace(/%/g,".*").replace(/_/g,"."),l=o.likeMode;return new RegExp(`^${c}$`,l==="case-insensitive"?"i":"").test(s)}default:throw new Error(`Unsupported operator: ${o.operator}`)}}return Object.entries(r).every(([o,s])=>{let a=this.normalizeForComparison(t[o]),c=this.normalizeForComparison(s);return a===c})}throw new Error(`Invalid filter expression: ${JSON.stringify(r)}`)}simulateJoins(t,e,r){if(r.length===0)return e.map(o=>({record:o,joined:{}}));let n=[];for(let o of e){let s={},a=!0;for(let c of r){let l=this.resolveTableName(c.table),y=this.data[l]||[],u=null;if(c.conditions.length===1){let d=c.conditions[0];if(d.operator==="="&&d.left.type==="column"&&d.right.type==="column"){let g=d.left.tableAlias||"t0",A=d.right.tableAlias;if(g==="t0"&&A===c.alias){let m=d.left.field,h=d.right.field,p=o[m];u=y.find(b=>this.normalizeForComparison(b[h])===this.normalizeForComparison(p))}}}if(!u&&(c.type==="inner"||c.type===void 0)){a=!1;break}s[c.alias]=u||null}a&&n.push({record:o,joined:s})}return n}extractField(t,e,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(t[r]);let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}extractAggregateField(t,e,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(t[r]);let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}async getSchemaVersion(){return this.schema.version}async setSchemaVersion(t){this.schema.version=t}async addTable(t){let e=this.resolveTableName(t.name);this.data[e]||(this.data[e]=[]),this.schema.tables.find(r=>r.name===t.name)||this.schema.tables.push(t)}async addColumn(t,e){}async get(t,e){var o;let r=this.resolveTableName(t);if(typeof e=="string"){let a=(this.data[r]||[]).find(c=>c.id===e);return a||null}return(o=(await this.query(t,{...e,limit:1}))[0])!=null?o:null}async query(t,e={}){var y;let r=this.resolveTableName(t),n="t0",o=[...this.data[r]||[]],s=this.simulateJoins(r,o,e.joins||[]);if(e.filters&&(s=s.filter(({record:u,joined:d})=>this.matchFilterExpression(u,d,e.filters,n))),e.aggregates&&e.aggregates.length>0){let u={};for(let d of e.aggregates){let g=s;d.filter&&(g=g.filter(({record:p,joined:b})=>this.matchFilterExpression(p,b,d.filter,n)));let A=g.map(({record:p,joined:b})=>this.extractAggregateField(p,b,d.field,n)),m=A.map(p=>typeof p=="number"?p:Number(p)).filter(p=>Number.isFinite(p)),h=null;switch(d.function){case"COUNT":h=A.filter(p=>p!=null).length;break;case"SUM":h=m.reduce((p,b)=>p+b,0);break;case"AVG":h=m.length?m.reduce((p,b)=>p+b,0)/m.length:0;break;case"MIN":h=m.length?Math.min(...m):null;break;case"MAX":h=m.length?Math.max(...m):null;break;default:throw new Error(`Unsupported aggregate function: ${d.function}`)}u[d.as]=h}return[u]}let a=s.map(({record:u,joined:d})=>{var g;if(e.fields){if(((g=e.resultShape)!=null?g:"flat")==="nested"){let h={};for(let[p,b]of Object.entries(e.fields)){let w=p===n?u:d[p]||{},x={};for(let k of b)x[k]=w[k];h[p]=x}return h}let m={};for(let[h,p]of Object.entries(e.fields)){let b=h===n?u:d[h]||{};for(let w of p)m[`${h}_${w}`]=b[w]}return m}return u});e.sort&&e.sort.length>0&&a.sort((u,d)=>{for(let g of e.sort){let A=this.extractField(u,{},g.field,n),m=this.extractField(d,{},g.field,n);if(A<m)return g.direction==="asc"?-1:1;if(A>m)return g.direction==="asc"?1:-1}return 0});let c=(y=e.offset)!=null?y:0,l=e.limit!=null?c+e.limit:void 0;return a.slice(c,l)}async create(t,e){let r=this.resolveTableName(t);this.data[r]||(this.data[r]=[]);let n={...e};return this.data[r].push(n),n}async update(t,e,r){let n=this.resolveTableName(t),o=this.data[n]||[],s=o.findIndex(c=>c.id===e);if(s===-1)throw new Error(`Record not found: ${t} with id ${e}`);let a={...o[s],...r};return o[s]=a,a}async delete(t,e){let r=this.resolveTableName(t),n=this.data[r]||[],o=n.findIndex(s=>s.id===e);o>=0&&n.splice(o,1)}async bulkCreate(t,e){let r=this.resolveTableName(t);this.data[r]||(this.data[r]=[]);let n=[...this.data[r]];try{let o=[];for(let s of e){let a={...s};this.data[r].push(a),o.push(a)}return o}catch(o){throw this.data[r]=n,o}}async bulkUpdate(t,e){let r=this.resolveTableName(t),n=[...this.data[r]||[]];try{let o=[];for(let{id:s,updates:a}of e){let c=await this.update(t,s,a);o.push(c)}return o}catch(o){throw this.data[r]=n,o}}takeSnapshot(){let t={};for(let e in this.data)t[e]=[...this.data[e]];return t}async transaction(t){let e=this.transactionDepth===0;e&&this.snapshots.push(this.takeSnapshot()),this.transactionDepth++;try{let r=await t(this);return e&&this.snapshots.pop(),this.transactionDepth--,r}catch(r){if(e){let n=this.snapshots.pop();n&&(this.data=n)}throw this.transactionDepth--,r}}};var V=class{constructor(t){}logInfo(t,e){console.log(t,e)}logWarn(t,e){console.warn(t,e)}logError(t,e){console.error(t,e)}};function lt(i,t){if(!t||Object.keys(t).length===0)return i;let e=new URLSearchParams;for(let[n,o]of Object.entries(t))o!=null&&e.set(n,String(o));let r=e.toString();return r?i.includes("?")?`${i}&${r}`:`${i}?${r}`:i}var L=class{constructor(t){this.fetchImpl=t}async request(t){var s,a,c,l,y,u,d,g,A;let e=(s=this.fetchImpl)!=null?s:globalThis.fetch;if(typeof e!="function")throw new Error("DefaultHttpAdapter requires fetch implementation");let r=lt(t.url,t.query),n=typeof AbortController!="undefined"?new AbortController:null,o=n&&t.timeoutMs?setTimeout(()=>n.abort(),t.timeoutMs):null;try{let m=t.body!==void 0&&t.body!==null,h={...(a=t.headers)!=null?a:{}};m&&!h["content-type"]&&(h["content-type"]="application/json");let p=await e(r,{method:t.method,headers:h,body:m?JSON.stringify(t.body):void 0,signal:n==null?void 0:n.signal}),b={};(l=(c=p.headers)==null?void 0:c.forEach)==null||l.call(c,(k,C)=>{b[C.toLowerCase()]=k});let x=((y=b["content-type"])!=null?y:"").includes("application/json")?await((d=(u=p.json)==null?void 0:u.call(p))!=null?d:Promise.resolve(void 0)):await((A=(g=p.text)==null?void 0:g.call(p))!=null?A:Promise.resolve(""));return{status:p.status,headers:b,data:x}}finally{o&&clearTimeout(o)}}};var T=class{constructor(t){}shouldRetry(t){return!1}nextDelayMs(t){return 0}};var pt=[408,425,429,500,502,503,504],$=class{constructor(t={}){var e,r,n,o;this.maxAttempts=Math.max(1,(e=t.maxAttempts)!=null?e:3),this.baseDelayMs=Math.max(0,(r=t.baseDelayMs)!=null?r:250),this.maxDelayMs=Math.max(this.baseDelayMs,(n=t.maxDelayMs)!=null?n:3e3),this.retryableStatusCodes=new Set((o=t.retryableStatusCodes)!=null?o:pt)}shouldRetry(t){var r,n;if(t.attempt>=this.maxAttempts)return!1;if(t.error)return!0;let e=(n=(r=t.response)==null?void 0:r.status)!=null?n:0;return this.retryableStatusCodes.has(e)}nextDelayMs(t){let e=Math.max(0,t.attempt-1),r=this.baseDelayMs*Math.pow(2,e);return Math.min(this.maxDelayMs,r)}};var _=class{constructor(){this.connected=!1;this.listeners=new Map}async connect(t){this.connectionOptions=t,this.connected=!0}async disconnect(){this.connected=!1}subscribe(t,e){this.listeners.has(t)||this.listeners.set(t,new Set);let r=this.listeners.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&this.listeners.delete(t)}}async publish(t,e){if(!this.connected)throw new Error(`InMemorySocketAdapter is not connected (event=${t})`);let r=this.listeners.get(t);if(!(!r||r.size===0))for(let n of r)n(e)}isConnected(){return this.connected}getConnectionOptions(){return this.connectionOptions}};var N=class{constructor(t){}configure(t){}createChannel(t){}localNotification(t){}};var j=class{constructor(t){}encrypt(t,e){return String(t)}decrypt(t,e){return String(t)}};var R=class{constructor(t){}compute(t){return""}verify(t,e){return String(e||"").trim()===""}};var E=class{constructor(t){}publish(t){}};var U=class{constructor(t){this.records=[]}publish(t){this.records.push(t)}getRecords(){return[...this.records]}clear(){this.records.length=0}};var z=class{constructor(t){}getDocumentPath(t){return t}async writeFile(t,e){throw new Error("exportAdapter.writeFile is not implemented for this platform")}async share(t){throw new Error("exportAdapter.share is not implemented for this platform")}};var q=class{constructor(t){this.map=new Map}getItem(t){var e;return(e=this.map.get(t))!=null?e:null}setItem(t,e){this.map.set(t,e)}removeItem(t){this.map.delete(t)}};var B=[];async function dt(i,t){if(typeof i.getSchemaVersion!="function"||typeof i.setSchemaVersion!="function"){let e="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw t.logError(new Error(e),{message:e}),new Error(e)}t.logInfo("Starting database migration process");try{let e=[...B].sort((o,s)=>o.toVersion-s.toVersion),r=e.length>0?e[e.length-1].toVersion:0,n=await i.getSchemaVersion();if((n==null||n<0)&&(n=0),n>=r){t.logInfo(`Database is already up-to-date at v${n}`);return}t.logInfo(`Migrating database from v${n} to v${r}`);for(let o of e)o.toVersion>n&&(t.logInfo(`Applying migration: v${o.toVersion}`),await o.up(i),await i.setSchemaVersion(o.toVersion),n=o.toVersion);t.logInfo("Database migration completed successfully")}catch(e){throw t.logError(e,{message:"Database migration failed"}),e}}function v(i,t){if(!i)throw new Error(t)}function f(i,t){return`${i}-${t}`}function ut(i){let t=[{name:"id",type:"string"},{name:"name",type:"string"},{name:"age",type:"number"},{name:"tenantId",type:"string"},{name:"isActive",type:"boolean"}];return{name:`${i}_users`,columns:t,skipMetadataColumns:!0}}function mt(i){let t=[{name:"id",type:"string"},{name:"userId",type:"string",isIndexed:!0},{name:"nickname",type:"string"}];return{name:`${i}_profiles`,columns:t,skipMetadataColumns:!0}}async function ht(i,t={}){var w,x,k,C,J,W,Q;let e=((w=t.prefix)!=null?w:`dbadapter_${Date.now()}`).replace(/[^a-zA-Z0-9_]/g,"_"),r=`${e}_users`,n=`${e}_profiles`;await i.setSchemaVersion(7);let o=await i.getSchemaVersion();v(o===7,`Expected schema version 7, got ${o}`),await i.addTable(ut(e)),await i.addTable(mt(e)),await i.addColumn(r,{name:"email",type:"string",isOptional:!0}),await i.create(r,{id:f(e,"u1"),name:"Alice",age:31,tenantId:"tenant-1",isActive:!0,email:"alice@example.com"}),await i.create(r,{id:f(e,"u2"),name:"Bob",age:24,tenantId:"tenant-1",isActive:!1,email:"bob@example.com"}),await i.bulkCreate(r,[{id:f(e,"u3"),name:"Carla",age:29,tenantId:"tenant-2",isActive:!0,email:"carla@example.com"},{id:f(e,"u4"),name:"Dian",age:22,tenantId:"tenant-2",isActive:!0}]),await i.bulkCreate(n,[{id:f(e,"p1"),userId:f(e,"u1"),nickname:"alice-nick"},{id:f(e,"p2"),userId:f(e,"u3"),nickname:"carla-nick"}]);let s=await i.get(r,f(e,"u1"));v((s==null?void 0:s.name)==="Alice","Expected get(table, id) to return Alice");let a=await i.query(r,{filters:{tenantId:"tenant-1"},sort:[{field:"age",direction:"desc"}]});v(a.length===2,`Expected 2 tenant-1 users, got ${a.length}`),v(a[0].age>=a[1].age,"Expected sorted by age desc");let c={and:[{field:"tenantId",value:"tenant-2"},{field:"isActive",value:!0}]},l=await i.query(r,{filters:c,sort:[{field:"name",direction:"asc"}]});v(l.length===2,`Expected 2 active tenant-2 users, got ${l.length}`);let y={filters:{and:[{field:"id",value:f(e,"u2")},{field:"tenantId",value:"tenant-1"}]}},u=await i.get(r,y);v((u==null?void 0:u.name)==="Bob","Expected get(table, options) to resolve Bob");let d=await i.update(r,f(e,"u1"),{age:32});v(d.age===32,`Expected age updated to 32, got ${d.age}`);let g=await i.bulkUpdate(r,[{id:f(e,"u3"),updates:{age:30}},{id:f(e,"u4"),updates:{age:23}}]);v(g.length===2,`Expected 2 bulk-updated rows, got ${g.length}`);let A=await i.query(r,{sort:[{field:"age",direction:"asc"}],limit:2,offset:1});v(A.length===2,`Expected 2 paged rows, got ${A.length}`);let m=await i.query(r,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:n,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:f(e,"u1")},resultShape:"flat"});v(m.length===1,`Expected one projected flat row, got ${m.length}`),v(((x=m[0])==null?void 0:x.t0_id)===f(e,"u1"),"Expected flat projected key t0_id"),v(((k=m[0])==null?void 0:k.p_nickname)==="alice-nick","Expected flat projected key p_nickname");let h=await i.query(r,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:n,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:f(e,"u1")},resultShape:"nested"});v(h.length===1,`Expected one projected nested row, got ${h.length}`),v(((J=(C=h[0])==null?void 0:C.t0)==null?void 0:J.id)===f(e,"u1"),"Expected nested row t0.id"),v(((Q=(W=h[0])==null?void 0:W.p)==null?void 0:Q.nickname)==="alice-nick","Expected nested row p.nickname");try{throw await i.transaction(async S=>{throw await S.create(r,{id:f(e,"tx_rollback"),name:"TxRollback",age:40,tenantId:"tenant-1",isActive:!0}),new Error("rollback-intent")}),new Error("Expected transaction rollback to throw")}catch(S){let G=S instanceof Error?S.message:String(S);v(G.includes("rollback-intent"),`Expected rollback-intent error, got ${G}`)}let p=await i.get(r,f(e,"tx_rollback"));v(p===null,"Expected rolled back record to not exist"),await i.delete(r,f(e,"u2"));let b=await i.get(r,f(e,"u2"));v(b===null,"Expected deleted record to be null")}var P=class{constructor(t,e){this.extensions=new Map;var r,n,o,s,a,c,l,y,u,d,g,A,m;this.platformAdapter=(r=e.platformAdapter)==null?void 0:r.call(e,t),this.dbAdapter=(n=e.dbAdapter)==null?void 0:n.call(e,t),this.loggerAdapter=(o=e.loggerAdapter)==null?void 0:o.call(e,t),this.httpAdapter=(s=e.httpAdapter)==null?void 0:s.call(e,t),this.httpRetryPolicy=(c=(a=e.httpRetryPolicy)==null?void 0:a.call(e,t))!=null?c:new T(t),this.socketAdapter=(l=e.socketAdapter)==null?void 0:l.call(e,t),this.encryptionAdapter=(y=e.encryptionAdapter)==null?void 0:y.call(e,t),this.checksumAdapter=(d=(u=e.checksumAdapter)==null?void 0:u.call(e,t))!=null?d:new R(t),this.activitySink=(A=(g=e.activitySink)==null?void 0:g.call(e,t))!=null?A:new E(t);for(let[h,p]of Object.entries((m=e.extensions)!=null?m:{}))this.extensions.set(h,p(t))}getExtension(t){return this.extensions.get(t)}clear(){this.extensions.clear()}};function X(i){return!!i&&typeof i.shutdown=="function"}var D=class{constructor(){this.correlationCounter=0;this.started=!1;this.pluginsLoaded=!1;this.pendingPlugins=[];this.hooks={}}static builder(){return new I}setHooks(t){this.hooks={...this.hooks,...t}}use(t,e,r=[]){if(!t.trim())throw new Error("plugin name is required");return this.pendingPlugins.some(n=>n.name===t)?this:(this.pendingPlugins.push({name:t,init:e,deps:r}),this)}async init(t={runMigrations:!0,useSeedData:!1}){if(!this.registry)throw new Error("CoreRuntime registry is not initialized. Call builder().build() first.");if(t.runMigrations!==!1&&this.hooks.runMigrations&&await this.hooks.runMigrations(this),this.hooks.onInit&&await this.hooks.onInit(this),!this.domainServices&&this.hooks.createDomainServices&&(this.domainServices=await this.hooks.createDomainServices(this)),!this.integrationServices&&this.hooks.createIntegrationServices&&(this.integrationServices=await this.hooks.createIntegrationServices(this)),!this.pluginsLoaded){let n=this.resolvePluginLevels();for(let o of n)await Promise.all(o.map(s=>s.init(this)));this.pluginsLoaded=!0}t.useSeedData===!0&&this.hooks.runSeed&&await this.hooks.runSeed(this)}async start(t={}){if(this.started)throw new Error("CoreRuntime already started");try{await this.init(t),this.started=!0}catch(e){throw this.started=!1,e}}async stop(){var t;this.started&&(this.hooks.onStop&&await this.hooks.onStop(this),X(this.integrationServices)&&await this.integrationServices.shutdown(),X(this.domainServices)&&await this.domainServices.shutdown(),(t=this.registry)==null||t.clear(),this.started=!1)}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.pendingPlugins=[],this.pluginsLoaded=!1,this.hooks={}}async restart(){let t=[...this.pendingPlugins],e={...this.hooks};await this.reset(),this.pendingPlugins=t,this.hooks=e,await this.start()}isStarted(){return this.started}createCorrelationId(t="cid"){return this.correlationCounter+=1,`${t}-${Date.now()}-${this.correlationCounter}`}logInfo(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logInfo(t,e)}logWarn(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logWarn(t,e)}logError(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logError(t,e)}async emitActivity(t){var e;(e=this.registry)!=null&&e.activitySink&&await this.registry.activitySink.publish(t)}resolvePluginLevels(){var s,a,c;if(this.pendingPlugins.length===0)return[];let t=new Map,e=new Map,r=new Map;for(let l of this.pendingPlugins){if(t.has(l.name))throw new Error(`Duplicate plugin name: ${l.name}`);t.set(l.name,[]),e.set(l.name,0),r.set(l.name,l)}for(let l of this.pendingPlugins)for(let y of l.deps){if(!t.has(y))throw new Error(`Plugin "${l.name}" depends on unknown plugin "${y}"`);t.get(y).push(l.name),e.set(l.name,((s=e.get(l.name))!=null?s:0)+1)}let n=[],o=Array.from(e.entries()).filter(([,l])=>l===0).map(([l])=>l);for(;o.length>0;){let l=o.map(u=>r.get(u));n.push(l);let y=[];for(let u of o)for(let d of(a=t.get(u))!=null?a:[]){let g=((c=e.get(d))!=null?c:0)-1;e.set(d,g),g===0&&y.push(d)}o=y}if(n.flat().length!==this.pendingPlugins.length)throw new Error("Circular dependency detected among plugins");return n}},I=class{constructor(){this.runtime=new D;this.adapterOptions={};this.hooks={}}withPlatformAdapter(t){return this.adapterOptions.platformAdapter=t,this}withDbAdapter(t){return this.adapterOptions.dbAdapter=t,this}withHttpAdapter(t){return this.adapterOptions.httpAdapter=t,this}withHttpRetryPolicy(t){return this.adapterOptions.httpRetryPolicy=t,this}withSocketAdapter(t){return this.adapterOptions.socketAdapter=t,this}withEncryptionAdapter(t){return this.adapterOptions.encryptionAdapter=t,this}withChecksumAdapter(t){return this.adapterOptions.checksumAdapter=t,this}withActivitySink(t){return this.adapterOptions.activitySink=t,this}withLoggerAdapter(t){return this.adapterOptions.loggerAdapter=t,this}withExtension(t,e){var r;return this.adapterOptions.extensions=(r=this.adapterOptions.extensions)!=null?r:{},this.adapterOptions.extensions[t]=e,this}withHooks(t){return this.hooks={...this.hooks,...t},this}build(){return this.runtime.setHooks(this.hooks),this.runtime.registry=new P(this.runtime,this.adapterOptions),this.runtime}};function gt(i){let t=i,e=new Set,r=(n,o)=>{for(let s of e)s(n,o)};return{getState(){return t},setState(n){let o=t;return t=typeof n=="function"?n(t):{...t,...n},r(t,o),t},reset(n){let o=t;return t=n!=null?n:i,r(t,o),t},subscribe(n){return e.add(n),()=>{e.delete(n)}}}}function ft(i){return{getState:i.getState,subscribe:i.subscribe}}function yt(){return new Date().toISOString()}function bt(i){let t=0;return()=>(t+=1,`${i}-${Date.now()}-${t}`)}function vt(i){return JSON.parse(JSON.stringify(i))}function At(i){if(i.length!==0)return i.length===1?i[0]:{and:i}}
|
|
1
|
+
"use strict";var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ft=(r,t)=>{for(var e in t)M(r,e,{get:t[e],enumerable:!0})},mt=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ut(t))!dt.call(r,i)&&i!==e&&M(r,i,{get:()=>t[i],enumerable:!(n=pt(t,i))||n.enumerable});return r};var gt=r=>mt(M({},"__esModule",{value:!0}),r);var Mt={};ft(Mt,{ConsoleLoggerAdapter:()=>Q,CoreAdapterRegistry:()=>N,CoreRuntime:()=>L,CoreRuntimeBuilder:()=>O,DefaultExportAdapter:()=>W,DefaultHttpAdapter:()=>z,DefaultPlatformAdapter:()=>V,ExponentialBackoffHttpPolicy:()=>B,InMemoryDbAdapter:()=>j,InMemorySocketAdapter:()=>q,MemoryActivitySink:()=>J,MemoryStorageAdapter:()=>G,NoRetryHttpPolicy:()=>_,NoopActivitySink:()=>P,NoopChecksumAdapter:()=>k,NoopEncryptionAdapter:()=>K,NoopNotificationAdapter:()=>Y,applyPendingMigrations:()=>St,areChecksumsEqual:()=>At,asReadonlyStore:()=>Dt,assertComplianceExportArtifactBundleIntegrity:()=>st,assertValidComplianceEvidenceItemContract:()=>It,assertValidComplianceExportArtifactContract:()=>$,assertValidComplianceProfileContract:()=>ot,buildComplianceExportArtifactBundle:()=>bt,cloneValue:()=>Lt,countComplianceScopeSpecificity:()=>U,createStore:()=>Pt,executeHttpRequestWithRetry:()=>yt,isContractVersionCompatible:()=>Ct,isFailureEnvelope:()=>nt,makeIdFactory:()=>Nt,matchesComplianceScopeRef:()=>it,migrations:()=>Z,normalizeChecksum:()=>H,normalizeComplianceScopeRef:()=>R,nowIso:()=>Ft,resolveEffectiveComplianceProfile:()=>Rt,runDbAdapterContractHarness:()=>kt,toAndFilter:()=>Ot,unwrap:()=>Et});module.exports=gt(Mt);var V=class{constructor(t){}getEnvVar(t){let e=globalThis.process;if(typeof e!="undefined"&&e.env)return e.env[t]}isOnline(){return typeof globalThis.navigator!="undefined"&&typeof globalThis.navigator.onLine!="undefined"?!!globalThis.navigator.onLine:!0}async hashPin(t){return`sha256:${t}`}async verifyPin(t,e){return await this.hashPin(t)===e}};async function ht(r){r<=0||await new Promise(t=>setTimeout(t,r))}async function yt(r,t,e={}){var s;let n=e.policy,i=(s=e.sleep)!=null?s:ht,o=1;for(;;)try{let a=await r.request(t);if(!n)return a;let c={request:t,attempt:o,response:a};if(!n.shouldRetry(c))return a;let l=Math.max(0,n.nextDelayMs(c));await i(l),o+=1}catch(a){if(!n)throw a;let c={request:t,attempt:o,error:a};if(!n.shouldRetry(c))throw a;let l=Math.max(0,n.nextDelayMs(c));await i(l),o+=1}}function H(r){return String(r||"").trim().toLowerCase()}function At(r,t){return H(r)===H(t)}function nt(r){return typeof(r==null?void 0:r.error)=="object"&&r!==null}function Et(r){if(nt(r))throw new Error(r.error.message||r.error.code);return r.data}function Ct(r,t,e){return e===r?!0:t.includes(e)}function y(r,t){if(typeof r!="string"||r.trim().length===0)throw new Error(t);return r.trim()}function x(r,t){let e=y(r,t);if(Number.isNaN(Date.parse(e)))throw new Error(t);return e}function I(r){if(typeof r!="string")return;let t=r.trim();return t.length>0?t:void 0}function F(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Tt(r){return Object.keys(r).length>0}function R(r){return{tenantId:I(r==null?void 0:r.tenantId),branchId:I(r==null?void 0:r.branchId),domain:I(r==null?void 0:r.domain),domainId:I(r==null?void 0:r.domainId),ledgerProfileId:I(r==null?void 0:r.ledgerProfileId)}}function U(r){let t=R(r);return["tenantId","branchId","domain","domainId","ledgerProfileId"].map(e=>t[e]).filter(Boolean).length}function it(r,t){let e=R(r),n=R(t);for(let i of["tenantId","branchId","domain","domainId","ledgerProfileId"]){let o=e[i],s=n[i];if(o&&(!s||o!==s))return!1}return!0}function ot(r){var t;if(y(r.id,"COMPLIANCE_PROFILE_ID_REQUIRED"),y(r.profileType,"COMPLIANCE_PROFILE_TYPE_REQUIRED"),x(r.effectiveFrom,"COMPLIANCE_PROFILE_EFFECTIVE_FROM_INVALID"),r.createdAt!=null&&x(r.createdAt,"COMPLIANCE_PROFILE_CREATED_AT_INVALID"),r.updatedAt!=null&&x(r.updatedAt,"COMPLIANCE_PROFILE_UPDATED_AT_INVALID"),typeof r.isActive!="boolean")throw new Error("COMPLIANCE_PROFILE_IS_ACTIVE_REQUIRED");if(!F(r.config))throw new Error("COMPLIANCE_PROFILE_CONFIG_REQUIRED");R((t=r.scopeRef)!=null?t:{})}function It(r){var n,i,o;if(y(r.id,"COMPLIANCE_EVIDENCE_ID_REQUIRED"),y(r.evidenceType,"COMPLIANCE_EVIDENCE_TYPE_REQUIRED"),y(r.sourceDomain,"COMPLIANCE_EVIDENCE_SOURCE_DOMAIN_REQUIRED"),y(r.sourceReferenceType,"COMPLIANCE_EVIDENCE_SOURCE_REFERENCE_TYPE_REQUIRED"),y(r.sourceReferenceId,"COMPLIANCE_EVIDENCE_SOURCE_REFERENCE_ID_REQUIRED"),x(r.recordedAt,"COMPLIANCE_EVIDENCE_RECORDED_AT_INVALID"),!["draft","ready","rejected","archived"].includes(r.status))throw new Error("COMPLIANCE_EVIDENCE_STATUS_INVALID");let t=(n=r.artifactRef)!=null?n:null,e=(i=r.payloadRef)!=null?i:null;if(!t&&!e)throw new Error("COMPLIANCE_EVIDENCE_REFERENCE_REQUIRED");if(t){if(!F(t))throw new Error("COMPLIANCE_EVIDENCE_ARTIFACT_REF_INVALID");let s=I(t.artifactId),a=I(t.uri);if(!!!(s||a))throw new Error("COMPLIANCE_EVIDENCE_ARTIFACT_REF_INVALID")}if(e&&(!F(e)||!Tt(e)))throw new Error("COMPLIANCE_EVIDENCE_PAYLOAD_REF_INVALID");R((o=r.scopeRef)!=null?o:{})}function $(r){var n;if(y(r.artifactId,"COMPLIANCE_ARTIFACT_ID_REQUIRED"),y(r.artifactType,"COMPLIANCE_ARTIFACT_TYPE_REQUIRED"),y(r.sourceDomain,"COMPLIANCE_ARTIFACT_SOURCE_DOMAIN_REQUIRED"),y(r.contractVersion,"COMPLIANCE_ARTIFACT_CONTRACT_VERSION_REQUIRED"),x(r.generatedAt,"COMPLIANCE_ARTIFACT_GENERATED_AT_INVALID"),!["ready","superseded","revoked"].includes(r.status))throw new Error("COMPLIANCE_ARTIFACT_STATUS_INVALID");if(!Array.isArray(r.files)||r.files.length===0)throw new Error("COMPLIANCE_ARTIFACT_FILES_REQUIRED");let t=new Set,e=new Set;for(let i of r.files){let o=y(i.key,"COMPLIANCE_ARTIFACT_FILE_KEY_REQUIRED");if(t.has(o))throw new Error("COMPLIANCE_ARTIFACT_FILE_KEY_DUPLICATE");t.add(o);let s=y(i.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(e.has(s))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");if(e.add(s),y(i.contentType,"COMPLIANCE_ARTIFACT_FILE_CONTENT_TYPE_REQUIRED"),y(i.checksum,"COMPLIANCE_ARTIFACT_FILE_CHECKSUM_REQUIRED"),!Number.isFinite(i.byteLength)||i.byteLength<0)throw new Error("COMPLIANCE_ARTIFACT_FILE_SIZE_INVALID");if(i.recordCount!=null&&(!Number.isFinite(i.recordCount)||i.recordCount<0))throw new Error("COMPLIANCE_ARTIFACT_FILE_RECORD_COUNT_INVALID")}R((n=r.scopeRef)!=null?n:{})}function st(r){if($(r.contract),!F(r.files))throw new Error("COMPLIANCE_ARTIFACT_FILES_PAYLOAD_INVALID");let t=Object.entries(r.files),e=new Set;for(let n of r.contract.files){let i=y(n.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(e.has(i))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");e.add(i);let o=r.files[i];if(typeof o!="string")throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_MISSING");if(at(o)!==n.checksum)throw new Error("COMPLIANCE_ARTIFACT_FILE_CHECKSUM_MISMATCH");if(ct(o)!==n.byteLength)throw new Error("COMPLIANCE_ARTIFACT_FILE_BYTE_LENGTH_MISMATCH")}if(t.length!==r.contract.files.length)throw new Error("COMPLIANCE_ARTIFACT_FILESET_SIZE_MISMATCH");for(let[n,i]of t){if(typeof n!="string"||n.trim().length===0)throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(typeof i!="string")throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_INVALID");if(!e.has(n))throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_EXTRA")}}function at(r){let t=2166136261;for(let e=0;e<r.length;e+=1)t^=r.charCodeAt(e),t=Math.imul(t,16777619);return`fnv1a32-${(t>>>0).toString(16).padStart(8,"0")}`}function ct(r){var n;let t=globalThis.TextEncoder;if(t)return new t().encode(r).length;let e=0;for(let i of r){let o=(n=i.codePointAt(0))!=null?n:0;o<=127?e+=1:o<=2047?e+=2:o<=65535?e+=3:e+=4}return e}function bt(r){var a,c,l,h,f,u,m,A;if(!Array.isArray(r.files)||r.files.length===0)throw new Error("COMPLIANCE_ARTIFACT_FILES_REQUIRED");let t=[],e={},n=new Set,i=new Set;for(let d of r.files){let g=y(d.key,"COMPLIANCE_ARTIFACT_FILE_KEY_REQUIRED");if(n.has(g))throw new Error("COMPLIANCE_ARTIFACT_FILE_KEY_DUPLICATE");n.add(g);let p=y(d.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(i.has(p))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");i.add(p);let E=y(d.payload,"COMPLIANCE_ARTIFACT_FILE_PAYLOAD_REQUIRED"),b=(a=I(d.contentType))!=null?a:"application/octet-stream";e[p]=E,t.push({key:g,fileName:p,contentType:b,checksum:at(E),byteLength:ct(E),recordCount:(c=d.recordCount)!=null?c:null})}let o={artifactId:y(r.artifactId,"COMPLIANCE_ARTIFACT_ID_REQUIRED"),scopeRef:R((l=r.scopeRef)!=null?l:{}),artifactType:y(r.artifactType,"COMPLIANCE_ARTIFACT_TYPE_REQUIRED"),sourceDomain:y(r.sourceDomain,"COMPLIANCE_ARTIFACT_SOURCE_DOMAIN_REQUIRED"),contractVersion:y(r.contractVersion,"COMPLIANCE_ARTIFACT_CONTRACT_VERSION_REQUIRED"),status:(h=r.status)!=null?h:"ready",generatedAt:(f=r.generatedAt)!=null?f:new Date().toISOString(),sourceReferenceType:(u=I(r.sourceReferenceType))!=null?u:null,sourceReferenceId:(m=I(r.sourceReferenceId))!=null?m:null,profileId:(A=I(r.profileId))!=null?A:null,files:t,summary:r.summary,tags:Array.isArray(r.tags)?r.tags.filter(d=>typeof d=="string"&&d.trim().length>0):[]};$(o);let s={contract:o,files:e};return st(s),s}function Rt(r,t){var i,o;let e=(i=t.effectiveAt)!=null?i:new Date().toISOString();if(Number.isNaN(Date.parse(e)))throw new Error("COMPLIANCE_PROFILE_EFFECTIVE_AT_INVALID");return(o=r.filter(s=>{var a;return ot(s),!s.isActive||Date.parse(s.effectiveFrom)>Date.parse(e)||t.profileType&&s.profileType!==t.profileType||t.regulatorKey!=null&&((a=s.regulatorKey)!=null?a:null)!==t.regulatorKey?!1:it(s.scopeRef,t.scopeRef)}).sort((s,a)=>{var f,u,m,A;let c=U(a.scopeRef)-U(s.scopeRef);if(c!==0)return c;let l=Date.parse(a.effectiveFrom)-Date.parse(s.effectiveFrom);if(l!==0)return l;let h=Date.parse((u=(f=a.updatedAt)!=null?f:a.createdAt)!=null?u:a.effectiveFrom)-Date.parse((A=(m=s.updatedAt)!=null?m:s.createdAt)!=null?A:s.effectiveFrom);return h!==0?h:s.id.localeCompare(a.id)})[0])!=null?o:null}var j=class{constructor(){this.schema={version:0,tables:[]};this.data={};this.tableNameResolver=t=>t;this.transactionDepth=0;this.snapshots=[]}setTableNameResolver(t){this.tableNameResolver=t}resolveTableName(t){return this.tableNameResolver(t)}async setUpWithSchema(t){this.schema={...t},this.data={},t.tables.forEach(e=>{this.data[e.name]=[]})}normalizeForComparison(t){if(t instanceof Date)return t.getTime();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t==null)return t;if(Array.isArray(t))return t.map(e=>this.normalizeForComparison(e));if(typeof t=="object"&&t!==null)try{return JSON.stringify(t)}catch{return String(t)}return t}evalValueExpr(t,e,n,i="t0"){if(n.type==="column"){let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}if(n.type==="literal")return this.normalizeForComparison(n.value);throw new Error(`Unsupported ValueExpression type: ${n.type}`)}buildFieldCondition(t,e){if("field"in t){let i={type:"column",tableAlias:t.alias||e,field:t.field},o={type:"literal",value:t.value};return{left:i,operator:t.operator||"=",right:o,...t.operator==="BETWEEN"?{}:{likeMode:t.likeMode}}}if("left"in t)return t;throw new Error("Invalid FieldCondition")}matchFilterExpression(t,e,n,i="t0"){if(n&&typeof n=="object"&&!Array.isArray(n)&&"and"in n)return n.and.every(o=>this.matchFilterExpression(t,e,o,i));if(n&&typeof n=="object"&&!Array.isArray(n)&&"or"in n)return n.or.some(o=>this.matchFilterExpression(t,e,o,i));if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if("left"in n||"field"in n){let o=this.buildFieldCondition(n,i),s=this.evalValueExpr(t,e,o.left,i),a=this.evalValueExpr(t,e,o.right,i);if(o.operator==="IS NULL")return s==null;if(o.operator==="IS NOT NULL")return s!=null;if(o.operator==="IN"||o.operator==="NOT IN"){if(!Array.isArray(a))throw new Error("IN/NOT IN requires array on right side");let c=a.includes(s);return o.operator==="IN"?c:!c}switch(o.operator){case"=":return s===a;case"!=":return s!==a;case"<":return s<a;case"<=":return s<=a;case">":return s>a;case">=":return s>=a;case"LIKE":{if(typeof s!="string"||typeof a!="string")return!1;let c=a.replace(/%/g,".*").replace(/_/g,"."),l=o.likeMode;return new RegExp(`^${c}$`,l==="case-insensitive"?"i":"").test(s)}default:throw new Error(`Unsupported operator: ${o.operator}`)}}return Object.entries(n).every(([o,s])=>{let a=this.normalizeForComparison(t[o]),c=this.normalizeForComparison(s);return a===c})}throw new Error(`Invalid filter expression: ${JSON.stringify(n)}`)}simulateJoins(t,e,n){if(n.length===0)return e.map(o=>({record:o,joined:{}}));let i=[];for(let o of e){let s={},a=!0;for(let c of n){let l=this.resolveTableName(c.table),h=this.data[l]||[],f=null;if(c.conditions.length===1){let u=c.conditions[0];if(u.operator==="="&&u.left.type==="column"&&u.right.type==="column"){let m=u.left.tableAlias||"t0",A=u.right.tableAlias;if(m==="t0"&&A===c.alias){let d=u.left.field,g=u.right.field,p=o[d];f=h.find(E=>this.normalizeForComparison(E[g])===this.normalizeForComparison(p))}}}if(!f&&(c.type==="inner"||c.type===void 0)){a=!1;break}s[c.alias]=f||null}a&&i.push({record:o,joined:s})}return i}extractField(t,e,n,i="t0"){if(typeof n=="string")return this.normalizeForComparison(t[n]);let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}extractAggregateField(t,e,n,i="t0"){if(typeof n=="string")return this.normalizeForComparison(t[n]);let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}async getSchemaVersion(){return this.schema.version}async setSchemaVersion(t){this.schema.version=t}async addTable(t){let e=this.resolveTableName(t.name);this.data[e]||(this.data[e]=[]),this.schema.tables.find(n=>n.name===t.name)||this.schema.tables.push(t)}async addColumn(t,e){}async get(t,e){var o;let n=this.resolveTableName(t);if(typeof e=="string"){let a=(this.data[n]||[]).find(c=>c.id===e);return a||null}return(o=(await this.query(t,{...e,limit:1}))[0])!=null?o:null}async query(t,e={}){var h;let n=this.resolveTableName(t),i="t0",o=[...this.data[n]||[]],s=this.simulateJoins(n,o,e.joins||[]);if(e.filters&&(s=s.filter(({record:f,joined:u})=>this.matchFilterExpression(f,u,e.filters,i))),e.aggregates&&e.aggregates.length>0){let f={};for(let u of e.aggregates){let m=s;u.filter&&(m=m.filter(({record:p,joined:E})=>this.matchFilterExpression(p,E,u.filter,i)));let A=m.map(({record:p,joined:E})=>this.extractAggregateField(p,E,u.field,i)),d=A.map(p=>typeof p=="number"?p:Number(p)).filter(p=>Number.isFinite(p)),g=null;switch(u.function){case"COUNT":g=A.filter(p=>p!=null).length;break;case"SUM":g=d.reduce((p,E)=>p+E,0);break;case"AVG":g=d.length?d.reduce((p,E)=>p+E,0)/d.length:0;break;case"MIN":g=d.length?Math.min(...d):null;break;case"MAX":g=d.length?Math.max(...d):null;break;default:throw new Error(`Unsupported aggregate function: ${u.function}`)}f[u.as]=g}return[f]}let a=s.map(({record:f,joined:u})=>{var m;if(e.fields){if(((m=e.resultShape)!=null?m:"flat")==="nested"){let g={};for(let[p,E]of Object.entries(e.fields)){let b=p===i?f:u[p]||{},w={};for(let v of E)w[v]=b[v];g[p]=w}return g}let d={};for(let[g,p]of Object.entries(e.fields)){let E=g===i?f:u[g]||{};for(let b of p)d[`${g}_${b}`]=E[b]}return d}return f});e.sort&&e.sort.length>0&&a.sort((f,u)=>{for(let m of e.sort){let A=this.extractField(f,{},m.field,i),d=this.extractField(u,{},m.field,i);if(A<d)return m.direction==="asc"?-1:1;if(A>d)return m.direction==="asc"?1:-1}return 0});let c=(h=e.offset)!=null?h:0,l=e.limit!=null?c+e.limit:void 0;return a.slice(c,l)}async create(t,e){let n=this.resolveTableName(t);this.data[n]||(this.data[n]=[]);let i={...e};return this.data[n].push(i),i}async update(t,e,n){let i=this.resolveTableName(t),o=this.data[i]||[],s=o.findIndex(c=>c.id===e);if(s===-1)throw new Error(`Record not found: ${t} with id ${e}`);let a={...o[s],...n};return o[s]=a,a}async delete(t,e){let n=this.resolveTableName(t),i=this.data[n]||[],o=i.findIndex(s=>s.id===e);o>=0&&i.splice(o,1)}async bulkCreate(t,e){let n=this.resolveTableName(t);this.data[n]||(this.data[n]=[]);let i=[...this.data[n]];try{let o=[];for(let s of e){let a={...s};this.data[n].push(a),o.push(a)}return o}catch(o){throw this.data[n]=i,o}}async bulkUpdate(t,e){let n=this.resolveTableName(t),i=[...this.data[n]||[]];try{let o=[];for(let{id:s,updates:a}of e){let c=await this.update(t,s,a);o.push(c)}return o}catch(o){throw this.data[n]=i,o}}takeSnapshot(){let t={};for(let e in this.data)t[e]=[...this.data[e]];return t}async transaction(t){let e=this.transactionDepth===0;e&&this.snapshots.push(this.takeSnapshot()),this.transactionDepth++;try{let n=await t(this);return e&&this.snapshots.pop(),this.transactionDepth--,n}catch(n){if(e){let i=this.snapshots.pop();i&&(this.data=i)}throw this.transactionDepth--,n}}};var Q=class{constructor(t){}logInfo(t,e){console.log(t,e)}logWarn(t,e){console.warn(t,e)}logError(t,e){console.error(t,e)}};function wt(r,t){if(!t||Object.keys(t).length===0)return r;let e=new URLSearchParams;for(let[i,o]of Object.entries(t))o!=null&&e.set(i,String(o));let n=e.toString();return n?r.includes("?")?`${r}&${n}`:`${r}?${n}`:r}var z=class{constructor(t){this.fetchImpl=t}async request(t){var s,a,c,l,h,f,u,m,A;let e=(s=this.fetchImpl)!=null?s:globalThis.fetch;if(typeof e!="function")throw new Error("DefaultHttpAdapter requires fetch implementation");let n=wt(t.url,t.query),i=typeof AbortController!="undefined"?new AbortController:null,o=i&&t.timeoutMs?setTimeout(()=>i.abort(),t.timeoutMs):null;try{let d=t.body!==void 0&&t.body!==null,g={...(a=t.headers)!=null?a:{}};d&&!g["content-type"]&&(g["content-type"]="application/json");let p=await e(n,{method:t.method,headers:g,body:d?JSON.stringify(t.body):void 0,signal:i==null?void 0:i.signal}),E={};(l=(c=p.headers)==null?void 0:c.forEach)==null||l.call(c,(v,D)=>{E[D.toLowerCase()]=v});let w=((h=E["content-type"])!=null?h:"").includes("application/json")?await((u=(f=p.json)==null?void 0:f.call(p))!=null?u:Promise.resolve(void 0)):await((A=(m=p.text)==null?void 0:m.call(p))!=null?A:Promise.resolve(""));return{status:p.status,headers:E,data:w}}finally{o&&clearTimeout(o)}}};var _=class{constructor(t){}shouldRetry(t){return!1}nextDelayMs(t){return 0}};var vt=[408,425,429,500,502,503,504],B=class{constructor(t={}){var e,n,i,o;this.maxAttempts=Math.max(1,(e=t.maxAttempts)!=null?e:3),this.baseDelayMs=Math.max(0,(n=t.baseDelayMs)!=null?n:250),this.maxDelayMs=Math.max(this.baseDelayMs,(i=t.maxDelayMs)!=null?i:3e3),this.retryableStatusCodes=new Set((o=t.retryableStatusCodes)!=null?o:vt)}shouldRetry(t){var n,i;if(t.attempt>=this.maxAttempts)return!1;if(t.error)return!0;let e=(i=(n=t.response)==null?void 0:n.status)!=null?i:0;return this.retryableStatusCodes.has(e)}nextDelayMs(t){let e=Math.max(0,t.attempt-1),n=this.baseDelayMs*Math.pow(2,e);return Math.min(this.maxDelayMs,n)}};var q=class{constructor(){this.connected=!1;this.listeners=new Map}async connect(t){this.connectionOptions=t,this.connected=!0}async disconnect(){this.connected=!1}subscribe(t,e){this.listeners.has(t)||this.listeners.set(t,new Set);let n=this.listeners.get(t);return n.add(e),()=>{n.delete(e),n.size===0&&this.listeners.delete(t)}}async publish(t,e){if(!this.connected)throw new Error(`InMemorySocketAdapter is not connected (event=${t})`);let n=this.listeners.get(t);if(!(!n||n.size===0))for(let i of n)i(e)}isConnected(){return this.connected}getConnectionOptions(){return this.connectionOptions}};var Y=class{constructor(t){}configure(t){}createChannel(t){}localNotification(t){}};var K=class{constructor(t){}encrypt(t,e){return String(t)}decrypt(t,e){return String(t)}};var k=class{constructor(t){}compute(t){return""}verify(t,e){return String(e||"").trim()===""}};var P=class{constructor(t){}publish(t){}};var J=class{constructor(t){this.records=[]}publish(t){this.records.push(t)}getRecords(){return[...this.records]}clear(){this.records.length=0}};var W=class{constructor(t){}getDocumentPath(t){return t}async writeFile(t,e){throw new Error("exportAdapter.writeFile is not implemented for this platform")}async share(t){throw new Error("exportAdapter.share is not implemented for this platform")}};var G=class{constructor(t){this.map=new Map}getItem(t){var e;return(e=this.map.get(t))!=null?e:null}setItem(t,e){this.map.set(t,e)}removeItem(t){this.map.delete(t)}};var Z=[];async function St(r,t){if(typeof r.getSchemaVersion!="function"||typeof r.setSchemaVersion!="function"){let e="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw t.logError(new Error(e),{message:e}),new Error(e)}t.logInfo("Starting database migration process");try{let e=[...Z].sort((o,s)=>o.toVersion-s.toVersion),n=e.length>0?e[e.length-1].toVersion:0,i=await r.getSchemaVersion();if((i==null||i<0)&&(i=0),i>=n){t.logInfo(`Database is already up-to-date at v${i}`);return}t.logInfo(`Migrating database from v${i} to v${n}`);for(let o of e)o.toVersion>i&&(t.logInfo(`Applying migration: v${o.toVersion}`),await o.up(r),await r.setSchemaVersion(o.toVersion),i=o.toVersion);t.logInfo("Database migration completed successfully")}catch(e){throw t.logError(e,{message:"Database migration failed"}),e}}function T(r,t){if(!r)throw new Error(t)}function C(r,t){return`${r}-${t}`}function xt(r){let t=[{name:"id",type:"string"},{name:"name",type:"string"},{name:"age",type:"number"},{name:"tenantId",type:"string"},{name:"isActive",type:"boolean"}];return{name:`${r}_users`,columns:t,skipMetadataColumns:!0}}function _t(r){let t=[{name:"id",type:"string"},{name:"userId",type:"string",isIndexed:!0},{name:"nickname",type:"string"}];return{name:`${r}_profiles`,columns:t,skipMetadataColumns:!0}}async function kt(r,t={}){var b,w,v,D,X,tt,et;let e=((b=t.prefix)!=null?b:`dbadapter_${Date.now()}`).replace(/[^a-zA-Z0-9_]/g,"_"),n=`${e}_users`,i=`${e}_profiles`;await r.setSchemaVersion(7);let o=await r.getSchemaVersion();T(o===7,`Expected schema version 7, got ${o}`),await r.addTable(xt(e)),await r.addTable(_t(e)),await r.addColumn(n,{name:"email",type:"string",isOptional:!0}),await r.create(n,{id:C(e,"u1"),name:"Alice",age:31,tenantId:"tenant-1",isActive:!0,email:"alice@example.com"}),await r.create(n,{id:C(e,"u2"),name:"Bob",age:24,tenantId:"tenant-1",isActive:!1,email:"bob@example.com"}),await r.bulkCreate(n,[{id:C(e,"u3"),name:"Carla",age:29,tenantId:"tenant-2",isActive:!0,email:"carla@example.com"},{id:C(e,"u4"),name:"Dian",age:22,tenantId:"tenant-2",isActive:!0}]),await r.bulkCreate(i,[{id:C(e,"p1"),userId:C(e,"u1"),nickname:"alice-nick"},{id:C(e,"p2"),userId:C(e,"u3"),nickname:"carla-nick"}]);let s=await r.get(n,C(e,"u1"));T((s==null?void 0:s.name)==="Alice","Expected get(table, id) to return Alice");let a=await r.query(n,{filters:{tenantId:"tenant-1"},sort:[{field:"age",direction:"desc"}]});T(a.length===2,`Expected 2 tenant-1 users, got ${a.length}`),T(a[0].age>=a[1].age,"Expected sorted by age desc");let c={and:[{field:"tenantId",value:"tenant-2"},{field:"isActive",value:!0}]},l=await r.query(n,{filters:c,sort:[{field:"name",direction:"asc"}]});T(l.length===2,`Expected 2 active tenant-2 users, got ${l.length}`);let h={filters:{and:[{field:"id",value:C(e,"u2")},{field:"tenantId",value:"tenant-1"}]}},f=await r.get(n,h);T((f==null?void 0:f.name)==="Bob","Expected get(table, options) to resolve Bob");let u=await r.update(n,C(e,"u1"),{age:32});T(u.age===32,`Expected age updated to 32, got ${u.age}`);let m=await r.bulkUpdate(n,[{id:C(e,"u3"),updates:{age:30}},{id:C(e,"u4"),updates:{age:23}}]);T(m.length===2,`Expected 2 bulk-updated rows, got ${m.length}`);let A=await r.query(n,{sort:[{field:"age",direction:"asc"}],limit:2,offset:1});T(A.length===2,`Expected 2 paged rows, got ${A.length}`);let d=await r.query(n,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:i,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:C(e,"u1")},resultShape:"flat"});T(d.length===1,`Expected one projected flat row, got ${d.length}`),T(((w=d[0])==null?void 0:w.t0_id)===C(e,"u1"),"Expected flat projected key t0_id"),T(((v=d[0])==null?void 0:v.p_nickname)==="alice-nick","Expected flat projected key p_nickname");let g=await r.query(n,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:i,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:C(e,"u1")},resultShape:"nested"});T(g.length===1,`Expected one projected nested row, got ${g.length}`),T(((X=(D=g[0])==null?void 0:D.t0)==null?void 0:X.id)===C(e,"u1"),"Expected nested row t0.id"),T(((et=(tt=g[0])==null?void 0:tt.p)==null?void 0:et.nickname)==="alice-nick","Expected nested row p.nickname");try{throw await r.transaction(async S=>{throw await S.create(n,{id:C(e,"tx_rollback"),name:"TxRollback",age:40,tenantId:"tenant-1",isActive:!0}),new Error("rollback-intent")}),new Error("Expected transaction rollback to throw")}catch(S){let rt=S instanceof Error?S.message:String(S);T(rt.includes("rollback-intent"),`Expected rollback-intent error, got ${rt}`)}let p=await r.get(n,C(e,"tx_rollback"));T(p===null,"Expected rolled back record to not exist"),await r.delete(n,C(e,"u2"));let E=await r.get(n,C(e,"u2"));T(E===null,"Expected deleted record to be null")}var N=class{constructor(t,e){this.extensions=new Map;var n,i,o,s,a,c,l,h,f,u,m,A,d;this.platformAdapter=(n=e.platformAdapter)==null?void 0:n.call(e,t),this.dbAdapter=(i=e.dbAdapter)==null?void 0:i.call(e,t),this.loggerAdapter=(o=e.loggerAdapter)==null?void 0:o.call(e,t),this.httpAdapter=(s=e.httpAdapter)==null?void 0:s.call(e,t),this.httpRetryPolicy=(c=(a=e.httpRetryPolicy)==null?void 0:a.call(e,t))!=null?c:new _(t),this.socketAdapter=(l=e.socketAdapter)==null?void 0:l.call(e,t),this.encryptionAdapter=(h=e.encryptionAdapter)==null?void 0:h.call(e,t),this.checksumAdapter=(u=(f=e.checksumAdapter)==null?void 0:f.call(e,t))!=null?u:new k(t),this.activitySink=(A=(m=e.activitySink)==null?void 0:m.call(e,t))!=null?A:new P(t);for(let[g,p]of Object.entries((d=e.extensions)!=null?d:{}))this.extensions.set(g,p(t))}getExtension(t){return this.extensions.get(t)}clear(){this.extensions.clear()}};function lt(r){return!!r&&typeof r.shutdown=="function"}var L=class{constructor(){this.correlationCounter=0;this.started=!1;this.pluginsLoaded=!1;this.pendingPlugins=[];this.hooks={}}static builder(){return new O}setHooks(t){this.hooks={...this.hooks,...t}}use(t,e,n=[]){if(!t.trim())throw new Error("plugin name is required");return this.pendingPlugins.some(i=>i.name===t)?this:(this.pendingPlugins.push({name:t,init:e,deps:n}),this)}async init(t={runMigrations:!0,useSeedData:!1}){if(!this.registry)throw new Error("CoreRuntime registry is not initialized. Call builder().build() first.");if(t.runMigrations!==!1&&this.hooks.runMigrations&&await this.hooks.runMigrations(this),this.hooks.onInit&&await this.hooks.onInit(this),!this.domainServices&&this.hooks.createDomainServices&&(this.domainServices=await this.hooks.createDomainServices(this)),!this.integrationServices&&this.hooks.createIntegrationServices&&(this.integrationServices=await this.hooks.createIntegrationServices(this)),!this.pluginsLoaded){let i=this.resolvePluginLevels();for(let o of i)await Promise.all(o.map(s=>s.init(this)));this.pluginsLoaded=!0}t.useSeedData===!0&&this.hooks.runSeed&&await this.hooks.runSeed(this)}async start(t={}){if(this.started)throw new Error("CoreRuntime already started");try{await this.init(t),this.started=!0}catch(e){throw this.started=!1,e}}async stop(){var t;this.started&&(this.hooks.onStop&&await this.hooks.onStop(this),lt(this.integrationServices)&&await this.integrationServices.shutdown(),lt(this.domainServices)&&await this.domainServices.shutdown(),(t=this.registry)==null||t.clear(),this.started=!1)}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.pendingPlugins=[],this.pluginsLoaded=!1,this.hooks={}}async restart(){let t=[...this.pendingPlugins],e={...this.hooks};await this.reset(),this.pendingPlugins=t,this.hooks=e,await this.start()}isStarted(){return this.started}createCorrelationId(t="cid"){return this.correlationCounter+=1,`${t}-${Date.now()}-${this.correlationCounter}`}logInfo(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logInfo(t,e)}logWarn(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logWarn(t,e)}logError(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logError(t,e)}async emitActivity(t){var e;(e=this.registry)!=null&&e.activitySink&&await this.registry.activitySink.publish(t)}resolvePluginLevels(){var s,a,c;if(this.pendingPlugins.length===0)return[];let t=new Map,e=new Map,n=new Map;for(let l of this.pendingPlugins){if(t.has(l.name))throw new Error(`Duplicate plugin name: ${l.name}`);t.set(l.name,[]),e.set(l.name,0),n.set(l.name,l)}for(let l of this.pendingPlugins)for(let h of l.deps){if(!t.has(h))throw new Error(`Plugin "${l.name}" depends on unknown plugin "${h}"`);t.get(h).push(l.name),e.set(l.name,((s=e.get(l.name))!=null?s:0)+1)}let i=[],o=Array.from(e.entries()).filter(([,l])=>l===0).map(([l])=>l);for(;o.length>0;){let l=o.map(f=>n.get(f));i.push(l);let h=[];for(let f of o)for(let u of(a=t.get(f))!=null?a:[]){let m=((c=e.get(u))!=null?c:0)-1;e.set(u,m),m===0&&h.push(u)}o=h}if(i.flat().length!==this.pendingPlugins.length)throw new Error("Circular dependency detected among plugins");return i}},O=class{constructor(){this.runtime=new L;this.adapterOptions={};this.hooks={}}withPlatformAdapter(t){return this.adapterOptions.platformAdapter=t,this}withDbAdapter(t){return this.adapterOptions.dbAdapter=t,this}withHttpAdapter(t){return this.adapterOptions.httpAdapter=t,this}withHttpRetryPolicy(t){return this.adapterOptions.httpRetryPolicy=t,this}withSocketAdapter(t){return this.adapterOptions.socketAdapter=t,this}withEncryptionAdapter(t){return this.adapterOptions.encryptionAdapter=t,this}withChecksumAdapter(t){return this.adapterOptions.checksumAdapter=t,this}withActivitySink(t){return this.adapterOptions.activitySink=t,this}withLoggerAdapter(t){return this.adapterOptions.loggerAdapter=t,this}withExtension(t,e){var n;return this.adapterOptions.extensions=(n=this.adapterOptions.extensions)!=null?n:{},this.adapterOptions.extensions[t]=e,this}withHooks(t){return this.hooks={...this.hooks,...t},this}build(){return this.runtime.setHooks(this.hooks),this.runtime.registry=new N(this.runtime,this.adapterOptions),this.runtime}};function Pt(r){let t=r,e=new Set,n=(i,o)=>{for(let s of e)s(i,o)};return{getState(){return t},setState(i){let o=t;return t=typeof i=="function"?i(t):{...t,...i},n(t,o),t},reset(i){let o=t;return t=i!=null?i:r,n(t,o),t},subscribe(i){return e.add(i),()=>{e.delete(i)}}}}function Dt(r){return{getState:r.getState,subscribe:r.subscribe}}function Ft(){return new Date().toISOString()}function Nt(r){let t=0;return()=>(t+=1,`${r}-${Date.now()}-${t}`)}function Lt(r){return JSON.parse(JSON.stringify(r))}function Ot(r){if(r.length!==0)return r.length===1?r[0]:{and:r}}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export * from './contracts/ChecksumPrimitives';
|
|
|
13
13
|
export * from './contracts/ResponseEnvelope';
|
|
14
14
|
export * from './contracts/ContractVersioning';
|
|
15
15
|
export * from './contracts/CrossDomainPrimitives';
|
|
16
|
+
export * from './contracts/CompliancePrimitives';
|
|
16
17
|
export * from './defaults/InMemoryDbAdapter';
|
|
17
18
|
export * from './defaults/ConsoleLoggerAdapter';
|
|
18
19
|
export * from './defaults/DefaultHttpAdapter';
|
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var V=class{constructor(t){}getEnvVar(t){let e=globalThis.process;if(typeof e!="undefined"&&e.env)return e.env[t]}isOnline(){return typeof globalThis.navigator!="undefined"&&typeof globalThis.navigator.onLine!="undefined"?!!globalThis.navigator.onLine:!0}async hashPin(t){return`sha256:${t}`}async verifyPin(t,e){return await this.hashPin(t)===e}};async function K(i){i<=0||await new Promise(t=>setTimeout(t,i))}async function nt(i,t,e={}){var s;let r=e.policy,n=(s=e.sleep)!=null?s:K,o=1;for(;;)try{let a=await i.request(t);if(!r)return a;let c={request:t,attempt:o,response:a};if(!r.shouldRetry(c))return a;let l=Math.max(0,r.nextDelayMs(c));await n(l),o+=1}catch(a){if(!r)throw a;let c={request:t,attempt:o,error:a};if(!r.shouldRetry(c))throw a;let l=Math.max(0,r.nextDelayMs(c));await n(l),o+=1}}function L(i){return String(i||"").trim().toLowerCase()}function ot(i,t){return L(i)===L(t)}function X(i){return typeof(i==null?void 0:i.error)=="object"&&i!==null}function at(i){if(X(i))throw new Error(i.error.message||i.error.code);return i.data}function lt(i,t,e){return e===i?!0:t.includes(e)}var $=class{constructor(){this.schema={version:0,tables:[]};this.data={};this.tableNameResolver=t=>t;this.transactionDepth=0;this.snapshots=[]}setTableNameResolver(t){this.tableNameResolver=t}resolveTableName(t){return this.tableNameResolver(t)}async setUpWithSchema(t){this.schema={...t},this.data={},t.tables.forEach(e=>{this.data[e.name]=[]})}normalizeForComparison(t){if(t instanceof Date)return t.getTime();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t==null)return t;if(Array.isArray(t))return t.map(e=>this.normalizeForComparison(e));if(typeof t=="object"&&t!==null)try{return JSON.stringify(t)}catch{return String(t)}return t}evalValueExpr(t,e,r,n="t0"){if(r.type==="column"){let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}if(r.type==="literal")return this.normalizeForComparison(r.value);throw new Error(`Unsupported ValueExpression type: ${r.type}`)}buildFieldCondition(t,e){if("field"in t){let n={type:"column",tableAlias:t.alias||e,field:t.field},o={type:"literal",value:t.value};return{left:n,operator:t.operator||"=",right:o,...t.operator==="BETWEEN"?{}:{likeMode:t.likeMode}}}if("left"in t)return t;throw new Error("Invalid FieldCondition")}matchFilterExpression(t,e,r,n="t0"){if(r&&typeof r=="object"&&!Array.isArray(r)&&"and"in r)return r.and.every(o=>this.matchFilterExpression(t,e,o,n));if(r&&typeof r=="object"&&!Array.isArray(r)&&"or"in r)return r.or.some(o=>this.matchFilterExpression(t,e,o,n));if(r!==null&&typeof r=="object"&&!Array.isArray(r)){if("left"in r||"field"in r){let o=this.buildFieldCondition(r,n),s=this.evalValueExpr(t,e,o.left,n),a=this.evalValueExpr(t,e,o.right,n);if(o.operator==="IS NULL")return s==null;if(o.operator==="IS NOT NULL")return s!=null;if(o.operator==="IN"||o.operator==="NOT IN"){if(!Array.isArray(a))throw new Error("IN/NOT IN requires array on right side");let c=a.includes(s);return o.operator==="IN"?c:!c}switch(o.operator){case"=":return s===a;case"!=":return s!==a;case"<":return s<a;case"<=":return s<=a;case">":return s>a;case">=":return s>=a;case"LIKE":{if(typeof s!="string"||typeof a!="string")return!1;let c=a.replace(/%/g,".*").replace(/_/g,"."),l=o.likeMode;return new RegExp(`^${c}$`,l==="case-insensitive"?"i":"").test(s)}default:throw new Error(`Unsupported operator: ${o.operator}`)}}return Object.entries(r).every(([o,s])=>{let a=this.normalizeForComparison(t[o]),c=this.normalizeForComparison(s);return a===c})}throw new Error(`Invalid filter expression: ${JSON.stringify(r)}`)}simulateJoins(t,e,r){if(r.length===0)return e.map(o=>({record:o,joined:{}}));let n=[];for(let o of e){let s={},a=!0;for(let c of r){let l=this.resolveTableName(c.table),y=this.data[l]||[],u=null;if(c.conditions.length===1){let d=c.conditions[0];if(d.operator==="="&&d.left.type==="column"&&d.right.type==="column"){let g=d.left.tableAlias||"t0",A=d.right.tableAlias;if(g==="t0"&&A===c.alias){let m=d.left.field,h=d.right.field,p=o[m];u=y.find(b=>this.normalizeForComparison(b[h])===this.normalizeForComparison(p))}}}if(!u&&(c.type==="inner"||c.type===void 0)){a=!1;break}s[c.alias]=u||null}a&&n.push({record:o,joined:s})}return n}extractField(t,e,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(t[r]);let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}extractAggregateField(t,e,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(t[r]);let o=r.tableAlias||n,s=o===n?t:e[o]||{};return this.normalizeForComparison(s[r.field])}async getSchemaVersion(){return this.schema.version}async setSchemaVersion(t){this.schema.version=t}async addTable(t){let e=this.resolveTableName(t.name);this.data[e]||(this.data[e]=[]),this.schema.tables.find(r=>r.name===t.name)||this.schema.tables.push(t)}async addColumn(t,e){}async get(t,e){var o;let r=this.resolveTableName(t);if(typeof e=="string"){let a=(this.data[r]||[]).find(c=>c.id===e);return a||null}return(o=(await this.query(t,{...e,limit:1}))[0])!=null?o:null}async query(t,e={}){var y;let r=this.resolveTableName(t),n="t0",o=[...this.data[r]||[]],s=this.simulateJoins(r,o,e.joins||[]);if(e.filters&&(s=s.filter(({record:u,joined:d})=>this.matchFilterExpression(u,d,e.filters,n))),e.aggregates&&e.aggregates.length>0){let u={};for(let d of e.aggregates){let g=s;d.filter&&(g=g.filter(({record:p,joined:b})=>this.matchFilterExpression(p,b,d.filter,n)));let A=g.map(({record:p,joined:b})=>this.extractAggregateField(p,b,d.field,n)),m=A.map(p=>typeof p=="number"?p:Number(p)).filter(p=>Number.isFinite(p)),h=null;switch(d.function){case"COUNT":h=A.filter(p=>p!=null).length;break;case"SUM":h=m.reduce((p,b)=>p+b,0);break;case"AVG":h=m.length?m.reduce((p,b)=>p+b,0)/m.length:0;break;case"MIN":h=m.length?Math.min(...m):null;break;case"MAX":h=m.length?Math.max(...m):null;break;default:throw new Error(`Unsupported aggregate function: ${d.function}`)}u[d.as]=h}return[u]}let a=s.map(({record:u,joined:d})=>{var g;if(e.fields){if(((g=e.resultShape)!=null?g:"flat")==="nested"){let h={};for(let[p,b]of Object.entries(e.fields)){let w=p===n?u:d[p]||{},x={};for(let k of b)x[k]=w[k];h[p]=x}return h}let m={};for(let[h,p]of Object.entries(e.fields)){let b=h===n?u:d[h]||{};for(let w of p)m[`${h}_${w}`]=b[w]}return m}return u});e.sort&&e.sort.length>0&&a.sort((u,d)=>{for(let g of e.sort){let A=this.extractField(u,{},g.field,n),m=this.extractField(d,{},g.field,n);if(A<m)return g.direction==="asc"?-1:1;if(A>m)return g.direction==="asc"?1:-1}return 0});let c=(y=e.offset)!=null?y:0,l=e.limit!=null?c+e.limit:void 0;return a.slice(c,l)}async create(t,e){let r=this.resolveTableName(t);this.data[r]||(this.data[r]=[]);let n={...e};return this.data[r].push(n),n}async update(t,e,r){let n=this.resolveTableName(t),o=this.data[n]||[],s=o.findIndex(c=>c.id===e);if(s===-1)throw new Error(`Record not found: ${t} with id ${e}`);let a={...o[s],...r};return o[s]=a,a}async delete(t,e){let r=this.resolveTableName(t),n=this.data[r]||[],o=n.findIndex(s=>s.id===e);o>=0&&n.splice(o,1)}async bulkCreate(t,e){let r=this.resolveTableName(t);this.data[r]||(this.data[r]=[]);let n=[...this.data[r]];try{let o=[];for(let s of e){let a={...s};this.data[r].push(a),o.push(a)}return o}catch(o){throw this.data[r]=n,o}}async bulkUpdate(t,e){let r=this.resolveTableName(t),n=[...this.data[r]||[]];try{let o=[];for(let{id:s,updates:a}of e){let c=await this.update(t,s,a);o.push(c)}return o}catch(o){throw this.data[r]=n,o}}takeSnapshot(){let t={};for(let e in this.data)t[e]=[...this.data[e]];return t}async transaction(t){let e=this.transactionDepth===0;e&&this.snapshots.push(this.takeSnapshot()),this.transactionDepth++;try{let r=await t(this);return e&&this.snapshots.pop(),this.transactionDepth--,r}catch(r){if(e){let n=this.snapshots.pop();n&&(this.data=n)}throw this.transactionDepth--,r}}};var _=class{constructor(t){}logInfo(t,e){console.log(t,e)}logWarn(t,e){console.warn(t,e)}logError(t,e){console.error(t,e)}};function Y(i,t){if(!t||Object.keys(t).length===0)return i;let e=new URLSearchParams;for(let[n,o]of Object.entries(t))o!=null&&e.set(n,String(o));let r=e.toString();return r?i.includes("?")?`${i}&${r}`:`${i}?${r}`:i}var N=class{constructor(t){this.fetchImpl=t}async request(t){var s,a,c,l,y,u,d,g,A;let e=(s=this.fetchImpl)!=null?s:globalThis.fetch;if(typeof e!="function")throw new Error("DefaultHttpAdapter requires fetch implementation");let r=Y(t.url,t.query),n=typeof AbortController!="undefined"?new AbortController:null,o=n&&t.timeoutMs?setTimeout(()=>n.abort(),t.timeoutMs):null;try{let m=t.body!==void 0&&t.body!==null,h={...(a=t.headers)!=null?a:{}};m&&!h["content-type"]&&(h["content-type"]="application/json");let p=await e(r,{method:t.method,headers:h,body:m?JSON.stringify(t.body):void 0,signal:n==null?void 0:n.signal}),b={};(l=(c=p.headers)==null?void 0:c.forEach)==null||l.call(c,(k,T)=>{b[T.toLowerCase()]=k});let x=((y=b["content-type"])!=null?y:"").includes("application/json")?await((d=(u=p.json)==null?void 0:u.call(p))!=null?d:Promise.resolve(void 0)):await((A=(g=p.text)==null?void 0:g.call(p))!=null?A:Promise.resolve(""));return{status:p.status,headers:b,data:x}}finally{o&&clearTimeout(o)}}};var R=class{constructor(t){}shouldRetry(t){return!1}nextDelayMs(t){return 0}};var Z=[408,425,429,500,502,503,504],j=class{constructor(t={}){var e,r,n,o;this.maxAttempts=Math.max(1,(e=t.maxAttempts)!=null?e:3),this.baseDelayMs=Math.max(0,(r=t.baseDelayMs)!=null?r:250),this.maxDelayMs=Math.max(this.baseDelayMs,(n=t.maxDelayMs)!=null?n:3e3),this.retryableStatusCodes=new Set((o=t.retryableStatusCodes)!=null?o:Z)}shouldRetry(t){var r,n;if(t.attempt>=this.maxAttempts)return!1;if(t.error)return!0;let e=(n=(r=t.response)==null?void 0:r.status)!=null?n:0;return this.retryableStatusCodes.has(e)}nextDelayMs(t){let e=Math.max(0,t.attempt-1),r=this.baseDelayMs*Math.pow(2,e);return Math.min(this.maxDelayMs,r)}};var U=class{constructor(){this.connected=!1;this.listeners=new Map}async connect(t){this.connectionOptions=t,this.connected=!0}async disconnect(){this.connected=!1}subscribe(t,e){this.listeners.has(t)||this.listeners.set(t,new Set);let r=this.listeners.get(t);return r.add(e),()=>{r.delete(e),r.size===0&&this.listeners.delete(t)}}async publish(t,e){if(!this.connected)throw new Error(`InMemorySocketAdapter is not connected (event=${t})`);let r=this.listeners.get(t);if(!(!r||r.size===0))for(let n of r)n(e)}isConnected(){return this.connected}getConnectionOptions(){return this.connectionOptions}};var z=class{constructor(t){}configure(t){}createChannel(t){}localNotification(t){}};var q=class{constructor(t){}encrypt(t,e){return String(t)}decrypt(t,e){return String(t)}};var E=class{constructor(t){}compute(t){return""}verify(t,e){return String(e||"").trim()===""}};var C=class{constructor(t){}publish(t){}};var B=class{constructor(t){this.records=[]}publish(t){this.records.push(t)}getRecords(){return[...this.records]}clear(){this.records.length=0}};var J=class{constructor(t){}getDocumentPath(t){return t}async writeFile(t,e){throw new Error("exportAdapter.writeFile is not implemented for this platform")}async share(t){throw new Error("exportAdapter.share is not implemented for this platform")}};var W=class{constructor(t){this.map=new Map}getItem(t){var e;return(e=this.map.get(t))!=null?e:null}setItem(t,e){this.map.set(t,e)}removeItem(t){this.map.delete(t)}};var Q=[];async function Rt(i,t){if(typeof i.getSchemaVersion!="function"||typeof i.setSchemaVersion!="function"){let e="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw t.logError(new Error(e),{message:e}),new Error(e)}t.logInfo("Starting database migration process");try{let e=[...Q].sort((o,s)=>o.toVersion-s.toVersion),r=e.length>0?e[e.length-1].toVersion:0,n=await i.getSchemaVersion();if((n==null||n<0)&&(n=0),n>=r){t.logInfo(`Database is already up-to-date at v${n}`);return}t.logInfo(`Migrating database from v${n} to v${r}`);for(let o of e)o.toVersion>n&&(t.logInfo(`Applying migration: v${o.toVersion}`),await o.up(i),await i.setSchemaVersion(o.toVersion),n=o.toVersion);t.logInfo("Database migration completed successfully")}catch(e){throw t.logError(e,{message:"Database migration failed"}),e}}function v(i,t){if(!i)throw new Error(t)}function f(i,t){return`${i}-${t}`}function tt(i){let t=[{name:"id",type:"string"},{name:"name",type:"string"},{name:"age",type:"number"},{name:"tenantId",type:"string"},{name:"isActive",type:"boolean"}];return{name:`${i}_users`,columns:t,skipMetadataColumns:!0}}function et(i){let t=[{name:"id",type:"string"},{name:"userId",type:"string",isIndexed:!0},{name:"nickname",type:"string"}];return{name:`${i}_profiles`,columns:t,skipMetadataColumns:!0}}async function Ct(i,t={}){var w,x,k,T,H,F,M;let e=((w=t.prefix)!=null?w:`dbadapter_${Date.now()}`).replace(/[^a-zA-Z0-9_]/g,"_"),r=`${e}_users`,n=`${e}_profiles`;await i.setSchemaVersion(7);let o=await i.getSchemaVersion();v(o===7,`Expected schema version 7, got ${o}`),await i.addTable(tt(e)),await i.addTable(et(e)),await i.addColumn(r,{name:"email",type:"string",isOptional:!0}),await i.create(r,{id:f(e,"u1"),name:"Alice",age:31,tenantId:"tenant-1",isActive:!0,email:"alice@example.com"}),await i.create(r,{id:f(e,"u2"),name:"Bob",age:24,tenantId:"tenant-1",isActive:!1,email:"bob@example.com"}),await i.bulkCreate(r,[{id:f(e,"u3"),name:"Carla",age:29,tenantId:"tenant-2",isActive:!0,email:"carla@example.com"},{id:f(e,"u4"),name:"Dian",age:22,tenantId:"tenant-2",isActive:!0}]),await i.bulkCreate(n,[{id:f(e,"p1"),userId:f(e,"u1"),nickname:"alice-nick"},{id:f(e,"p2"),userId:f(e,"u3"),nickname:"carla-nick"}]);let s=await i.get(r,f(e,"u1"));v((s==null?void 0:s.name)==="Alice","Expected get(table, id) to return Alice");let a=await i.query(r,{filters:{tenantId:"tenant-1"},sort:[{field:"age",direction:"desc"}]});v(a.length===2,`Expected 2 tenant-1 users, got ${a.length}`),v(a[0].age>=a[1].age,"Expected sorted by age desc");let c={and:[{field:"tenantId",value:"tenant-2"},{field:"isActive",value:!0}]},l=await i.query(r,{filters:c,sort:[{field:"name",direction:"asc"}]});v(l.length===2,`Expected 2 active tenant-2 users, got ${l.length}`);let y={filters:{and:[{field:"id",value:f(e,"u2")},{field:"tenantId",value:"tenant-1"}]}},u=await i.get(r,y);v((u==null?void 0:u.name)==="Bob","Expected get(table, options) to resolve Bob");let d=await i.update(r,f(e,"u1"),{age:32});v(d.age===32,`Expected age updated to 32, got ${d.age}`);let g=await i.bulkUpdate(r,[{id:f(e,"u3"),updates:{age:30}},{id:f(e,"u4"),updates:{age:23}}]);v(g.length===2,`Expected 2 bulk-updated rows, got ${g.length}`);let A=await i.query(r,{sort:[{field:"age",direction:"asc"}],limit:2,offset:1});v(A.length===2,`Expected 2 paged rows, got ${A.length}`);let m=await i.query(r,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:n,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:f(e,"u1")},resultShape:"flat"});v(m.length===1,`Expected one projected flat row, got ${m.length}`),v(((x=m[0])==null?void 0:x.t0_id)===f(e,"u1"),"Expected flat projected key t0_id"),v(((k=m[0])==null?void 0:k.p_nickname)==="alice-nick","Expected flat projected key p_nickname");let h=await i.query(r,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:n,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:f(e,"u1")},resultShape:"nested"});v(h.length===1,`Expected one projected nested row, got ${h.length}`),v(((H=(T=h[0])==null?void 0:T.t0)==null?void 0:H.id)===f(e,"u1"),"Expected nested row t0.id"),v(((M=(F=h[0])==null?void 0:F.p)==null?void 0:M.nickname)==="alice-nick","Expected nested row p.nickname");try{throw await i.transaction(async S=>{throw await S.create(r,{id:f(e,"tx_rollback"),name:"TxRollback",age:40,tenantId:"tenant-1",isActive:!0}),new Error("rollback-intent")}),new Error("Expected transaction rollback to throw")}catch(S){let O=S instanceof Error?S.message:String(S);v(O.includes("rollback-intent"),`Expected rollback-intent error, got ${O}`)}let p=await i.get(r,f(e,"tx_rollback"));v(p===null,"Expected rolled back record to not exist"),await i.delete(r,f(e,"u2"));let b=await i.get(r,f(e,"u2"));v(b===null,"Expected deleted record to be null")}var P=class{constructor(t,e){this.extensions=new Map;var r,n,o,s,a,c,l,y,u,d,g,A,m;this.platformAdapter=(r=e.platformAdapter)==null?void 0:r.call(e,t),this.dbAdapter=(n=e.dbAdapter)==null?void 0:n.call(e,t),this.loggerAdapter=(o=e.loggerAdapter)==null?void 0:o.call(e,t),this.httpAdapter=(s=e.httpAdapter)==null?void 0:s.call(e,t),this.httpRetryPolicy=(c=(a=e.httpRetryPolicy)==null?void 0:a.call(e,t))!=null?c:new R(t),this.socketAdapter=(l=e.socketAdapter)==null?void 0:l.call(e,t),this.encryptionAdapter=(y=e.encryptionAdapter)==null?void 0:y.call(e,t),this.checksumAdapter=(d=(u=e.checksumAdapter)==null?void 0:u.call(e,t))!=null?d:new E(t),this.activitySink=(A=(g=e.activitySink)==null?void 0:g.call(e,t))!=null?A:new C(t);for(let[h,p]of Object.entries((m=e.extensions)!=null?m:{}))this.extensions.set(h,p(t))}getExtension(t){return this.extensions.get(t)}clear(){this.extensions.clear()}};function G(i){return!!i&&typeof i.shutdown=="function"}var D=class{constructor(){this.correlationCounter=0;this.started=!1;this.pluginsLoaded=!1;this.pendingPlugins=[];this.hooks={}}static builder(){return new I}setHooks(t){this.hooks={...this.hooks,...t}}use(t,e,r=[]){if(!t.trim())throw new Error("plugin name is required");return this.pendingPlugins.some(n=>n.name===t)?this:(this.pendingPlugins.push({name:t,init:e,deps:r}),this)}async init(t={runMigrations:!0,useSeedData:!1}){if(!this.registry)throw new Error("CoreRuntime registry is not initialized. Call builder().build() first.");if(t.runMigrations!==!1&&this.hooks.runMigrations&&await this.hooks.runMigrations(this),this.hooks.onInit&&await this.hooks.onInit(this),!this.domainServices&&this.hooks.createDomainServices&&(this.domainServices=await this.hooks.createDomainServices(this)),!this.integrationServices&&this.hooks.createIntegrationServices&&(this.integrationServices=await this.hooks.createIntegrationServices(this)),!this.pluginsLoaded){let n=this.resolvePluginLevels();for(let o of n)await Promise.all(o.map(s=>s.init(this)));this.pluginsLoaded=!0}t.useSeedData===!0&&this.hooks.runSeed&&await this.hooks.runSeed(this)}async start(t={}){if(this.started)throw new Error("CoreRuntime already started");try{await this.init(t),this.started=!0}catch(e){throw this.started=!1,e}}async stop(){var t;this.started&&(this.hooks.onStop&&await this.hooks.onStop(this),G(this.integrationServices)&&await this.integrationServices.shutdown(),G(this.domainServices)&&await this.domainServices.shutdown(),(t=this.registry)==null||t.clear(),this.started=!1)}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.pendingPlugins=[],this.pluginsLoaded=!1,this.hooks={}}async restart(){let t=[...this.pendingPlugins],e={...this.hooks};await this.reset(),this.pendingPlugins=t,this.hooks=e,await this.start()}isStarted(){return this.started}createCorrelationId(t="cid"){return this.correlationCounter+=1,`${t}-${Date.now()}-${this.correlationCounter}`}logInfo(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logInfo(t,e)}logWarn(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logWarn(t,e)}logError(t,e){var r,n;(n=(r=this.registry)==null?void 0:r.loggerAdapter)==null||n.logError(t,e)}async emitActivity(t){var e;(e=this.registry)!=null&&e.activitySink&&await this.registry.activitySink.publish(t)}resolvePluginLevels(){var s,a,c;if(this.pendingPlugins.length===0)return[];let t=new Map,e=new Map,r=new Map;for(let l of this.pendingPlugins){if(t.has(l.name))throw new Error(`Duplicate plugin name: ${l.name}`);t.set(l.name,[]),e.set(l.name,0),r.set(l.name,l)}for(let l of this.pendingPlugins)for(let y of l.deps){if(!t.has(y))throw new Error(`Plugin "${l.name}" depends on unknown plugin "${y}"`);t.get(y).push(l.name),e.set(l.name,((s=e.get(l.name))!=null?s:0)+1)}let n=[],o=Array.from(e.entries()).filter(([,l])=>l===0).map(([l])=>l);for(;o.length>0;){let l=o.map(u=>r.get(u));n.push(l);let y=[];for(let u of o)for(let d of(a=t.get(u))!=null?a:[]){let g=((c=e.get(d))!=null?c:0)-1;e.set(d,g),g===0&&y.push(d)}o=y}if(n.flat().length!==this.pendingPlugins.length)throw new Error("Circular dependency detected among plugins");return n}},I=class{constructor(){this.runtime=new D;this.adapterOptions={};this.hooks={}}withPlatformAdapter(t){return this.adapterOptions.platformAdapter=t,this}withDbAdapter(t){return this.adapterOptions.dbAdapter=t,this}withHttpAdapter(t){return this.adapterOptions.httpAdapter=t,this}withHttpRetryPolicy(t){return this.adapterOptions.httpRetryPolicy=t,this}withSocketAdapter(t){return this.adapterOptions.socketAdapter=t,this}withEncryptionAdapter(t){return this.adapterOptions.encryptionAdapter=t,this}withChecksumAdapter(t){return this.adapterOptions.checksumAdapter=t,this}withActivitySink(t){return this.adapterOptions.activitySink=t,this}withLoggerAdapter(t){return this.adapterOptions.loggerAdapter=t,this}withExtension(t,e){var r;return this.adapterOptions.extensions=(r=this.adapterOptions.extensions)!=null?r:{},this.adapterOptions.extensions[t]=e,this}withHooks(t){return this.hooks={...this.hooks,...t},this}build(){return this.runtime.setHooks(this.hooks),this.runtime.registry=new P(this.runtime,this.adapterOptions),this.runtime}};function Mt(i){let t=i,e=new Set,r=(n,o)=>{for(let s of e)s(n,o)};return{getState(){return t},setState(n){let o=t;return t=typeof n=="function"?n(t):{...t,...n},r(t,o),t},reset(n){let o=t;return t=n!=null?n:i,r(t,o),t},subscribe(n){return e.add(n),()=>{e.delete(n)}}}}function Ot(i){return{getState:i.getState,subscribe:i.subscribe}}function Lt(){return new Date().toISOString()}function $t(i){let t=0;return()=>(t+=1,`${i}-${Date.now()}-${t}`)}function _t(i){return JSON.parse(JSON.stringify(i))}function Nt(i){if(i.length!==0)return i.length===1?i[0]:{and:i}}export{_ as ConsoleLoggerAdapter,P as CoreAdapterRegistry,D as CoreRuntime,I as CoreRuntimeBuilder,J as DefaultExportAdapter,N as DefaultHttpAdapter,V as DefaultPlatformAdapter,j as ExponentialBackoffHttpPolicy,$ as InMemoryDbAdapter,U as InMemorySocketAdapter,B as MemoryActivitySink,W as MemoryStorageAdapter,R as NoRetryHttpPolicy,C as NoopActivitySink,E as NoopChecksumAdapter,q as NoopEncryptionAdapter,z as NoopNotificationAdapter,Rt as applyPendingMigrations,ot as areChecksumsEqual,Ot as asReadonlyStore,_t as cloneValue,Mt as createStore,nt as executeHttpRequestWithRetry,lt as isContractVersionCompatible,X as isFailureEnvelope,$t as makeIdFactory,Q as migrations,L as normalizeChecksum,Lt as nowIso,Ct as runDbAdapterContractHarness,Nt as toAndFilter,at as unwrap};
|
|
1
|
+
var $=class{constructor(t){}getEnvVar(t){let e=globalThis.process;if(typeof e!="undefined"&&e.env)return e.env[t]}isOnline(){return typeof globalThis.navigator!="undefined"&&typeof globalThis.navigator.onLine!="undefined"?!!globalThis.navigator.onLine:!0}async hashPin(t){return`sha256:${t}`}async verifyPin(t,e){return await this.hashPin(t)===e}};async function ot(r){r<=0||await new Promise(t=>setTimeout(t,r))}async function ht(r,t,e={}){var s;let n=e.policy,i=(s=e.sleep)!=null?s:ot,o=1;for(;;)try{let a=await r.request(t);if(!n)return a;let c={request:t,attempt:o,response:a};if(!n.shouldRetry(c))return a;let l=Math.max(0,n.nextDelayMs(c));await i(l),o+=1}catch(a){if(!n)throw a;let c={request:t,attempt:o,error:a};if(!n.shouldRetry(c))throw a;let l=Math.max(0,n.nextDelayMs(c));await i(l),o+=1}}function j(r){return String(r||"").trim().toLowerCase()}function At(r,t){return j(r)===j(t)}function st(r){return typeof(r==null?void 0:r.error)=="object"&&r!==null}function Ct(r){if(st(r))throw new Error(r.error.message||r.error.code);return r.data}function It(r,t,e){return e===r?!0:t.includes(e)}function y(r,t){if(typeof r!="string"||r.trim().length===0)throw new Error(t);return r.trim()}function x(r,t){let e=y(r,t);if(Number.isNaN(Date.parse(e)))throw new Error(t);return e}function I(r){if(typeof r!="string")return;let t=r.trim();return t.length>0?t:void 0}function k(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function at(r){return Object.keys(r).length>0}function v(r){return{tenantId:I(r==null?void 0:r.tenantId),branchId:I(r==null?void 0:r.branchId),domain:I(r==null?void 0:r.domain),domainId:I(r==null?void 0:r.domainId),ledgerProfileId:I(r==null?void 0:r.ledgerProfileId)}}function Q(r){let t=v(r);return["tenantId","branchId","domain","domainId","ledgerProfileId"].map(e=>t[e]).filter(Boolean).length}function ct(r,t){let e=v(r),n=v(t);for(let i of["tenantId","branchId","domain","domainId","ledgerProfileId"]){let o=e[i],s=n[i];if(o&&(!s||o!==s))return!1}return!0}function lt(r){var t;if(y(r.id,"COMPLIANCE_PROFILE_ID_REQUIRED"),y(r.profileType,"COMPLIANCE_PROFILE_TYPE_REQUIRED"),x(r.effectiveFrom,"COMPLIANCE_PROFILE_EFFECTIVE_FROM_INVALID"),r.createdAt!=null&&x(r.createdAt,"COMPLIANCE_PROFILE_CREATED_AT_INVALID"),r.updatedAt!=null&&x(r.updatedAt,"COMPLIANCE_PROFILE_UPDATED_AT_INVALID"),typeof r.isActive!="boolean")throw new Error("COMPLIANCE_PROFILE_IS_ACTIVE_REQUIRED");if(!k(r.config))throw new Error("COMPLIANCE_PROFILE_CONFIG_REQUIRED");v((t=r.scopeRef)!=null?t:{})}function Rt(r){var n,i,o;if(y(r.id,"COMPLIANCE_EVIDENCE_ID_REQUIRED"),y(r.evidenceType,"COMPLIANCE_EVIDENCE_TYPE_REQUIRED"),y(r.sourceDomain,"COMPLIANCE_EVIDENCE_SOURCE_DOMAIN_REQUIRED"),y(r.sourceReferenceType,"COMPLIANCE_EVIDENCE_SOURCE_REFERENCE_TYPE_REQUIRED"),y(r.sourceReferenceId,"COMPLIANCE_EVIDENCE_SOURCE_REFERENCE_ID_REQUIRED"),x(r.recordedAt,"COMPLIANCE_EVIDENCE_RECORDED_AT_INVALID"),!["draft","ready","rejected","archived"].includes(r.status))throw new Error("COMPLIANCE_EVIDENCE_STATUS_INVALID");let t=(n=r.artifactRef)!=null?n:null,e=(i=r.payloadRef)!=null?i:null;if(!t&&!e)throw new Error("COMPLIANCE_EVIDENCE_REFERENCE_REQUIRED");if(t){if(!k(t))throw new Error("COMPLIANCE_EVIDENCE_ARTIFACT_REF_INVALID");let s=I(t.artifactId),a=I(t.uri);if(!!!(s||a))throw new Error("COMPLIANCE_EVIDENCE_ARTIFACT_REF_INVALID")}if(e&&(!k(e)||!at(e)))throw new Error("COMPLIANCE_EVIDENCE_PAYLOAD_REF_INVALID");v((o=r.scopeRef)!=null?o:{})}function z(r){var n;if(y(r.artifactId,"COMPLIANCE_ARTIFACT_ID_REQUIRED"),y(r.artifactType,"COMPLIANCE_ARTIFACT_TYPE_REQUIRED"),y(r.sourceDomain,"COMPLIANCE_ARTIFACT_SOURCE_DOMAIN_REQUIRED"),y(r.contractVersion,"COMPLIANCE_ARTIFACT_CONTRACT_VERSION_REQUIRED"),x(r.generatedAt,"COMPLIANCE_ARTIFACT_GENERATED_AT_INVALID"),!["ready","superseded","revoked"].includes(r.status))throw new Error("COMPLIANCE_ARTIFACT_STATUS_INVALID");if(!Array.isArray(r.files)||r.files.length===0)throw new Error("COMPLIANCE_ARTIFACT_FILES_REQUIRED");let t=new Set,e=new Set;for(let i of r.files){let o=y(i.key,"COMPLIANCE_ARTIFACT_FILE_KEY_REQUIRED");if(t.has(o))throw new Error("COMPLIANCE_ARTIFACT_FILE_KEY_DUPLICATE");t.add(o);let s=y(i.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(e.has(s))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");if(e.add(s),y(i.contentType,"COMPLIANCE_ARTIFACT_FILE_CONTENT_TYPE_REQUIRED"),y(i.checksum,"COMPLIANCE_ARTIFACT_FILE_CHECKSUM_REQUIRED"),!Number.isFinite(i.byteLength)||i.byteLength<0)throw new Error("COMPLIANCE_ARTIFACT_FILE_SIZE_INVALID");if(i.recordCount!=null&&(!Number.isFinite(i.recordCount)||i.recordCount<0))throw new Error("COMPLIANCE_ARTIFACT_FILE_RECORD_COUNT_INVALID")}v((n=r.scopeRef)!=null?n:{})}function pt(r){if(z(r.contract),!k(r.files))throw new Error("COMPLIANCE_ARTIFACT_FILES_PAYLOAD_INVALID");let t=Object.entries(r.files),e=new Set;for(let n of r.contract.files){let i=y(n.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(e.has(i))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");e.add(i);let o=r.files[i];if(typeof o!="string")throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_MISSING");if(B(o)!==n.checksum)throw new Error("COMPLIANCE_ARTIFACT_FILE_CHECKSUM_MISMATCH");if(q(o)!==n.byteLength)throw new Error("COMPLIANCE_ARTIFACT_FILE_BYTE_LENGTH_MISMATCH")}if(t.length!==r.contract.files.length)throw new Error("COMPLIANCE_ARTIFACT_FILESET_SIZE_MISMATCH");for(let[n,i]of t){if(typeof n!="string"||n.trim().length===0)throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(typeof i!="string")throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_INVALID");if(!e.has(n))throw new Error("COMPLIANCE_ARTIFACT_FILE_PAYLOAD_EXTRA")}}function B(r){let t=2166136261;for(let e=0;e<r.length;e+=1)t^=r.charCodeAt(e),t=Math.imul(t,16777619);return`fnv1a32-${(t>>>0).toString(16).padStart(8,"0")}`}function q(r){var n;let t=globalThis.TextEncoder;if(t)return new t().encode(r).length;let e=0;for(let i of r){let o=(n=i.codePointAt(0))!=null?n:0;o<=127?e+=1:o<=2047?e+=2:o<=65535?e+=3:e+=4}return e}function wt(r){var a,c,l,h,f,u,m,A;if(!Array.isArray(r.files)||r.files.length===0)throw new Error("COMPLIANCE_ARTIFACT_FILES_REQUIRED");let t=[],e={},n=new Set,i=new Set;for(let d of r.files){let g=y(d.key,"COMPLIANCE_ARTIFACT_FILE_KEY_REQUIRED");if(n.has(g))throw new Error("COMPLIANCE_ARTIFACT_FILE_KEY_DUPLICATE");n.add(g);let p=y(d.fileName,"COMPLIANCE_ARTIFACT_FILE_NAME_REQUIRED");if(i.has(p))throw new Error("COMPLIANCE_ARTIFACT_FILE_NAME_DUPLICATE");i.add(p);let E=y(d.payload,"COMPLIANCE_ARTIFACT_FILE_PAYLOAD_REQUIRED"),b=(a=I(d.contentType))!=null?a:"application/octet-stream";e[p]=E,t.push({key:g,fileName:p,contentType:b,checksum:B(E),byteLength:q(E),recordCount:(c=d.recordCount)!=null?c:null})}let o={artifactId:y(r.artifactId,"COMPLIANCE_ARTIFACT_ID_REQUIRED"),scopeRef:v((l=r.scopeRef)!=null?l:{}),artifactType:y(r.artifactType,"COMPLIANCE_ARTIFACT_TYPE_REQUIRED"),sourceDomain:y(r.sourceDomain,"COMPLIANCE_ARTIFACT_SOURCE_DOMAIN_REQUIRED"),contractVersion:y(r.contractVersion,"COMPLIANCE_ARTIFACT_CONTRACT_VERSION_REQUIRED"),status:(h=r.status)!=null?h:"ready",generatedAt:(f=r.generatedAt)!=null?f:new Date().toISOString(),sourceReferenceType:(u=I(r.sourceReferenceType))!=null?u:null,sourceReferenceId:(m=I(r.sourceReferenceId))!=null?m:null,profileId:(A=I(r.profileId))!=null?A:null,files:t,summary:r.summary,tags:Array.isArray(r.tags)?r.tags.filter(d=>typeof d=="string"&&d.trim().length>0):[]};z(o);let s={contract:o,files:e};return pt(s),s}function vt(r,t){var i,o;let e=(i=t.effectiveAt)!=null?i:new Date().toISOString();if(Number.isNaN(Date.parse(e)))throw new Error("COMPLIANCE_PROFILE_EFFECTIVE_AT_INVALID");return(o=r.filter(s=>{var a;return lt(s),!s.isActive||Date.parse(s.effectiveFrom)>Date.parse(e)||t.profileType&&s.profileType!==t.profileType||t.regulatorKey!=null&&((a=s.regulatorKey)!=null?a:null)!==t.regulatorKey?!1:ct(s.scopeRef,t.scopeRef)}).sort((s,a)=>{var f,u,m,A;let c=Q(a.scopeRef)-Q(s.scopeRef);if(c!==0)return c;let l=Date.parse(a.effectiveFrom)-Date.parse(s.effectiveFrom);if(l!==0)return l;let h=Date.parse((u=(f=a.updatedAt)!=null?f:a.createdAt)!=null?u:a.effectiveFrom)-Date.parse((A=(m=s.updatedAt)!=null?m:s.createdAt)!=null?A:s.effectiveFrom);return h!==0?h:s.id.localeCompare(a.id)})[0])!=null?o:null}var Y=class{constructor(){this.schema={version:0,tables:[]};this.data={};this.tableNameResolver=t=>t;this.transactionDepth=0;this.snapshots=[]}setTableNameResolver(t){this.tableNameResolver=t}resolveTableName(t){return this.tableNameResolver(t)}async setUpWithSchema(t){this.schema={...t},this.data={},t.tables.forEach(e=>{this.data[e.name]=[]})}normalizeForComparison(t){if(t instanceof Date)return t.getTime();if(typeof t=="boolean")return t?1:0;if(typeof t=="string"||typeof t=="number"||t==null)return t;if(Array.isArray(t))return t.map(e=>this.normalizeForComparison(e));if(typeof t=="object"&&t!==null)try{return JSON.stringify(t)}catch{return String(t)}return t}evalValueExpr(t,e,n,i="t0"){if(n.type==="column"){let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}if(n.type==="literal")return this.normalizeForComparison(n.value);throw new Error(`Unsupported ValueExpression type: ${n.type}`)}buildFieldCondition(t,e){if("field"in t){let i={type:"column",tableAlias:t.alias||e,field:t.field},o={type:"literal",value:t.value};return{left:i,operator:t.operator||"=",right:o,...t.operator==="BETWEEN"?{}:{likeMode:t.likeMode}}}if("left"in t)return t;throw new Error("Invalid FieldCondition")}matchFilterExpression(t,e,n,i="t0"){if(n&&typeof n=="object"&&!Array.isArray(n)&&"and"in n)return n.and.every(o=>this.matchFilterExpression(t,e,o,i));if(n&&typeof n=="object"&&!Array.isArray(n)&&"or"in n)return n.or.some(o=>this.matchFilterExpression(t,e,o,i));if(n!==null&&typeof n=="object"&&!Array.isArray(n)){if("left"in n||"field"in n){let o=this.buildFieldCondition(n,i),s=this.evalValueExpr(t,e,o.left,i),a=this.evalValueExpr(t,e,o.right,i);if(o.operator==="IS NULL")return s==null;if(o.operator==="IS NOT NULL")return s!=null;if(o.operator==="IN"||o.operator==="NOT IN"){if(!Array.isArray(a))throw new Error("IN/NOT IN requires array on right side");let c=a.includes(s);return o.operator==="IN"?c:!c}switch(o.operator){case"=":return s===a;case"!=":return s!==a;case"<":return s<a;case"<=":return s<=a;case">":return s>a;case">=":return s>=a;case"LIKE":{if(typeof s!="string"||typeof a!="string")return!1;let c=a.replace(/%/g,".*").replace(/_/g,"."),l=o.likeMode;return new RegExp(`^${c}$`,l==="case-insensitive"?"i":"").test(s)}default:throw new Error(`Unsupported operator: ${o.operator}`)}}return Object.entries(n).every(([o,s])=>{let a=this.normalizeForComparison(t[o]),c=this.normalizeForComparison(s);return a===c})}throw new Error(`Invalid filter expression: ${JSON.stringify(n)}`)}simulateJoins(t,e,n){if(n.length===0)return e.map(o=>({record:o,joined:{}}));let i=[];for(let o of e){let s={},a=!0;for(let c of n){let l=this.resolveTableName(c.table),h=this.data[l]||[],f=null;if(c.conditions.length===1){let u=c.conditions[0];if(u.operator==="="&&u.left.type==="column"&&u.right.type==="column"){let m=u.left.tableAlias||"t0",A=u.right.tableAlias;if(m==="t0"&&A===c.alias){let d=u.left.field,g=u.right.field,p=o[d];f=h.find(E=>this.normalizeForComparison(E[g])===this.normalizeForComparison(p))}}}if(!f&&(c.type==="inner"||c.type===void 0)){a=!1;break}s[c.alias]=f||null}a&&i.push({record:o,joined:s})}return i}extractField(t,e,n,i="t0"){if(typeof n=="string")return this.normalizeForComparison(t[n]);let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}extractAggregateField(t,e,n,i="t0"){if(typeof n=="string")return this.normalizeForComparison(t[n]);let o=n.tableAlias||i,s=o===i?t:e[o]||{};return this.normalizeForComparison(s[n.field])}async getSchemaVersion(){return this.schema.version}async setSchemaVersion(t){this.schema.version=t}async addTable(t){let e=this.resolveTableName(t.name);this.data[e]||(this.data[e]=[]),this.schema.tables.find(n=>n.name===t.name)||this.schema.tables.push(t)}async addColumn(t,e){}async get(t,e){var o;let n=this.resolveTableName(t);if(typeof e=="string"){let a=(this.data[n]||[]).find(c=>c.id===e);return a||null}return(o=(await this.query(t,{...e,limit:1}))[0])!=null?o:null}async query(t,e={}){var h;let n=this.resolveTableName(t),i="t0",o=[...this.data[n]||[]],s=this.simulateJoins(n,o,e.joins||[]);if(e.filters&&(s=s.filter(({record:f,joined:u})=>this.matchFilterExpression(f,u,e.filters,i))),e.aggregates&&e.aggregates.length>0){let f={};for(let u of e.aggregates){let m=s;u.filter&&(m=m.filter(({record:p,joined:E})=>this.matchFilterExpression(p,E,u.filter,i)));let A=m.map(({record:p,joined:E})=>this.extractAggregateField(p,E,u.field,i)),d=A.map(p=>typeof p=="number"?p:Number(p)).filter(p=>Number.isFinite(p)),g=null;switch(u.function){case"COUNT":g=A.filter(p=>p!=null).length;break;case"SUM":g=d.reduce((p,E)=>p+E,0);break;case"AVG":g=d.length?d.reduce((p,E)=>p+E,0)/d.length:0;break;case"MIN":g=d.length?Math.min(...d):null;break;case"MAX":g=d.length?Math.max(...d):null;break;default:throw new Error(`Unsupported aggregate function: ${u.function}`)}f[u.as]=g}return[f]}let a=s.map(({record:f,joined:u})=>{var m;if(e.fields){if(((m=e.resultShape)!=null?m:"flat")==="nested"){let g={};for(let[p,E]of Object.entries(e.fields)){let b=p===i?f:u[p]||{},R={};for(let w of E)R[w]=b[w];g[p]=R}return g}let d={};for(let[g,p]of Object.entries(e.fields)){let E=g===i?f:u[g]||{};for(let b of p)d[`${g}_${b}`]=E[b]}return d}return f});e.sort&&e.sort.length>0&&a.sort((f,u)=>{for(let m of e.sort){let A=this.extractField(f,{},m.field,i),d=this.extractField(u,{},m.field,i);if(A<d)return m.direction==="asc"?-1:1;if(A>d)return m.direction==="asc"?1:-1}return 0});let c=(h=e.offset)!=null?h:0,l=e.limit!=null?c+e.limit:void 0;return a.slice(c,l)}async create(t,e){let n=this.resolveTableName(t);this.data[n]||(this.data[n]=[]);let i={...e};return this.data[n].push(i),i}async update(t,e,n){let i=this.resolveTableName(t),o=this.data[i]||[],s=o.findIndex(c=>c.id===e);if(s===-1)throw new Error(`Record not found: ${t} with id ${e}`);let a={...o[s],...n};return o[s]=a,a}async delete(t,e){let n=this.resolveTableName(t),i=this.data[n]||[],o=i.findIndex(s=>s.id===e);o>=0&&i.splice(o,1)}async bulkCreate(t,e){let n=this.resolveTableName(t);this.data[n]||(this.data[n]=[]);let i=[...this.data[n]];try{let o=[];for(let s of e){let a={...s};this.data[n].push(a),o.push(a)}return o}catch(o){throw this.data[n]=i,o}}async bulkUpdate(t,e){let n=this.resolveTableName(t),i=[...this.data[n]||[]];try{let o=[];for(let{id:s,updates:a}of e){let c=await this.update(t,s,a);o.push(c)}return o}catch(o){throw this.data[n]=i,o}}takeSnapshot(){let t={};for(let e in this.data)t[e]=[...this.data[e]];return t}async transaction(t){let e=this.transactionDepth===0;e&&this.snapshots.push(this.takeSnapshot()),this.transactionDepth++;try{let n=await t(this);return e&&this.snapshots.pop(),this.transactionDepth--,n}catch(n){if(e){let i=this.snapshots.pop();i&&(this.data=i)}throw this.transactionDepth--,n}}};var K=class{constructor(t){}logInfo(t,e){console.log(t,e)}logWarn(t,e){console.warn(t,e)}logError(t,e){console.error(t,e)}};function ut(r,t){if(!t||Object.keys(t).length===0)return r;let e=new URLSearchParams;for(let[i,o]of Object.entries(t))o!=null&&e.set(i,String(o));let n=e.toString();return n?r.includes("?")?`${r}&${n}`:`${r}?${n}`:r}var J=class{constructor(t){this.fetchImpl=t}async request(t){var s,a,c,l,h,f,u,m,A;let e=(s=this.fetchImpl)!=null?s:globalThis.fetch;if(typeof e!="function")throw new Error("DefaultHttpAdapter requires fetch implementation");let n=ut(t.url,t.query),i=typeof AbortController!="undefined"?new AbortController:null,o=i&&t.timeoutMs?setTimeout(()=>i.abort(),t.timeoutMs):null;try{let d=t.body!==void 0&&t.body!==null,g={...(a=t.headers)!=null?a:{}};d&&!g["content-type"]&&(g["content-type"]="application/json");let p=await e(n,{method:t.method,headers:g,body:d?JSON.stringify(t.body):void 0,signal:i==null?void 0:i.signal}),E={};(l=(c=p.headers)==null?void 0:c.forEach)==null||l.call(c,(w,_)=>{E[_.toLowerCase()]=w});let R=((h=E["content-type"])!=null?h:"").includes("application/json")?await((u=(f=p.json)==null?void 0:f.call(p))!=null?u:Promise.resolve(void 0)):await((A=(m=p.text)==null?void 0:m.call(p))!=null?A:Promise.resolve(""));return{status:p.status,headers:E,data:R}}finally{o&&clearTimeout(o)}}};var P=class{constructor(t){}shouldRetry(t){return!1}nextDelayMs(t){return 0}};var dt=[408,425,429,500,502,503,504],W=class{constructor(t={}){var e,n,i,o;this.maxAttempts=Math.max(1,(e=t.maxAttempts)!=null?e:3),this.baseDelayMs=Math.max(0,(n=t.baseDelayMs)!=null?n:250),this.maxDelayMs=Math.max(this.baseDelayMs,(i=t.maxDelayMs)!=null?i:3e3),this.retryableStatusCodes=new Set((o=t.retryableStatusCodes)!=null?o:dt)}shouldRetry(t){var n,i;if(t.attempt>=this.maxAttempts)return!1;if(t.error)return!0;let e=(i=(n=t.response)==null?void 0:n.status)!=null?i:0;return this.retryableStatusCodes.has(e)}nextDelayMs(t){let e=Math.max(0,t.attempt-1),n=this.baseDelayMs*Math.pow(2,e);return Math.min(this.maxDelayMs,n)}};var G=class{constructor(){this.connected=!1;this.listeners=new Map}async connect(t){this.connectionOptions=t,this.connected=!0}async disconnect(){this.connected=!1}subscribe(t,e){this.listeners.has(t)||this.listeners.set(t,new Set);let n=this.listeners.get(t);return n.add(e),()=>{n.delete(e),n.size===0&&this.listeners.delete(t)}}async publish(t,e){if(!this.connected)throw new Error(`InMemorySocketAdapter is not connected (event=${t})`);let n=this.listeners.get(t);if(!(!n||n.size===0))for(let i of n)i(e)}isConnected(){return this.connected}getConnectionOptions(){return this.connectionOptions}};var Z=class{constructor(t){}configure(t){}createChannel(t){}localNotification(t){}};var X=class{constructor(t){}encrypt(t,e){return String(t)}decrypt(t,e){return String(t)}};var D=class{constructor(t){}compute(t){return""}verify(t,e){return String(e||"").trim()===""}};var F=class{constructor(t){}publish(t){}};var tt=class{constructor(t){this.records=[]}publish(t){this.records.push(t)}getRecords(){return[...this.records]}clear(){this.records.length=0}};var et=class{constructor(t){}getDocumentPath(t){return t}async writeFile(t,e){throw new Error("exportAdapter.writeFile is not implemented for this platform")}async share(t){throw new Error("exportAdapter.share is not implemented for this platform")}};var rt=class{constructor(t){this.map=new Map}getItem(t){var e;return(e=this.map.get(t))!=null?e:null}setItem(t,e){this.map.set(t,e)}removeItem(t){this.map.delete(t)}};var nt=[];async function Qt(r,t){if(typeof r.getSchemaVersion!="function"||typeof r.setSchemaVersion!="function"){let e="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw t.logError(new Error(e),{message:e}),new Error(e)}t.logInfo("Starting database migration process");try{let e=[...nt].sort((o,s)=>o.toVersion-s.toVersion),n=e.length>0?e[e.length-1].toVersion:0,i=await r.getSchemaVersion();if((i==null||i<0)&&(i=0),i>=n){t.logInfo(`Database is already up-to-date at v${i}`);return}t.logInfo(`Migrating database from v${i} to v${n}`);for(let o of e)o.toVersion>i&&(t.logInfo(`Applying migration: v${o.toVersion}`),await o.up(r),await r.setSchemaVersion(o.toVersion),i=o.toVersion);t.logInfo("Database migration completed successfully")}catch(e){throw t.logError(e,{message:"Database migration failed"}),e}}function T(r,t){if(!r)throw new Error(t)}function C(r,t){return`${r}-${t}`}function ft(r){let t=[{name:"id",type:"string"},{name:"name",type:"string"},{name:"age",type:"number"},{name:"tenantId",type:"string"},{name:"isActive",type:"boolean"}];return{name:`${r}_users`,columns:t,skipMetadataColumns:!0}}function mt(r){let t=[{name:"id",type:"string"},{name:"userId",type:"string",isIndexed:!0},{name:"nickname",type:"string"}];return{name:`${r}_profiles`,columns:t,skipMetadataColumns:!0}}async function Bt(r,t={}){var b,R,w,_,M,V,H;let e=((b=t.prefix)!=null?b:`dbadapter_${Date.now()}`).replace(/[^a-zA-Z0-9_]/g,"_"),n=`${e}_users`,i=`${e}_profiles`;await r.setSchemaVersion(7);let o=await r.getSchemaVersion();T(o===7,`Expected schema version 7, got ${o}`),await r.addTable(ft(e)),await r.addTable(mt(e)),await r.addColumn(n,{name:"email",type:"string",isOptional:!0}),await r.create(n,{id:C(e,"u1"),name:"Alice",age:31,tenantId:"tenant-1",isActive:!0,email:"alice@example.com"}),await r.create(n,{id:C(e,"u2"),name:"Bob",age:24,tenantId:"tenant-1",isActive:!1,email:"bob@example.com"}),await r.bulkCreate(n,[{id:C(e,"u3"),name:"Carla",age:29,tenantId:"tenant-2",isActive:!0,email:"carla@example.com"},{id:C(e,"u4"),name:"Dian",age:22,tenantId:"tenant-2",isActive:!0}]),await r.bulkCreate(i,[{id:C(e,"p1"),userId:C(e,"u1"),nickname:"alice-nick"},{id:C(e,"p2"),userId:C(e,"u3"),nickname:"carla-nick"}]);let s=await r.get(n,C(e,"u1"));T((s==null?void 0:s.name)==="Alice","Expected get(table, id) to return Alice");let a=await r.query(n,{filters:{tenantId:"tenant-1"},sort:[{field:"age",direction:"desc"}]});T(a.length===2,`Expected 2 tenant-1 users, got ${a.length}`),T(a[0].age>=a[1].age,"Expected sorted by age desc");let c={and:[{field:"tenantId",value:"tenant-2"},{field:"isActive",value:!0}]},l=await r.query(n,{filters:c,sort:[{field:"name",direction:"asc"}]});T(l.length===2,`Expected 2 active tenant-2 users, got ${l.length}`);let h={filters:{and:[{field:"id",value:C(e,"u2")},{field:"tenantId",value:"tenant-1"}]}},f=await r.get(n,h);T((f==null?void 0:f.name)==="Bob","Expected get(table, options) to resolve Bob");let u=await r.update(n,C(e,"u1"),{age:32});T(u.age===32,`Expected age updated to 32, got ${u.age}`);let m=await r.bulkUpdate(n,[{id:C(e,"u3"),updates:{age:30}},{id:C(e,"u4"),updates:{age:23}}]);T(m.length===2,`Expected 2 bulk-updated rows, got ${m.length}`);let A=await r.query(n,{sort:[{field:"age",direction:"asc"}],limit:2,offset:1});T(A.length===2,`Expected 2 paged rows, got ${A.length}`);let d=await r.query(n,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:i,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:C(e,"u1")},resultShape:"flat"});T(d.length===1,`Expected one projected flat row, got ${d.length}`),T(((R=d[0])==null?void 0:R.t0_id)===C(e,"u1"),"Expected flat projected key t0_id"),T(((w=d[0])==null?void 0:w.p_nickname)==="alice-nick","Expected flat projected key p_nickname");let g=await r.query(n,{fields:{t0:["id","name"],p:["nickname"]},joins:[{table:i,alias:"p",type:"left",conditions:[{left:{type:"column",tableAlias:"t0",field:"id"},operator:"=",right:{type:"column",tableAlias:"p",field:"userId"}}]}],filters:{field:"id",value:C(e,"u1")},resultShape:"nested"});T(g.length===1,`Expected one projected nested row, got ${g.length}`),T(((M=(_=g[0])==null?void 0:_.t0)==null?void 0:M.id)===C(e,"u1"),"Expected nested row t0.id"),T(((H=(V=g[0])==null?void 0:V.p)==null?void 0:H.nickname)==="alice-nick","Expected nested row p.nickname");try{throw await r.transaction(async S=>{throw await S.create(n,{id:C(e,"tx_rollback"),name:"TxRollback",age:40,tenantId:"tenant-1",isActive:!0}),new Error("rollback-intent")}),new Error("Expected transaction rollback to throw")}catch(S){let U=S instanceof Error?S.message:String(S);T(U.includes("rollback-intent"),`Expected rollback-intent error, got ${U}`)}let p=await r.get(n,C(e,"tx_rollback"));T(p===null,"Expected rolled back record to not exist"),await r.delete(n,C(e,"u2"));let E=await r.get(n,C(e,"u2"));T(E===null,"Expected deleted record to be null")}var N=class{constructor(t,e){this.extensions=new Map;var n,i,o,s,a,c,l,h,f,u,m,A,d;this.platformAdapter=(n=e.platformAdapter)==null?void 0:n.call(e,t),this.dbAdapter=(i=e.dbAdapter)==null?void 0:i.call(e,t),this.loggerAdapter=(o=e.loggerAdapter)==null?void 0:o.call(e,t),this.httpAdapter=(s=e.httpAdapter)==null?void 0:s.call(e,t),this.httpRetryPolicy=(c=(a=e.httpRetryPolicy)==null?void 0:a.call(e,t))!=null?c:new P(t),this.socketAdapter=(l=e.socketAdapter)==null?void 0:l.call(e,t),this.encryptionAdapter=(h=e.encryptionAdapter)==null?void 0:h.call(e,t),this.checksumAdapter=(u=(f=e.checksumAdapter)==null?void 0:f.call(e,t))!=null?u:new D(t),this.activitySink=(A=(m=e.activitySink)==null?void 0:m.call(e,t))!=null?A:new F(t);for(let[g,p]of Object.entries((d=e.extensions)!=null?d:{}))this.extensions.set(g,p(t))}getExtension(t){return this.extensions.get(t)}clear(){this.extensions.clear()}};function it(r){return!!r&&typeof r.shutdown=="function"}var L=class{constructor(){this.correlationCounter=0;this.started=!1;this.pluginsLoaded=!1;this.pendingPlugins=[];this.hooks={}}static builder(){return new O}setHooks(t){this.hooks={...this.hooks,...t}}use(t,e,n=[]){if(!t.trim())throw new Error("plugin name is required");return this.pendingPlugins.some(i=>i.name===t)?this:(this.pendingPlugins.push({name:t,init:e,deps:n}),this)}async init(t={runMigrations:!0,useSeedData:!1}){if(!this.registry)throw new Error("CoreRuntime registry is not initialized. Call builder().build() first.");if(t.runMigrations!==!1&&this.hooks.runMigrations&&await this.hooks.runMigrations(this),this.hooks.onInit&&await this.hooks.onInit(this),!this.domainServices&&this.hooks.createDomainServices&&(this.domainServices=await this.hooks.createDomainServices(this)),!this.integrationServices&&this.hooks.createIntegrationServices&&(this.integrationServices=await this.hooks.createIntegrationServices(this)),!this.pluginsLoaded){let i=this.resolvePluginLevels();for(let o of i)await Promise.all(o.map(s=>s.init(this)));this.pluginsLoaded=!0}t.useSeedData===!0&&this.hooks.runSeed&&await this.hooks.runSeed(this)}async start(t={}){if(this.started)throw new Error("CoreRuntime already started");try{await this.init(t),this.started=!0}catch(e){throw this.started=!1,e}}async stop(){var t;this.started&&(this.hooks.onStop&&await this.hooks.onStop(this),it(this.integrationServices)&&await this.integrationServices.shutdown(),it(this.domainServices)&&await this.domainServices.shutdown(),(t=this.registry)==null||t.clear(),this.started=!1)}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.pendingPlugins=[],this.pluginsLoaded=!1,this.hooks={}}async restart(){let t=[...this.pendingPlugins],e={...this.hooks};await this.reset(),this.pendingPlugins=t,this.hooks=e,await this.start()}isStarted(){return this.started}createCorrelationId(t="cid"){return this.correlationCounter+=1,`${t}-${Date.now()}-${this.correlationCounter}`}logInfo(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logInfo(t,e)}logWarn(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logWarn(t,e)}logError(t,e){var n,i;(i=(n=this.registry)==null?void 0:n.loggerAdapter)==null||i.logError(t,e)}async emitActivity(t){var e;(e=this.registry)!=null&&e.activitySink&&await this.registry.activitySink.publish(t)}resolvePluginLevels(){var s,a,c;if(this.pendingPlugins.length===0)return[];let t=new Map,e=new Map,n=new Map;for(let l of this.pendingPlugins){if(t.has(l.name))throw new Error(`Duplicate plugin name: ${l.name}`);t.set(l.name,[]),e.set(l.name,0),n.set(l.name,l)}for(let l of this.pendingPlugins)for(let h of l.deps){if(!t.has(h))throw new Error(`Plugin "${l.name}" depends on unknown plugin "${h}"`);t.get(h).push(l.name),e.set(l.name,((s=e.get(l.name))!=null?s:0)+1)}let i=[],o=Array.from(e.entries()).filter(([,l])=>l===0).map(([l])=>l);for(;o.length>0;){let l=o.map(f=>n.get(f));i.push(l);let h=[];for(let f of o)for(let u of(a=t.get(f))!=null?a:[]){let m=((c=e.get(u))!=null?c:0)-1;e.set(u,m),m===0&&h.push(u)}o=h}if(i.flat().length!==this.pendingPlugins.length)throw new Error("Circular dependency detected among plugins");return i}},O=class{constructor(){this.runtime=new L;this.adapterOptions={};this.hooks={}}withPlatformAdapter(t){return this.adapterOptions.platformAdapter=t,this}withDbAdapter(t){return this.adapterOptions.dbAdapter=t,this}withHttpAdapter(t){return this.adapterOptions.httpAdapter=t,this}withHttpRetryPolicy(t){return this.adapterOptions.httpRetryPolicy=t,this}withSocketAdapter(t){return this.adapterOptions.socketAdapter=t,this}withEncryptionAdapter(t){return this.adapterOptions.encryptionAdapter=t,this}withChecksumAdapter(t){return this.adapterOptions.checksumAdapter=t,this}withActivitySink(t){return this.adapterOptions.activitySink=t,this}withLoggerAdapter(t){return this.adapterOptions.loggerAdapter=t,this}withExtension(t,e){var n;return this.adapterOptions.extensions=(n=this.adapterOptions.extensions)!=null?n:{},this.adapterOptions.extensions[t]=e,this}withHooks(t){return this.hooks={...this.hooks,...t},this}build(){return this.runtime.setHooks(this.hooks),this.runtime.registry=new N(this.runtime,this.adapterOptions),this.runtime}};function Gt(r){let t=r,e=new Set,n=(i,o)=>{for(let s of e)s(i,o)};return{getState(){return t},setState(i){let o=t;return t=typeof i=="function"?i(t):{...t,...i},n(t,o),t},reset(i){let o=t;return t=i!=null?i:r,n(t,o),t},subscribe(i){return e.add(i),()=>{e.delete(i)}}}}function Zt(r){return{getState:r.getState,subscribe:r.subscribe}}function te(){return new Date().toISOString()}function ee(r){let t=0;return()=>(t+=1,`${r}-${Date.now()}-${t}`)}function re(r){return JSON.parse(JSON.stringify(r))}function ne(r){if(r.length!==0)return r.length===1?r[0]:{and:r}}export{K as ConsoleLoggerAdapter,N as CoreAdapterRegistry,L as CoreRuntime,O as CoreRuntimeBuilder,et as DefaultExportAdapter,J as DefaultHttpAdapter,$ as DefaultPlatformAdapter,W as ExponentialBackoffHttpPolicy,Y as InMemoryDbAdapter,G as InMemorySocketAdapter,tt as MemoryActivitySink,rt as MemoryStorageAdapter,P as NoRetryHttpPolicy,F as NoopActivitySink,D as NoopChecksumAdapter,X as NoopEncryptionAdapter,Z as NoopNotificationAdapter,Qt as applyPendingMigrations,At as areChecksumsEqual,Zt as asReadonlyStore,pt as assertComplianceExportArtifactBundleIntegrity,Rt as assertValidComplianceEvidenceItemContract,z as assertValidComplianceExportArtifactContract,lt as assertValidComplianceProfileContract,wt as buildComplianceExportArtifactBundle,re as cloneValue,Q as countComplianceScopeSpecificity,Gt as createStore,ht as executeHttpRequestWithRetry,It as isContractVersionCompatible,st as isFailureEnvelope,ee as makeIdFactory,ct as matchesComplianceScopeRef,nt as migrations,j as normalizeChecksum,v as normalizeComplianceScopeRef,te as nowIso,vt as resolveEffectiveComplianceProfile,Bt as runDbAdapterContractHarness,ne as toAndFilter,Ct as unwrap};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ofcore",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.2",
|
|
4
4
|
"description": "Lightweight runtime core for offline-first TypeScript apps.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Agus Made",
|
|
@@ -21,12 +21,13 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
|
-
"clean": "rimraf dist",
|
|
25
|
-
"build": "npm run clean && tsc -b && node esbuild.config.js",
|
|
24
|
+
"clean": "rimraf dist \"src/**/*.js\" \"src/**/*.js.map\"",
|
|
25
|
+
"build": "npm run clean && tsc -b && node esbuild.config.js && npm run verify:no-src-build-artifacts",
|
|
26
26
|
"bundle": "node esbuild.config.js",
|
|
27
27
|
"verify:contract": "node ./scripts/verify-contract-surface.js",
|
|
28
28
|
"verify:surface": "node ./scripts/verify-contract-surface.js",
|
|
29
|
-
"verify:logic": "node ./scripts/verify-logic-behavior.js && node ./scripts/verify-dbadapter-harness.js && node ./scripts/verify-core-runtime.js && node ./scripts/verify-store.js && node ./scripts/verify-adapter-conformance.js && node ./scripts/verify-adapter-default-vs-override.js",
|
|
29
|
+
"verify:logic": "node ./scripts/verify-logic-behavior.js && node ./scripts/verify-compliance-primitives.js && node ./scripts/verify-dbadapter-harness.js && node ./scripts/verify-core-runtime.js && node ./scripts/verify-store.js && node ./scripts/verify-adapter-conformance.js && node ./scripts/verify-adapter-default-vs-override.js",
|
|
30
|
+
"verify:no-src-build-artifacts": "node ./scripts/verify-no-src-build-artifacts.js",
|
|
30
31
|
"verify:adapter-conformance": "node ./scripts/verify-adapter-conformance.js",
|
|
31
32
|
"verify:adapter-default-vs-override": "node ./scripts/verify-adapter-default-vs-override.js",
|
|
32
33
|
"verify:dbadapter-harness": "node ./scripts/verify-dbadapter-harness.js",
|