@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.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.
Files changed (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,313 @@
1
+ // The MongoDB storage adapter of the EPCIS exchange, held to what the module
2
+ // asks of any adapter. The module ships a suite for that and this file runs
3
+ // it, unchanged, against one MongoDB node in memory: the same kind of node
4
+ // the reference deployment runs, where no multi-document transaction is
5
+ // available. The suite stops the store before and after every durable call
6
+ // of an import, a conflict decision and an index rebuild, reopens it, and
7
+ // checks that nothing acknowledged was lost and nothing is half recorded.
8
+ //
9
+ // The suite stops the adapter between its calls. The tests after it stop it
10
+ // inside them, at each step the adapter itself takes in the database, and
11
+ // run two writers over one store.
12
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
13
+ import {
14
+ EPCIS_RECORD_KINDS,
15
+ EpcisStorageError,
16
+ EpcisStorageFault,
17
+ checkEpcisExchangeInvariants,
18
+ epcisStorageAdapterSuite,
19
+ exportEpcisSource,
20
+ findEpcisImportByRequest,
21
+ importEpcisSource,
22
+ recoverEpcisExchange,
23
+ type EpcisExchangeStorage,
24
+ type EpcisImportOutcome,
25
+ type EpcisStorageAdapterHarness,
26
+ } from '@bsv/dpp-credentials/epcis-exchange'
27
+ import { MONGO_EPCIS_MAX_BATCH_BYTES, openMongoEpcisStorage, type MongoEpcisStorage, type MongoEpcisStorageOptions, type MongoEpcisStorageStep } from '../src/epcis/mongo-storage.js'
28
+ import { epcisDocument, gs1Dir, item, objectEvent, sha256, startMongo, utf8, type Json, type TestMongo } from './epcis-fixtures.js'
29
+
30
+ let mongo: TestMongo
31
+ beforeAll(async () => {
32
+ mongo = await startMongo()
33
+ })
34
+ afterAll(async () => {
35
+ await mongo.stop()
36
+ })
37
+
38
+ // The simulated crashes are made by the test, so waiting for the journal adds nothing but time. One test below runs with it on.
39
+ // Small chunks, so a source of a few thousand bytes is held in several.
40
+ const quick: MongoEpcisStorageOptions = { journal: false, chunkBytes: 16 * 1024 }
41
+
42
+ const harness = (): EpcisStorageAdapterHarness => {
43
+ const db = mongo.database()
44
+ return {
45
+ open: () => openMongoEpcisStorage(db, quick),
46
+ abandon: (storage) => (storage as MongoEpcisStorage).abandon(),
47
+ destroy: async () => {
48
+ await db.dropDatabase()
49
+ },
50
+ }
51
+ }
52
+
53
+ describe('the node these tests run on', () => {
54
+ it('is a single node without multi-document transactions', async () => {
55
+ const hello = await mongo.client.db('admin').command({ hello: 1 })
56
+ expect(hello.setName).toBeUndefined()
57
+ const session = mongo.client.startSession()
58
+ try {
59
+ const refused = await session
60
+ .withTransaction(async () => {
61
+ await mongo.database().collection('probe').insertOne({ n: 1 }, { session })
62
+ })
63
+ .then(
64
+ () => undefined,
65
+ (error: unknown) => error as { message?: string; originalError?: { message?: string } }
66
+ )
67
+ // The driver words the node's refusal in its own way and keeps the node's beside it.
68
+ expect(`${refused?.message} ${refused?.originalError?.message}`).toMatch(/Transaction numbers are only allowed on a replica set member or mongos|does not support retryable writes/)
69
+ } finally {
70
+ await session.endSession()
71
+ }
72
+ })
73
+ })
74
+
75
+ describe('the shared adapter suite: the MongoDB adapter', () => {
76
+ const cases = epcisStorageAdapterSuite(harness, { artefactsDir: gs1Dir() })
77
+ it('covers the interface and every crash', () => {
78
+ expect(cases.length).toBeGreaterThanOrEqual(14)
79
+ expect(cases.filter((test) => test.name.startsWith('crash:')).length).toBe(5)
80
+ })
81
+ for (const test of cases) it(test.name, test.run, 300_000)
82
+ })
83
+
84
+ describe('the MongoDB adapter', () => {
85
+ const AT = '2026-03-10T00:00:00.000Z'
86
+ const documentBytes = utf8(JSON.stringify(epcisDocument([objectEvent(1, [item('ADAPTER-1')]), objectEvent(2, [item('ADAPTER-1'), item('ADAPTER-2')]), objectEvent(3, [item('ADAPTER-2')], { 'example:note': 'seen on the line' })]), null, 2))
87
+ const request = (storage: EpcisExchangeStorage, requestId = 'request-1', bytes = documentBytes) => ({ storage, sourceId: 'source-a', requestId, bytes, mediaType: 'application/ld+json', receivedAt: AT, provenance: { kind: 'file' as const }, policy: { policyId: 'test-policy@1' }, artefactsDir: gs1Dir(), now: () => AT })
88
+ const record = (outcome: EpcisImportOutcome) => {
89
+ if (outcome.outcome !== 'retained') throw new Error(JSON.stringify(outcome))
90
+ return outcome.record
91
+ }
92
+ const dump = async (storage: EpcisExchangeStorage): Promise<Array<[string, string, Json]>> => {
93
+ const out: Array<[string, string, Json]> = []
94
+ for (const kind of Object.values(EPCIS_RECORD_KINDS)) for (const held of await storage.list(kind, { limit: 100_000 })) out.push([kind, held.key, held.value])
95
+ return out
96
+ }
97
+ const held = async (storage: EpcisExchangeStorage): Promise<unknown[]> => (await storage.list('suite', { limit: 20 })).map((r) => [r.key, r.revision, r.value.n])
98
+
99
+ it('keeps an import across a close and a reopen, waiting for the journal', async () => {
100
+ const db = mongo.database()
101
+ const first = await openMongoEpcisStorage(db)
102
+ const imported = record(await importEpcisSource(request(first)))
103
+ await first.close()
104
+ await expect(first.get('import', 'aaaa')).rejects.toMatchObject({ code: 'closed' })
105
+ const second = await openMongoEpcisStorage(db)
106
+ expect(second.reopened).toEqual({ batchesApplied: 0 })
107
+ expect(await findEpcisImportByRequest(second, 'source-a', 'request-1')).toEqual(imported)
108
+ expect(Buffer.from((await exportEpcisSource(second, imported.importId))!.bytes).equals(Buffer.from(documentBytes))).toBe(true)
109
+ expect(await checkEpcisExchangeInvariants(second, { associations: true })).toEqual([])
110
+ // The value of a record is held as the JSON text it was written as, so it reads back exactly, whatever its member names are.
111
+ const strange = { '': 1, 'a.b': { $set: [1.5, -0, 1e21, null] }, 'café ☃': 'ok', 'with\u0000nul': true }
112
+ await second.commit([{ op: 'put', kind: 'suite', key: 'strange', value: strange }])
113
+ expect((await second.get('suite', 'strange'))!.value).toEqual(JSON.parse(JSON.stringify(strange)))
114
+ await second.close()
115
+ })
116
+
117
+ it('refuses a database that holds another format, and a batch too large to commit as one document', async () => {
118
+ const foreign = mongo.database()
119
+ await foreign.collection<{ _id: string }>('epcis_log').insertOne({ _id: 'log', format: 'something-else', version: '9' } as never)
120
+ await expect(openMongoEpcisStorage(foreign, quick)).rejects.toMatchObject({ code: 'corrupt' })
121
+
122
+ const storage = await openMongoEpcisStorage(mongo.database(), quick)
123
+ const large = 'x'.repeat(MONGO_EPCIS_MAX_BATCH_BYTES)
124
+ await expect(storage.commit([{ op: 'put', kind: 'suite', key: 'small', value: { n: 1 } }, { op: 'put', kind: 'suite', key: 'large', value: { large } }])).rejects.toMatchObject({ code: 'invalid-value' })
125
+ // Nothing of the refused batch was written.
126
+ expect(await held(storage)).toEqual([])
127
+ })
128
+
129
+ it('applies a batch whole when it is stopped at any database step and reopened', async () => {
130
+ const writes = [
131
+ { op: 'put' as const, kind: 'suite', key: 'one.record', value: { n: 1 } },
132
+ { op: 'put' as const, kind: 'suite', key: 'two.record', value: { n: 2 }, expect: 1 },
133
+ { op: 'delete' as const, kind: 'suite', key: 'three.record' },
134
+ ]
135
+ const seed = async (storage: EpcisExchangeStorage): Promise<void> => {
136
+ await storage.commit([
137
+ { op: 'put', kind: 'suite', key: 'two.record', value: { n: 0 } },
138
+ { op: 'put', kind: 'suite', key: 'three.record', value: { n: 3 } },
139
+ ])
140
+ }
141
+ const before = [['three.record', 1, 3], ['two.record', 1, 0]]
142
+ const after = [['one.record', 1, 1], ['two.record', 2, 2]]
143
+ const steps: MongoEpcisStorageStep[] = []
144
+ {
145
+ const db = mongo.database()
146
+ await seed(await openMongoEpcisStorage(db, quick))
147
+ const traced = await openMongoEpcisStorage(db, { ...quick, interrupt: (step) => void steps.push(step) })
148
+ await traced.commit(writes)
149
+ expect(await held(traced)).toEqual(after)
150
+ }
151
+ expect(steps).toEqual(['batch-commit', 'record-put', 'record-put', 'record-delete', 'batch-clear'])
152
+ for (let at = 0; at < steps.length; at += 1) {
153
+ const db = mongo.database()
154
+ await seed(await openMongoEpcisStorage(db, quick))
155
+ let seen = 0
156
+ const stopping = await openMongoEpcisStorage(db, { ...quick, interrupt: () => { if (seen++ === at) throw new EpcisStorageFault(at + 1, 'before', steps[at]!) } })
157
+ await expect(stopping.commit(writes)).rejects.toBeInstanceOf(EpcisStorageFault)
158
+ await expect(stopping.get('suite', 'one.record')).rejects.toBeInstanceOf(EpcisStorageFault)
159
+ const reopened = await openMongoEpcisStorage(db, quick)
160
+ // Before the log document names the batch it never happened. From then on it always completes.
161
+ const committed = at >= 1
162
+ expect(await held(reopened), `stopped before ${steps[at]} (step ${at + 1})`).toEqual(committed ? after : before)
163
+ expect(reopened.reopened.batchesApplied, steps[at]).toBe(committed ? 1 : 0)
164
+ // The deleted record is gone to every reader, and a record put in its place starts a new count.
165
+ if (committed) {
166
+ expect(await reopened.get('suite', 'three.record')).toBeUndefined()
167
+ expect(await reopened.commit([{ op: 'put', kind: 'suite', key: 'three.record', value: { n: 9 }, expect: 'absent' }])).toEqual({ committed: true })
168
+ expect((await reopened.get('suite', 'three.record'))!.revision).toBe(1)
169
+ }
170
+ }
171
+ })
172
+
173
+ it('never shows half of a source: bytes stopped before their head document are not there', async () => {
174
+ const bytes = new Uint8Array(40_000).map((_, i) => (i * 7) & 0xff)
175
+ const digest = sha256(bytes)
176
+ for (const stopAt of [0, 1, 2, 3] as const) {
177
+ const db = mongo.database()
178
+ let seen = 0
179
+ const steps: MongoEpcisStorageStep[] = []
180
+ const stopping = await openMongoEpcisStorage(db, { ...quick, interrupt: (step) => { steps.push(step); if (seen++ === stopAt) throw new EpcisStorageFault(stopAt + 1, 'before', step) } })
181
+ await expect(stopping.putBytes(digest, bytes)).rejects.toBeInstanceOf(EpcisStorageFault)
182
+ // 40,000 bytes are three chunks and then the head.
183
+ expect(steps.at(-1)).toBe(stopAt < 3 ? 'bytes-chunk' : 'bytes-head')
184
+ const reopened = await openMongoEpcisStorage(db, quick)
185
+ expect(await reopened.getBytes(digest), `stopped at step ${stopAt + 1}`).toBeUndefined()
186
+ await reopened.putBytes(digest, bytes)
187
+ expect(Buffer.from((await reopened.getBytes(digest))!).equals(Buffer.from(bytes))).toBe(true)
188
+ await reopened.deleteBytes(digest)
189
+ expect(await reopened.getBytes(digest)).toBeUndefined()
190
+ }
191
+ })
192
+
193
+ it('gives the same store when an import is stopped at every database step, then recovered and retried', async () => {
194
+ // The uninterrupted import is the measure, and its trace is the list of places to stop.
195
+ const steps: MongoEpcisStorageStep[] = []
196
+ const control = await openMongoEpcisStorage(mongo.database(), { ...quick, interrupt: (step) => void steps.push(step) })
197
+ const controlRecord = record(await importEpcisSource(request(control)))
198
+ const controlStore = await dump(control)
199
+ expect(steps.length).toBeGreaterThan(20)
200
+ expect(new Set(steps)).toEqual(new Set(['bytes-chunk', 'bytes-head', 'batch-commit', 'record-put', 'record-delete', 'batch-clear']))
201
+
202
+ const outcomes = { discarded: 0, finished: 0 }
203
+ for (let at = 0; at < steps.length; at += 1) {
204
+ const where = `stopped before database step ${at + 1} of ${steps.length} (${steps[at]})`
205
+ const db = mongo.database()
206
+ let seen = 0
207
+ const stopping = await openMongoEpcisStorage(db, { ...quick, interrupt: () => { if (seen++ === at) throw new EpcisStorageFault(at + 1, 'before', steps[at]!) } })
208
+ await expect(importEpcisSource(request(stopping)), where).rejects.toBeInstanceOf(EpcisStorageFault)
209
+
210
+ const reopened = await openMongoEpcisStorage(db, quick)
211
+ const report = await recoverEpcisExchange(reopened, { now: () => AT })
212
+ expect(report.remaining, where).toBe(0)
213
+ expect(await checkEpcisExchangeInvariants(reopened, { associations: true }), where).toEqual([])
214
+ const receipt = await findEpcisImportByRequest(reopened, 'source-a', 'request-1')
215
+ if (receipt == null) {
216
+ // No receipt: nothing of the request is left, bytes included.
217
+ outcomes.discarded += 1
218
+ expect(await reopened.getBytes(controlRecord.sha256), where).toBeUndefined()
219
+ expect(await dump(reopened), where).toEqual([])
220
+ } else {
221
+ // A receipt: recovery finished the import to the same result, and the source is whole.
222
+ outcomes.finished += 1
223
+ expect(receipt, where).toEqual(controlRecord)
224
+ expect(Buffer.from((await exportEpcisSource(reopened, receipt.importId))!.bytes).equals(Buffer.from(documentBytes)), where).toBe(true)
225
+ }
226
+ const retried = await importEpcisSource(request(reopened))
227
+ expect(record(retried), where).toEqual(controlRecord)
228
+ expect(await dump(reopened), where).toEqual(controlStore)
229
+ await db.dropDatabase()
230
+ }
231
+ // Both sides of the receipt were stopped at.
232
+ expect(outcomes.discarded).toBeGreaterThan(1)
233
+ expect(outcomes.finished).toBeGreaterThan(10)
234
+ }, 300_000)
235
+
236
+ it('lets a second process finish a committed batch, and never lets the first bring back what was deleted since', async () => {
237
+ const db = mongo.database()
238
+ // The first writer is held still after it committed a batch of two records and applied one of them.
239
+ let puts = 0
240
+ let release: () => void = () => undefined
241
+ const stalled = new Promise<void>((resolve) => { release = resolve })
242
+ let reached: () => void = () => undefined
243
+ const atStall = new Promise<void>((resolve) => { reached = resolve })
244
+ const first = await openMongoEpcisStorage(db, { ...quick, interrupt: async (step) => { if (step === 'record-put' && (puts += 1) === 2) { reached(); await stalled } } })
245
+ const committing = first.commit([
246
+ { op: 'put', kind: 'suite', key: 'kept.record', value: { n: 1 } },
247
+ { op: 'put', kind: 'suite', key: 'gone.record', value: { n: 1 } },
248
+ ])
249
+ await atStall
250
+
251
+ // A second process reads: it finds the batch committed, applies all of it and sees both records.
252
+ const second = await openMongoEpcisStorage(db, quick)
253
+ expect(second.reopened.batchesApplied).toBe(1)
254
+ expect(await held(second)).toEqual([['gone.record', 1, 1], ['kept.record', 1, 1]])
255
+ // It then deletes one and rewrites the other, in two further batches.
256
+ expect(await second.commit([{ op: 'delete', kind: 'suite', key: 'gone.record', expect: 1 }])).toEqual({ committed: true })
257
+ expect(await second.commit([{ op: 'put', kind: 'suite', key: 'kept.record', value: { n: 2 }, expect: 1 }])).toEqual({ committed: true })
258
+
259
+ // The first writer wakes and applies the rest of its old batch. Every write of it meets a record a later batch wrote, and changes nothing.
260
+ release()
261
+ expect(await committing).toEqual({ committed: true })
262
+ expect(await held(second)).toEqual([['kept.record', 2, 2]])
263
+ expect(await held(first)).toEqual([['kept.record', 2, 2]])
264
+ expect(await first.get('suite', 'gone.record')).toBeUndefined()
265
+ })
266
+
267
+ it('serialises two writers on one store, and shows a reader whole batches only', async () => {
268
+ const db = mongo.database()
269
+ const writers = [await openMongoEpcisStorage(db, quick), await openMongoEpcisStorage(db, quick)]
270
+ const reader = await openMongoEpcisStorage(db, quick)
271
+ await writers[0]!.commit([
272
+ { op: 'put', kind: 'suite', key: 'pair.left', value: { n: 0 } },
273
+ { op: 'put', kind: 'suite', key: 'pair.right', value: { n: 0 } },
274
+ ])
275
+ let writing = true
276
+ const torn: unknown[] = []
277
+ const reading = (async () => {
278
+ while (writing) {
279
+ const [left, right] = await reader.list('suite', { prefix: 'pair.', limit: 2 })
280
+ // Both records are written in one batch, so they always agree.
281
+ if (left!.value.n !== right!.value.n || left!.revision !== right!.revision) torn.push([left, right])
282
+ }
283
+ })()
284
+ // Each writer adds one to both records twenty-five times, expecting the revision it read. A lost race is answered, and tried again.
285
+ const increments = async (storage: EpcisExchangeStorage): Promise<number> => {
286
+ let lost = 0
287
+ for (let done = 0; done < 25; ) {
288
+ const now = (await storage.get('suite', 'pair.left'))!
289
+ const next = { n: (now.value.n as number) + 1 }
290
+ const result = await storage.commit([
291
+ { op: 'put', kind: 'suite', key: 'pair.left', value: next, expect: now.revision },
292
+ { op: 'put', kind: 'suite', key: 'pair.right', value: next, expect: now.revision },
293
+ ])
294
+ if (result.committed) done += 1
295
+ else lost += 1
296
+ }
297
+ return lost
298
+ }
299
+ await Promise.all(writers.map(increments))
300
+ writing = false
301
+ await reading
302
+ expect(torn).toEqual([])
303
+ // Fifty increments were acknowledged, and fifty are held: none was lost and none applied twice.
304
+ expect(await held(reader)).toEqual([['pair.left', 51, 50], ['pair.right', 51, 50]])
305
+ })
306
+
307
+ it('refuses a malformed call the way every adapter does', async () => {
308
+ const storage = await openMongoEpcisStorage(mongo.database(), quick)
309
+ await expect(storage.putBytes(sha256(utf8('other')), utf8('exact'))).rejects.toBeInstanceOf(EpcisStorageError)
310
+ await expect(openMongoEpcisStorage(mongo.database(), { collectionPrefix: 'Not A Name' })).rejects.toMatchObject({ code: 'invalid-value' })
311
+ await expect(openMongoEpcisStorage(mongo.database(), { chunkBytes: 0 })).rejects.toMatchObject({ code: 'invalid-value' })
312
+ })
313
+ })
@@ -0,0 +1,253 @@
1
+ // An EPCIS import or pull retains data. It changes no custody, signs nothing,
2
+ // writes nothing on chain and never calls the wallet. Two tests hold the
3
+ // application to that.
4
+ //
5
+ // The first reads the source: it follows every import from the EPCIS routes
6
+ // and fails if the code they are built from can reach the wallet, the writer,
7
+ // the index client or any package that signs or broadcasts. The second runs
8
+ // every EPCIS route against a platform whose wallet, writer and index record
9
+ // each call made to them, and sees none.
10
+ import { existsSync, readFileSync } from 'node:fs'
11
+ import { dirname, join, relative, resolve } from 'node:path'
12
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
13
+ import { mintPassportId } from '../src/identifiers.js'
14
+ import { samplePayload } from '../src/profiles.js'
15
+ import { epcisDocument, item, objectEvent, startApp, startEpcisSource, testConfig, utf8, type FixtureSource, type Json, type TestApp } from './epcis-fixtures.js'
16
+
17
+ const SRC = resolve(import.meta.dirname, '..', 'src')
18
+
19
+ /**
20
+ * What a source file imports at run time: its `import` and `export ... from`
21
+ * statements, its dynamic imports and its `require` calls. An `import type`
22
+ * is left out, because the compiler removes it and nothing is loaded for it.
23
+ * A statement that imports a value beside a type is counted whole.
24
+ */
25
+ function importsOf(file: string): string[] {
26
+ const text = readFileSync(file, 'utf8')
27
+ const found = new Set<string>()
28
+ for (const match of text.matchAll(/^[ \t]*(?:import|export)\s+(?!type\b)(?:[^'";]*?\sfrom\s+)?['"]([^'"]+)['"]/gm)) found.add(match[1]!)
29
+ for (const match of text.matchAll(/\b(?:import|require)\(\s*['"]([^'"]+)['"]\s*\)/g)) found.add(match[1]!)
30
+ return [...found]
31
+ }
32
+
33
+ const packageName = (specifier: string): string => (specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]!)
34
+
35
+ /** The folder a package is installed in, found the way Node finds it: the nearest node_modules above the importer that holds it. */
36
+ function packageDir(name: string, from: string): string | undefined {
37
+ for (let dir = from; ; dir = dirname(dir)) {
38
+ const candidate = join(dir, 'node_modules', name)
39
+ if (existsSync(join(candidate, 'package.json'))) return candidate
40
+ if (dirname(dir) === dir) return undefined
41
+ }
42
+ }
43
+
44
+ /**
45
+ * The one package that is followed file by file. `@bsv/dpp-credentials` has
46
+ * several entry points, and one of them, `./epcis-lifecycle`, signs: it
47
+ * imports the protocol package and the SDK, which the package therefore
48
+ * declares. A package's declared dependencies say what it installs, not what
49
+ * one entry point loads, so for this package the walk follows the built files
50
+ * an imported entry point reaches and counts only the packages those files
51
+ * import. Every other package is counted with everything it declares.
52
+ */
53
+ const FOLLOWED_BY_FILE = '@bsv/dpp-credentials'
54
+
55
+ /** The built file an entry point of a package names, read from its `exports`. */
56
+ function entryFile(dir: string, specifier: string, name: string): string {
57
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { exports: Record<string, { default: string } | undefined> }
58
+ const subpath = specifier === name ? '.' : `.${specifier.slice(name.length)}`
59
+ const target = manifest.exports[subpath]?.default
60
+ if (target == null) throw new Error(`${name} declares no entry point ${subpath}`)
61
+ return join(dir, target)
62
+ }
63
+
64
+ /** Everything the code under `entry` can load: the files of this application it imports, and every package those files import with everything each depends on. */
65
+ function reachableFrom(entry: string, from = SRC): { files: string[]; direct: string[]; packages: string[] } {
66
+ const files = new Set<string>()
67
+ const direct = new Set<string>()
68
+ const specifiers = new Set<string>()
69
+ const visit = (file: string): void => {
70
+ if (files.has(file)) return
71
+ files.add(file)
72
+ for (const specifier of importsOf(file)) {
73
+ if (specifier.startsWith('.')) visit(resolve(dirname(file), specifier.replace(/\.js$/, '.ts')))
74
+ else if (!specifier.startsWith('node:')) { direct.add(packageName(specifier)); specifiers.add(specifier) }
75
+ }
76
+ }
77
+ if (!entry.startsWith('@')) visit(join(from, entry))
78
+ else { direct.add(packageName(entry)); specifiers.add(entry) }
79
+ const packages = new Map<string, string>()
80
+ const built = new Set<string>()
81
+ const install = (name: string, at: string): void => {
82
+ const dir = packageDir(name, at)
83
+ if (dir == null || packages.has(dir)) return
84
+ packages.set(dir, name)
85
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as Record<string, Record<string, string> | undefined>
86
+ for (const dependency of Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies, ...manifest.peerDependencies })) install(dependency, dir)
87
+ }
88
+ /** A built file of the followed package: its relative imports are followed, and each package it imports is counted whole. */
89
+ const follow = (file: string, dir: string): void => {
90
+ if (built.has(file)) return
91
+ built.add(file)
92
+ for (const specifier of importsOf(file)) {
93
+ if (specifier.startsWith('.')) follow(resolve(dirname(file), specifier), dir)
94
+ else if (!specifier.startsWith('node:')) install(packageName(specifier), dir)
95
+ }
96
+ }
97
+ for (const specifier of specifiers) {
98
+ const name = packageName(specifier)
99
+ if (name !== FOLLOWED_BY_FILE) { install(name, from); continue }
100
+ const dir = packageDir(name, from)
101
+ if (dir == null) throw new Error(`${name} is not installed`)
102
+ packages.set(dir, name)
103
+ follow(entryFile(dir, specifier, name), dir)
104
+ }
105
+ return { files: [...files].map((file) => relative(SRC, file)).sort(), direct: [...direct].sort(), packages: [...new Set(packages.values())].sort() }
106
+ }
107
+
108
+ /** The code that signs, spends, announces or broadcasts. */
109
+ const SIGNING_FILES = ['wallet.ts', 'writer.ts', 'index-client.ts', 'custody.ts', 'claims.ts', 'parties.ts', 'platform.ts', 'worker.ts', 'dev-index.ts', 'go-live.ts', 'reader.ts']
110
+ const SIGNING_PACKAGES = ['@bsv/sdk', '@bsv/wallet-toolbox', '@bsv/wallet-toolbox-client', '@bsv/overlay', '@bsv/dpp-overlay', '@bsv/dpp-protocol', '@bsv/dpp-profiles']
111
+
112
+ describe('what the EPCIS routes are built from', () => {
113
+ it('is five files of this application and three packages, none of which signs or broadcasts', () => {
114
+ const graph = reachableFrom('epcis/routes.ts')
115
+ // The whole list, so that a new import into the exchange is a decision someone makes here.
116
+ expect(graph.files).toEqual(['epcis/exchange.ts', 'epcis/mongo-storage.ts', 'epcis/routes.ts', 'epcis/sources.ts', 'http-error.ts'])
117
+ expect(graph.direct).toEqual(['@bsv/dpp-credentials', 'express', 'mongodb'])
118
+ for (const file of SIGNING_FILES) expect(graph.files, file).not.toContain(file)
119
+ // Every package those three load, however deep.
120
+ expect(graph.packages.length).toBeGreaterThan(40)
121
+ for (const name of SIGNING_PACKAGES) expect(graph.packages, name).not.toContain(name)
122
+ expect(graph.packages.filter((name) => name.startsWith('@bsv/'))).toEqual(['@bsv/dpp-credentials'])
123
+ })
124
+
125
+ it('sees the signing entry point of the credentials package for what it is, and the routes import none of it', () => {
126
+ // The same walk, started at the entry point that holds the EPCIS lifecycle claim, reaches the SDK and the protocol package.
127
+ const claim = reachableFrom('@bsv/dpp-credentials/epcis-lifecycle')
128
+ expect(claim.packages).toEqual(expect.arrayContaining(['@bsv/sdk', '@bsv/dpp-protocol']))
129
+ // The routes take the exchange and the source helpers, and never that entry point.
130
+ for (const file of reachableFrom('epcis/routes.ts').files) {
131
+ for (const specifier of importsOf(join(SRC, file))) expect(specifier, file).not.toMatch(/epcis-lifecycle/)
132
+ }
133
+ // The other entry points of the package reach neither.
134
+ for (const entry of ['@bsv/dpp-credentials', '@bsv/dpp-credentials/epcis-source', '@bsv/dpp-credentials/epcis-exchange']) {
135
+ const reached = reachableFrom(entry).packages
136
+ for (const name of SIGNING_PACKAGES) expect(reached, `${entry} ${name}`).not.toContain(name)
137
+ }
138
+ })
139
+
140
+ it('is found to reach the wallet when it does: the same walk from the start of the API finds it', () => {
141
+ // The check above would pass on anything if the walk followed nothing. From main.ts it follows the platform to everything a passport write uses.
142
+ const graph = reachableFrom('main.ts')
143
+ for (const file of ['wallet.ts', 'writer.ts', 'index-client.ts', 'platform.ts', 'custody.ts']) expect(graph.files, file).toContain(file)
144
+ expect(graph.packages).toEqual(expect.arrayContaining(['@bsv/sdk', '@bsv/dpp-protocol', '@bsv/dpp-overlay']))
145
+ // The exchange is opened beside the platform and handed to the server, never the other way round.
146
+ expect(graph.files).toEqual(expect.arrayContaining(['epcis/exchange.ts', 'epcis/routes.ts', 'http-error.ts']))
147
+ })
148
+
149
+ it('reads a type-only import as nothing and a value import as something', () => {
150
+ const routes = importsOf(join(SRC, 'epcis/routes.ts'))
151
+ expect(readFileSync(join(SRC, 'epcis/routes.ts'), 'utf8')).toMatch(/import type \{ Session \} from '\.\.\/auth\.js'/)
152
+ expect(routes).not.toContain('../auth.js')
153
+ expect(routes).toEqual(expect.arrayContaining(['./exchange.js', '../http-error.js', 'express']))
154
+ })
155
+ })
156
+
157
+ describe('what an import or a pull does to the platform', () => {
158
+ const calls: string[] = []
159
+ let api: TestApp
160
+ let fixture: FixtureSource
161
+ let passportId: string
162
+
163
+ /**
164
+ * Replace every function an object carries, its own and its class's, with one that notes the call and then makes it.
165
+ * Only the object itself is changed. What it refers to is left alone, because a library object shared with other code
166
+ * would then note calls nobody made through the platform.
167
+ */
168
+ const record = (target: object, name: string): void => {
169
+ const members = new Set<string>(Object.getOwnPropertyNames(target))
170
+ for (let proto = Object.getPrototypeOf(target) as object | null; proto != null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto) as object | null) for (const member of Object.getOwnPropertyNames(proto)) members.add(member)
171
+ for (const member of members) {
172
+ if (member === 'constructor') continue
173
+ const value = (target as Record<string, unknown>)[member]
174
+ if (typeof value !== 'function') continue
175
+ Object.defineProperty(target, member, {
176
+ configurable: true,
177
+ writable: true,
178
+ value: (...args: unknown[]) => {
179
+ calls.push(`${name}.${member}`)
180
+ return (value as (...a: unknown[]) => unknown).apply(target, args)
181
+ },
182
+ })
183
+ }
184
+ }
185
+
186
+ beforeAll(async () => {
187
+ fixture = await startEpcisSource(Array.from({ length: 5 }, (_, index) => objectEvent(index + 1, [item(`SEP-${index + 1}`)])))
188
+ api = await startApp({ config: testConfig({ EPCIS_SOURCES: 'supplier-a', EPCIS_SOURCE_SUPPLIER_A_URL: fixture.baseUrl, EPCIS_SOURCE_SUPPLIER_A_LOCAL_TEST: 'true' }) })
189
+ // A passport written before the doubles go in, so there is custody an import could change.
190
+ const brand = api.platform.parties.brand('dev-brand')
191
+ await api.platform.store.saveBrand({ id: 'dev-brand', name: 'Development brand', identityKey: brand.identityKey, did: brand.did, createdAt: new Date().toISOString() })
192
+ passportId = mintPassportId({ host: 'passports.example.com', prefix: '952' }, '100000001', 'SEPARATE-1')
193
+ await api.platform.writer.issue({ brandId: 'dev-brand', brand, passportId, profile: 'general@2', payload: samplePayload('general@2', true), ownerFields: {} })
194
+ const { wallet, writer, index, custody, claims } = api.platform
195
+ // The wallet, and the three parts of it that sign, hold the lock and send; then everything that asks it to.
196
+ for (const [name, part] of Object.entries({ wallet, 'wallet.publisher': wallet.publisher, 'wallet.custodian': wallet.custodian, 'wallet.adapter': wallet.adapter, writer, index, custody, claims })) record(part, name)
197
+ })
198
+ afterAll(async () => {
199
+ await api.close()
200
+ await fixture.close()
201
+ })
202
+
203
+ it('calls the wallet, the writer, the index, custody and claims not once, and leaves every passport as it was', async () => {
204
+ const journal = JSON.stringify(await api.platform.store.listPassports())
205
+ const offers = JSON.stringify(await api.platform.store.listOffers())
206
+ const lineage = async (): Promise<number> => ((await (await fetch(`${api.platform.index.url}/lookup`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ service: 'ls_dpp', query: { passportId } }) })).json()) as { outputs: unknown[] }).outputs.length
207
+ const indexed = await lineage()
208
+ expect(indexed).toBeGreaterThan(0)
209
+ calls.length = 0
210
+
211
+ // Every EPCIS route, with documents that name the passport itself.
212
+ const ref = encodeURIComponent
213
+ const first = utf8(JSON.stringify(epcisDocument([objectEvent(1, [passportId], { bizStep: 'shipping', disposition: 'in_transit' }), objectEvent(2, [passportId], { action: 'DELETE', bizStep: 'destroying', disposition: 'destroyed' })])))
214
+ const imported = await api.upload('/api/epcis/imports?requestId=separate-1', first)
215
+ expect(imported.status).toBe(201)
216
+ expect((await api.upload('/api/epcis/imports?requestId=separate-1', first)).status).toBe(200)
217
+ const changed = await api.upload('/api/epcis/imports?requestId=separate-2', utf8(JSON.stringify(epcisDocument([objectEvent(1, [passportId], { bizStep: 'receiving', disposition: 'in_progress' })]))))
218
+ expect(changed.body.record.state).toBe('blocked')
219
+ expect((await api.upload('/api/epcis/imports?requestId=separate-1', utf8('{}'))).status).toBe(409)
220
+ expect((await api.upload('/api/epcis/imports?requestId=separate-3', utf8('not json'))).status).toBe(422)
221
+ const importId = imported.body.record.importId as string
222
+ expect((await api.get('/api/epcis/imports')).body.imports).toHaveLength(2)
223
+ expect((await api.get(`/api/epcis/imports/${ref(importId)}`)).status).toBe(200)
224
+ expect((await api.get(`/api/epcis/imports/${ref(importId)}/original`)).status).toBe(200)
225
+ expect((await api.get(`/api/epcis/events?identifier=${ref(passportId)}`)).body.events.length).toBeGreaterThan(0)
226
+ const conflictId = (changed.body.record.events as Json[])[0]!.conflict as Json
227
+ expect((await api.get('/api/epcis/conflicts')).body.conflicts).toHaveLength(1)
228
+ expect((await api.post(`/api/epcis/conflicts/${ref(String(conflictId.conflictId))}/resolutions`, { decision: 'Both are kept.', disposition: 'all-retained' })).status).toBe(201)
229
+ const pulled = await api.post('/api/epcis/sources/supplier-a/pulls', { queryId: 'all', query: { perPage: 2 } })
230
+ expect(pulled.body).toMatchObject({ outcome: 'ok', events: { total: 5 } })
231
+ expect((await api.get('/api/epcis/sources/supplier-a/pulls/all')).status).toBe(200)
232
+ expect((await api.get('/api/epcis/sources')).status).toBe(200)
233
+ expect((await api.get('/api/epcis/status')).status).toBe(200)
234
+
235
+ // The doubles saw nothing, and neither the journal, the offers nor the index holds anything it did not hold before.
236
+ expect(calls).toEqual([])
237
+ expect(JSON.stringify(await api.platform.store.listPassports())).toBe(journal)
238
+ expect(JSON.stringify(await api.platform.store.listOffers())).toBe(offers)
239
+ expect(await lineage()).toBe(indexed)
240
+ // An event that says the item was destroyed retired nothing.
241
+ expect((await api.get(`/api/passports/${ref(passportId)}`)).body).toMatchObject({ status: 'active' })
242
+ expect(calls).toEqual([])
243
+ })
244
+
245
+ it('does record a call when a passport is written, so an empty record means none was made', async () => {
246
+ calls.length = 0
247
+ const updated = await api.post(`/api/passports/${encodeURIComponent(passportId)}/update`, { payload: samplePayload('general@2', true) })
248
+ expect(updated.status).toBe(200)
249
+ expect(calls.some((call) => call.startsWith('writer.update'))).toBe(true)
250
+ expect(calls.some((call) => call.startsWith('wallet.'))).toBe(true)
251
+ expect(calls.some((call) => call.startsWith('index.'))).toBe(true)
252
+ })
253
+ })