@originals/sdk 1.4.2 → 1.4.3

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.
Files changed (212) hide show
  1. package/package.json +4 -1
  2. package/.eslintrc.json +0 -33
  3. package/src/adapters/FeeOracleMock.ts +0 -9
  4. package/src/adapters/index.ts +0 -5
  5. package/src/adapters/providers/OrdHttpProvider.ts +0 -126
  6. package/src/adapters/providers/OrdMockProvider.ts +0 -101
  7. package/src/adapters/types.ts +0 -66
  8. package/src/bitcoin/BitcoinManager.ts +0 -330
  9. package/src/bitcoin/BroadcastClient.ts +0 -54
  10. package/src/bitcoin/OrdinalsClient.ts +0 -119
  11. package/src/bitcoin/PSBTBuilder.ts +0 -106
  12. package/src/bitcoin/fee-calculation.ts +0 -38
  13. package/src/bitcoin/providers/OrdNodeProvider.ts +0 -92
  14. package/src/bitcoin/providers/OrdinalsProvider.ts +0 -56
  15. package/src/bitcoin/providers/types.ts +0 -59
  16. package/src/bitcoin/transactions/commit.ts +0 -465
  17. package/src/bitcoin/transactions/index.ts +0 -13
  18. package/src/bitcoin/transfer.ts +0 -43
  19. package/src/bitcoin/utxo-selection.ts +0 -322
  20. package/src/bitcoin/utxo.ts +0 -113
  21. package/src/contexts/credentials-v1.json +0 -237
  22. package/src/contexts/credentials-v2-examples.json +0 -5
  23. package/src/contexts/credentials-v2.json +0 -340
  24. package/src/contexts/credentials.json +0 -237
  25. package/src/contexts/data-integrity-v2.json +0 -81
  26. package/src/contexts/dids.json +0 -58
  27. package/src/contexts/ed255192020.json +0 -93
  28. package/src/contexts/ordinals-plus.json +0 -23
  29. package/src/contexts/originals.json +0 -22
  30. package/src/core/OriginalsSDK.ts +0 -416
  31. package/src/crypto/Multikey.ts +0 -194
  32. package/src/crypto/Signer.ts +0 -254
  33. package/src/crypto/noble-init.ts +0 -121
  34. package/src/did/BtcoDidResolver.ts +0 -227
  35. package/src/did/DIDManager.ts +0 -694
  36. package/src/did/Ed25519Verifier.ts +0 -68
  37. package/src/did/KeyManager.ts +0 -236
  38. package/src/did/WebVHManager.ts +0 -498
  39. package/src/did/createBtcoDidDocument.ts +0 -59
  40. package/src/did/providers/OrdinalsClientProviderAdapter.ts +0 -68
  41. package/src/events/EventEmitter.ts +0 -222
  42. package/src/events/index.ts +0 -19
  43. package/src/events/types.ts +0 -331
  44. package/src/examples/basic-usage.ts +0 -78
  45. package/src/examples/create-module-original.ts +0 -435
  46. package/src/examples/full-lifecycle-flow.ts +0 -514
  47. package/src/examples/run.ts +0 -60
  48. package/src/index.ts +0 -150
  49. package/src/kinds/KindRegistry.ts +0 -290
  50. package/src/kinds/index.ts +0 -74
  51. package/src/kinds/types.ts +0 -470
  52. package/src/kinds/validators/AgentValidator.ts +0 -257
  53. package/src/kinds/validators/AppValidator.ts +0 -211
  54. package/src/kinds/validators/DatasetValidator.ts +0 -242
  55. package/src/kinds/validators/DocumentValidator.ts +0 -311
  56. package/src/kinds/validators/MediaValidator.ts +0 -269
  57. package/src/kinds/validators/ModuleValidator.ts +0 -225
  58. package/src/kinds/validators/base.ts +0 -276
  59. package/src/kinds/validators/index.ts +0 -12
  60. package/src/lifecycle/BatchOperations.ts +0 -373
  61. package/src/lifecycle/LifecycleManager.ts +0 -2126
  62. package/src/lifecycle/OriginalsAsset.ts +0 -524
  63. package/src/lifecycle/ProvenanceQuery.ts +0 -280
  64. package/src/lifecycle/ResourceVersioning.ts +0 -163
  65. package/src/migration/MigrationManager.ts +0 -527
  66. package/src/migration/audit/AuditLogger.ts +0 -176
  67. package/src/migration/checkpoint/CheckpointManager.ts +0 -112
  68. package/src/migration/checkpoint/CheckpointStorage.ts +0 -101
  69. package/src/migration/index.ts +0 -33
  70. package/src/migration/operations/BaseMigration.ts +0 -126
  71. package/src/migration/operations/PeerToBtcoMigration.ts +0 -105
  72. package/src/migration/operations/PeerToWebvhMigration.ts +0 -62
  73. package/src/migration/operations/WebvhToBtcoMigration.ts +0 -105
  74. package/src/migration/rollback/RollbackManager.ts +0 -170
  75. package/src/migration/state/StateMachine.ts +0 -92
  76. package/src/migration/state/StateTracker.ts +0 -156
  77. package/src/migration/types.ts +0 -344
  78. package/src/migration/validation/BitcoinValidator.ts +0 -107
  79. package/src/migration/validation/CredentialValidator.ts +0 -62
  80. package/src/migration/validation/DIDCompatibilityValidator.ts +0 -151
  81. package/src/migration/validation/LifecycleValidator.ts +0 -64
  82. package/src/migration/validation/StorageValidator.ts +0 -79
  83. package/src/migration/validation/ValidationPipeline.ts +0 -213
  84. package/src/resources/ResourceManager.ts +0 -655
  85. package/src/resources/index.ts +0 -21
  86. package/src/resources/types.ts +0 -202
  87. package/src/storage/LocalStorageAdapter.ts +0 -61
  88. package/src/storage/MemoryStorageAdapter.ts +0 -29
  89. package/src/storage/StorageAdapter.ts +0 -25
  90. package/src/storage/index.ts +0 -3
  91. package/src/types/bitcoin.ts +0 -98
  92. package/src/types/common.ts +0 -92
  93. package/src/types/credentials.ts +0 -88
  94. package/src/types/did.ts +0 -31
  95. package/src/types/external-shims.d.ts +0 -53
  96. package/src/types/index.ts +0 -7
  97. package/src/types/network.ts +0 -175
  98. package/src/utils/EventLogger.ts +0 -298
  99. package/src/utils/Logger.ts +0 -322
  100. package/src/utils/MetricsCollector.ts +0 -358
  101. package/src/utils/bitcoin-address.ts +0 -130
  102. package/src/utils/cbor.ts +0 -12
  103. package/src/utils/encoding.ts +0 -127
  104. package/src/utils/hash.ts +0 -6
  105. package/src/utils/retry.ts +0 -46
  106. package/src/utils/satoshi-validation.ts +0 -196
  107. package/src/utils/serialization.ts +0 -96
  108. package/src/utils/telemetry.ts +0 -40
  109. package/src/utils/validation.ts +0 -119
  110. package/src/vc/CredentialManager.ts +0 -918
  111. package/src/vc/Issuer.ts +0 -100
  112. package/src/vc/Verifier.ts +0 -47
  113. package/src/vc/cryptosuites/bbs.ts +0 -253
  114. package/src/vc/cryptosuites/bbsSimple.ts +0 -21
  115. package/src/vc/cryptosuites/eddsa.ts +0 -99
  116. package/src/vc/documentLoader.ts +0 -67
  117. package/src/vc/proofs/data-integrity.ts +0 -33
  118. package/src/vc/utils/jsonld.ts +0 -18
  119. package/tests/__mocks__/bbs-signatures.js +0 -17
  120. package/tests/__mocks__/mf-base58.js +0 -24
  121. package/tests/fixtures/did-documents.ts +0 -247
  122. package/tests/index.test.ts +0 -21
  123. package/tests/integration/BatchOperations.test.ts +0 -531
  124. package/tests/integration/CompleteLifecycle.e2e.test.ts +0 -735
  125. package/tests/integration/CredentialManager.test.ts +0 -42
  126. package/tests/integration/DIDManager.test.ts +0 -41
  127. package/tests/integration/DidPeerToWebVhFlow.test.ts +0 -351
  128. package/tests/integration/Events.test.ts +0 -435
  129. package/tests/integration/Lifecycle.transfer.btco.integration.test.ts +0 -25
  130. package/tests/integration/LifecycleManager.test.ts +0 -21
  131. package/tests/integration/MultikeyFlow.test.ts +0 -52
  132. package/tests/integration/TelemetryIntegration.test.ts +0 -395
  133. package/tests/integration/WebVhPublish.test.ts +0 -48
  134. package/tests/integration/createTypedOriginal.test.ts +0 -379
  135. package/tests/integration/migration/peer-to-webvh.test.ts +0 -172
  136. package/tests/manual/test-commit-creation.ts +0 -323
  137. package/tests/mocks/MockKeyStore.ts +0 -38
  138. package/tests/mocks/adapters/MemoryStorageAdapter.ts +0 -24
  139. package/tests/mocks/adapters/MockFeeOracle.ts +0 -11
  140. package/tests/mocks/adapters/MockOrdinalsProvider.ts +0 -76
  141. package/tests/mocks/adapters/OrdMockProvider.test.ts +0 -176
  142. package/tests/mocks/adapters/index.ts +0 -6
  143. package/tests/performance/BatchOperations.perf.test.ts +0 -403
  144. package/tests/performance/logging.perf.test.ts +0 -336
  145. package/tests/sdk.test.ts +0 -43
  146. package/tests/security/bitcoin-penetration-tests.test.ts +0 -622
  147. package/tests/setup.bun.ts +0 -69
  148. package/tests/setup.jest.ts +0 -23
  149. package/tests/stress/batch-operations-stress.test.ts +0 -571
  150. package/tests/unit/adapters/FeeOracleMock.test.ts +0 -40
  151. package/tests/unit/bitcoin/BitcoinManager.test.ts +0 -293
  152. package/tests/unit/bitcoin/BroadcastClient.test.ts +0 -52
  153. package/tests/unit/bitcoin/OrdNodeProvider.test.ts +0 -53
  154. package/tests/unit/bitcoin/OrdinalsClient.test.ts +0 -381
  155. package/tests/unit/bitcoin/OrdinalsClientProvider.test.ts +0 -102
  156. package/tests/unit/bitcoin/PSBTBuilder.test.ts +0 -84
  157. package/tests/unit/bitcoin/fee-calculation.test.ts +0 -261
  158. package/tests/unit/bitcoin/transactions/commit.test.ts +0 -649
  159. package/tests/unit/bitcoin/transfer.test.ts +0 -31
  160. package/tests/unit/bitcoin/utxo-selection-new.test.ts +0 -502
  161. package/tests/unit/bitcoin/utxo.more.test.ts +0 -39
  162. package/tests/unit/bitcoin/utxo.selection.test.ts +0 -38
  163. package/tests/unit/core/OriginalsSDK.test.ts +0 -152
  164. package/tests/unit/crypto/Multikey.test.ts +0 -206
  165. package/tests/unit/crypto/Signer.test.ts +0 -408
  166. package/tests/unit/did/BtcoDidResolver.test.ts +0 -611
  167. package/tests/unit/did/DIDManager.more.test.ts +0 -43
  168. package/tests/unit/did/DIDManager.test.ts +0 -185
  169. package/tests/unit/did/Ed25519Verifier.test.ts +0 -160
  170. package/tests/unit/did/KeyManager.test.ts +0 -452
  171. package/tests/unit/did/OrdinalsClientProviderAdapter.test.ts +0 -45
  172. package/tests/unit/did/WebVHManager.test.ts +0 -435
  173. package/tests/unit/did/createBtcoDidDocument.test.ts +0 -67
  174. package/tests/unit/did/providers/OrdinalsClientProviderAdapter.test.ts +0 -159
  175. package/tests/unit/events/EventEmitter.test.ts +0 -407
  176. package/tests/unit/kinds/KindRegistry.test.ts +0 -329
  177. package/tests/unit/kinds/types.test.ts +0 -409
  178. package/tests/unit/kinds/validators.test.ts +0 -651
  179. package/tests/unit/lifecycle/BatchOperations.test.ts +0 -527
  180. package/tests/unit/lifecycle/LifecycleManager.cleanapi.test.ts +0 -441
  181. package/tests/unit/lifecycle/LifecycleManager.keymanagement.test.ts +0 -312
  182. package/tests/unit/lifecycle/LifecycleManager.prov.test.ts +0 -18
  183. package/tests/unit/lifecycle/LifecycleManager.test.ts +0 -213
  184. package/tests/unit/lifecycle/LifecycleManager.transfer.unit.test.ts +0 -30
  185. package/tests/unit/lifecycle/OriginalsAsset.test.ts +0 -176
  186. package/tests/unit/lifecycle/ProvenanceQuery.test.ts +0 -577
  187. package/tests/unit/lifecycle/ResourceVersioning.test.ts +0 -651
  188. package/tests/unit/resources/ResourceManager.test.ts +0 -740
  189. package/tests/unit/storage/MemoryStorageAdapter.test.ts +0 -93
  190. package/tests/unit/types/network.test.ts +0 -255
  191. package/tests/unit/utils/EventIntegration.test.ts +0 -384
  192. package/tests/unit/utils/Logger.test.ts +0 -473
  193. package/tests/unit/utils/MetricsCollector.test.ts +0 -358
  194. package/tests/unit/utils/bitcoin-address.test.ts +0 -250
  195. package/tests/unit/utils/cbor.test.ts +0 -35
  196. package/tests/unit/utils/encoding.test.ts +0 -318
  197. package/tests/unit/utils/hash.test.ts +0 -12
  198. package/tests/unit/utils/retry.test.ts +0 -100
  199. package/tests/unit/utils/satoshi-validation.test.ts +0 -354
  200. package/tests/unit/utils/serialization.test.ts +0 -124
  201. package/tests/unit/utils/telemetry.test.ts +0 -52
  202. package/tests/unit/utils/validation.test.ts +0 -141
  203. package/tests/unit/vc/CredentialManager.helpers.test.ts +0 -527
  204. package/tests/unit/vc/CredentialManager.test.ts +0 -487
  205. package/tests/unit/vc/Issuer.test.ts +0 -107
  206. package/tests/unit/vc/Verifier.test.ts +0 -525
  207. package/tests/unit/vc/bbs.test.ts +0 -282
  208. package/tests/unit/vc/cryptosuites/eddsa.test.ts +0 -398
  209. package/tests/unit/vc/documentLoader.test.ts +0 -121
  210. package/tests/unit/vc/proofs/data-integrity.test.ts +0 -24
  211. package/tsconfig.json +0 -31
  212. package/tsconfig.test.json +0 -15
@@ -1,524 +0,0 @@
1
- import {
2
- AssetResource,
3
- DIDDocument,
4
- VerifiableCredential,
5
- LayerType
6
- } from '../types';
7
- import { validateDIDDocument, validateCredential, hashResource } from '../utils/validation';
8
- import { CredentialManager } from '../vc/CredentialManager';
9
- import { DIDManager } from '../did/DIDManager';
10
- import { ProvenanceQuery, Migration, Transfer } from './ProvenanceQuery';
11
- import { EventEmitter } from '../events/EventEmitter';
12
- import type { EventHandler, EventTypeMap } from '../events/types';
13
- import { ResourceVersionManager, ResourceHistory } from './ResourceVersioning';
14
-
15
- export interface ProvenanceChain {
16
- createdAt: string;
17
- creator: string;
18
- txid?: string;
19
- migrations: Array<{
20
- from: LayerType;
21
- to: LayerType;
22
- timestamp: string;
23
- transactionId?: string;
24
- inscriptionId?: string;
25
- satoshi?: string;
26
- commitTxId?: string;
27
- revealTxId?: string;
28
- feeRate?: number;
29
- }>;
30
- transfers: Array<{
31
- from: string;
32
- to: string;
33
- timestamp: string;
34
- transactionId: string;
35
- }>;
36
- resourceUpdates: Array<{
37
- resourceId: string;
38
- fromVersion: number;
39
- toVersion: number;
40
- fromHash: string;
41
- toHash: string;
42
- timestamp: string;
43
- changes?: string;
44
- }>;
45
- }
46
-
47
- export class OriginalsAsset {
48
- public readonly id: string;
49
- public readonly resources: AssetResource[];
50
- public readonly did: DIDDocument;
51
- public readonly credentials: VerifiableCredential[];
52
- public currentLayer: LayerType;
53
- public bindings?: Record<string, string>;
54
- private provenance: ProvenanceChain;
55
- private eventEmitter: EventEmitter;
56
- private versionManager: ResourceVersionManager;
57
-
58
- constructor(
59
- resources: AssetResource[],
60
- did: DIDDocument,
61
- credentials: VerifiableCredential[]
62
- ) {
63
- this.id = did.id;
64
- this.resources = resources;
65
- this.did = did;
66
- this.credentials = credentials;
67
- this.currentLayer = this.determineCurrentLayer(did.id);
68
- this.provenance = {
69
- createdAt: new Date().toISOString(),
70
- creator: did.id,
71
- migrations: [],
72
- transfers: [],
73
- resourceUpdates: []
74
- };
75
- this.eventEmitter = new EventEmitter();
76
- this.versionManager = new ResourceVersionManager();
77
-
78
- // Initialize version manager with existing resources
79
- // Group resources by ID and sort each group by version to handle unsorted persisted data
80
- const resourcesByIdMap = new Map<string, AssetResource[]>();
81
- for (const resource of resources) {
82
- const existing = resourcesByIdMap.get(resource.id) || [];
83
- existing.push(resource);
84
- resourcesByIdMap.set(resource.id, existing);
85
- }
86
-
87
- // Process each resource ID's versions in sorted order
88
- for (const [resourceId, resourceVersions] of resourcesByIdMap.entries()) {
89
- // Sort by version number (ascending)
90
- const sorted = resourceVersions.sort((a, b) => {
91
- const versionA = a.version || 1;
92
- const versionB = b.version || 1;
93
- return versionA - versionB;
94
- });
95
-
96
- // Add versions in correct order to version manager
97
- for (const resource of sorted) {
98
- this.versionManager.addVersion(
99
- resource.id,
100
- resource.hash,
101
- resource.contentType,
102
- resource.previousVersionHash
103
- );
104
- }
105
- }
106
- }
107
-
108
- async migrate(
109
- toLayer: LayerType,
110
- details?: {
111
- transactionId?: string;
112
- inscriptionId?: string;
113
- satoshi?: string;
114
- commitTxId?: string;
115
- revealTxId?: string;
116
- feeRate?: number;
117
- }
118
- ): Promise<void> {
119
- // Handle migration between layers
120
- const validTransitions: Record<LayerType, LayerType[]> = {
121
- 'did:peer': ['did:webvh', 'did:btco'],
122
- 'did:webvh': ['did:btco'],
123
- 'did:btco': [] // No further migrations possible
124
- };
125
-
126
- if (!validTransitions[this.currentLayer].includes(toLayer)) {
127
- throw new Error(`Invalid migration from ${this.currentLayer} to ${toLayer}`);
128
- }
129
-
130
- const fromLayer = this.currentLayer;
131
-
132
- this.provenance.migrations.push({
133
- from: fromLayer,
134
- to: toLayer,
135
- timestamp: new Date().toISOString(),
136
- transactionId: details?.transactionId,
137
- inscriptionId: details?.inscriptionId,
138
- satoshi: details?.satoshi,
139
- commitTxId: details?.commitTxId,
140
- revealTxId: details?.revealTxId,
141
- feeRate: details?.feeRate
142
- });
143
- if (details?.transactionId) {
144
- this.provenance.txid = details.transactionId;
145
- }
146
- this.currentLayer = toLayer;
147
-
148
- // Emit migration event and await handlers
149
- await this.eventEmitter.emit({
150
- type: 'asset:migrated',
151
- timestamp: new Date().toISOString(),
152
- asset: {
153
- id: this.id,
154
- fromLayer,
155
- toLayer
156
- },
157
- details
158
- });
159
- }
160
-
161
- getProvenance(): ProvenanceChain {
162
- return this.provenance;
163
- }
164
-
165
- async recordTransfer(from: string, to: string, transactionId: string): Promise<void> {
166
- this.provenance.transfers.push({
167
- from,
168
- to,
169
- timestamp: new Date().toISOString(),
170
- transactionId
171
- });
172
- this.provenance.txid = transactionId;
173
-
174
- // Emit transfer event and await handlers
175
- await this.eventEmitter.emit({
176
- type: 'asset:transferred',
177
- timestamp: new Date().toISOString(),
178
- asset: {
179
- id: this.id,
180
- layer: this.currentLayer
181
- },
182
- from,
183
- to,
184
- transactionId
185
- });
186
- }
187
-
188
- /**
189
- * Query provenance with fluent API
190
- */
191
- queryProvenance(): ProvenanceQuery {
192
- return new ProvenanceQuery(this.provenance);
193
- }
194
-
195
- /**
196
- * Get all migrations to a specific layer
197
- */
198
- getMigrationsToLayer(layer: LayerType): Migration[] {
199
- return this.provenance.migrations.filter(m => m.to === layer);
200
- }
201
-
202
- /**
203
- * Get all transfers from an address
204
- */
205
- getTransfersFrom(address: string): Transfer[] {
206
- return this.provenance.transfers.filter(t => t.from === address);
207
- }
208
-
209
- /**
210
- * Get all transfers to an address
211
- */
212
- getTransfersTo(address: string): Transfer[] {
213
- return this.provenance.transfers.filter(t => t.to === address);
214
- }
215
-
216
- /**
217
- * Get provenance summary
218
- */
219
- getProvenanceSummary(): {
220
- created: string;
221
- creator: string;
222
- currentLayer: LayerType;
223
- migrationCount: number;
224
- transferCount: number;
225
- lastActivity: string;
226
- } {
227
- const lastMigration = this.provenance.migrations[this.provenance.migrations.length - 1];
228
- const lastTransfer = this.provenance.transfers[this.provenance.transfers.length - 1];
229
-
230
- return {
231
- created: this.provenance.createdAt,
232
- creator: this.id,
233
- currentLayer: this.currentLayer,
234
- migrationCount: this.provenance.migrations.length,
235
- transferCount: this.provenance.transfers.length,
236
- lastActivity: lastTransfer?.timestamp || lastMigration?.timestamp || this.provenance.createdAt
237
- };
238
- }
239
-
240
- /**
241
- * Find migration or transfer by transaction ID
242
- */
243
- findByTransactionId(txId: string): Migration | Transfer | null {
244
- const migration = this.provenance.migrations.find(m => m.transactionId === txId);
245
- if (migration) return migration;
246
-
247
- const transfer = this.provenance.transfers.find(t => t.transactionId === txId);
248
- return transfer || null;
249
- }
250
-
251
- /**
252
- * Find migration by inscription ID
253
- */
254
- findByInscriptionId(inscriptionId: string): Migration | null {
255
- return this.provenance.migrations.find(m => m.inscriptionId === inscriptionId) || null;
256
- }
257
-
258
- async verify(deps?: {
259
- didManager?: DIDManager;
260
- credentialManager?: CredentialManager;
261
- fetch?: (url: string) => Promise<{ arrayBuffer: () => Promise<ArrayBuffer> }>;
262
- }): Promise<boolean> {
263
- try {
264
- // 1) DID Document validation (structure + supported method via validateDID)
265
- if (!validateDIDDocument(this.did)) {
266
- return false;
267
- }
268
-
269
- // 2) Resources integrity
270
- for (const res of this.resources) {
271
- if (!res || typeof res.id !== 'string' || typeof res.type !== 'string' || typeof res.contentType !== 'string') {
272
- return false;
273
- }
274
- if (typeof res.hash !== 'string' || !/[0-9a-f]+/i.test(res.hash)) {
275
- return false;
276
- }
277
-
278
- // If inline content is present, verify by hashing it
279
- if (typeof res.content === 'string') {
280
- const data = Buffer.from(res.content, 'utf8');
281
- const computed = hashResource(data);
282
- const expected = (res.hash || '').toLowerCase();
283
- if (computed.toLowerCase() !== expected) {
284
- return false;
285
- }
286
- continue;
287
- }
288
-
289
- // If URL present and fetch is provided, attempt to fetch and hash
290
- if (typeof res.url === 'string' && deps?.fetch) {
291
- try {
292
- const response = await deps.fetch(res.url);
293
- const buf = Buffer.from(await response.arrayBuffer());
294
- const computed = hashResource(buf);
295
- const expected = (res.hash || '').toLowerCase();
296
- if (computed.toLowerCase() !== expected) {
297
- return false;
298
- }
299
- } catch {
300
- // On fetch error, treat as unverifiable but do not fail the entire asset
301
- // Fall back to structural validation only
302
- }
303
- }
304
- }
305
-
306
- // 3) Credentials validation
307
- for (const cred of this.credentials) {
308
- if (!validateCredential(cred)) {
309
- return false;
310
- }
311
- }
312
-
313
- // If a credentialManager with didManager is provided, verify each credential cryptographically
314
- if (deps?.credentialManager && deps.credentialManager instanceof CredentialManager && deps?.didManager) {
315
- for (const cred of this.credentials) {
316
- const ok = await deps.credentialManager.verifyCredential(cred);
317
- if (!ok) return false;
318
- }
319
- }
320
-
321
- return true;
322
- } catch {
323
- return false;
324
- }
325
- }
326
-
327
- /**
328
- * Subscribe to an event
329
- *
330
- * @param eventType - The type of event to listen for
331
- * @param handler - The handler function to call when the event is emitted
332
- * @returns A function to unsubscribe the handler
333
- */
334
- on<K extends keyof EventTypeMap>(
335
- eventType: K,
336
- handler: EventHandler<EventTypeMap[K]>
337
- ): () => void {
338
- return this.eventEmitter.on(eventType, handler);
339
- }
340
-
341
- /**
342
- * Subscribe to an event for a single emission
343
- *
344
- * @param eventType - The type of event to listen for
345
- * @param handler - The handler function to call when the event is emitted (only once)
346
- * @returns A function to unsubscribe the handler
347
- */
348
- once<K extends keyof EventTypeMap>(
349
- eventType: K,
350
- handler: EventHandler<EventTypeMap[K]>
351
- ): () => void {
352
- return this.eventEmitter.once(eventType, handler);
353
- }
354
-
355
- /**
356
- * Unsubscribe from an event
357
- *
358
- * @param eventType - The type of event to stop listening for
359
- * @param handler - The handler function to remove
360
- */
361
- off<K extends keyof EventTypeMap>(
362
- eventType: K,
363
- handler: EventHandler<EventTypeMap[K]>
364
- ): void {
365
- this.eventEmitter.off(eventType, handler);
366
- }
367
-
368
- /**
369
- * Internal method for LifecycleManager to emit events
370
- * This allows type-safe event emission without exposing the internal EventEmitter
371
- *
372
- * @internal
373
- * @param event - The event to emit
374
- */
375
- _internalEmit<K extends keyof EventTypeMap>(event: EventTypeMap[K]): Promise<void> {
376
- return this.eventEmitter.emit(event);
377
- }
378
-
379
- /**
380
- * Add a new version of a resource (immutable versioning).
381
- * Creates a new AssetResource with incremented version number and links it to the previous version.
382
- *
383
- * @param resourceId - The logical resource ID
384
- * @param newContent - The new content (string or Buffer)
385
- * @param contentType - The content type
386
- * @param changes - Optional description of changes
387
- * @returns The newly created AssetResource
388
- * @throws Error if content is unchanged or resource not found
389
- */
390
- addResourceVersion(
391
- resourceId: string,
392
- newContent: string | Buffer,
393
- contentType: string,
394
- changes?: string
395
- ): AssetResource {
396
- // Find the current version of the resource by id
397
- const currentResources = this.resources.filter(r => r.id === resourceId);
398
- if (currentResources.length === 0) {
399
- throw new Error(`Resource with id ${resourceId} not found`);
400
- }
401
-
402
- // Get the latest version
403
- const currentResource = currentResources.sort((a, b) => {
404
- const versionA = a.version || 1;
405
- const versionB = b.version || 1;
406
- return versionB - versionA;
407
- })[0];
408
-
409
- // Compute new hash
410
- const contentBuffer = typeof newContent === 'string'
411
- ? Buffer.from(newContent, 'utf-8')
412
- : newContent;
413
- const newHash = hashResource(contentBuffer);
414
-
415
- // Check if content has actually changed
416
- if (newHash === currentResource.hash) {
417
- throw new Error('Content unchanged - new version would be identical to current version');
418
- }
419
-
420
- // Create new resource version
421
- const newVersion = (currentResource.version || 1) + 1;
422
- const newResource: AssetResource = {
423
- id: resourceId,
424
- type: currentResource.type,
425
- content: typeof newContent === 'string' ? newContent : undefined,
426
- contentType,
427
- hash: newHash,
428
- size: contentBuffer.length,
429
- version: newVersion,
430
- previousVersionHash: currentResource.hash,
431
- createdAt: new Date().toISOString()
432
- };
433
-
434
- // Add to resources array (immutable - don't modify old resource)
435
- (this.resources as AssetResource[]).push(newResource);
436
-
437
- // Track in version manager
438
- this.versionManager.addVersion(
439
- resourceId,
440
- newHash,
441
- contentType,
442
- currentResource.hash,
443
- changes
444
- );
445
-
446
- // Update provenance
447
- const timestamp = new Date().toISOString();
448
- this.provenance.resourceUpdates.push({
449
- resourceId,
450
- fromVersion: currentResource.version || 1,
451
- toVersion: newVersion,
452
- fromHash: currentResource.hash,
453
- toHash: newHash,
454
- timestamp,
455
- changes
456
- });
457
-
458
- // Emit version-created event
459
- const event = {
460
- type: 'resource:version:created' as const,
461
- timestamp,
462
- asset: {
463
- id: this.id
464
- },
465
- resource: {
466
- id: resourceId,
467
- fromVersion: currentResource.version || 1,
468
- toVersion: newVersion,
469
- fromHash: currentResource.hash,
470
- toHash: newHash
471
- },
472
- changes
473
- };
474
-
475
- // Emit asynchronously (don't block)
476
- queueMicrotask(() => {
477
- this.eventEmitter.emit(event);
478
- });
479
-
480
- return newResource;
481
- }
482
-
483
- /**
484
- * Get a specific version of a resource
485
- * @param resourceId - The logical resource ID
486
- * @param version - The version number (1-indexed)
487
- * @returns The AssetResource for that version, or null if not found
488
- */
489
- getResourceVersion(resourceId: string, version: number): AssetResource | null {
490
- const resource = this.resources.find(r =>
491
- r.id === resourceId && (r.version || 1) === version
492
- );
493
- return resource || null;
494
- }
495
-
496
- /**
497
- * Get all versions of a resource
498
- * @param resourceId - The logical resource ID
499
- * @returns Array of all AssetResource versions, sorted by version number
500
- */
501
- getAllVersions(resourceId: string): AssetResource[] {
502
- return this.resources
503
- .filter(r => r.id === resourceId)
504
- .sort((a, b) => (a.version || 1) - (b.version || 1));
505
- }
506
-
507
- /**
508
- * Get the version history for a resource
509
- * @param resourceId - The logical resource ID
510
- * @returns ResourceHistory or null if resource not found
511
- */
512
- getResourceHistory(resourceId: string): ResourceHistory | null {
513
- return this.versionManager.getHistory(resourceId);
514
- }
515
-
516
- private determineCurrentLayer(didId: string): LayerType {
517
- if (didId.startsWith('did:peer:')) return 'did:peer';
518
- if (didId.startsWith('did:webvh:')) return 'did:webvh';
519
- if (didId.startsWith('did:btco:')) return 'did:btco';
520
- throw new Error('Unknown DID method');
521
- }
522
- }
523
-
524
-