@bsv/create-dpp-app 0.1.0-beta.1 → 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.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- package/template/package.json +9 -3
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// What the EPCIS tests share: synthetic documents, an in-memory MongoDB and a
|
|
2
|
+
// small stand-in for a source's query interface.
|
|
3
|
+
//
|
|
4
|
+
// Every identifier is synthetic, under the GS1 demonstration prefix 952. The
|
|
5
|
+
// source listens on 127.0.0.1 only, on a port the system picks, and every
|
|
6
|
+
// test that starts one stops it. It is not an EPCIS repository and answers no
|
|
7
|
+
// more of the query interface than these tests ask of it.
|
|
8
|
+
import { createHash } from 'node:crypto'
|
|
9
|
+
import { once } from 'node:events'
|
|
10
|
+
import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'
|
|
11
|
+
import type { AddressInfo } from 'node:net'
|
|
12
|
+
import { MongoClient, type Db } from 'mongodb'
|
|
13
|
+
import { MongoMemoryServer } from 'mongodb-memory-server'
|
|
14
|
+
import type { EpcisExchangeStorage } from '@bsv/dpp-credentials/epcis-exchange'
|
|
15
|
+
import { EPCIS_CONTEXT_IRI } from '@bsv/dpp-credentials/epcis-source'
|
|
16
|
+
import { createAuth, type Session } from '../src/auth.js'
|
|
17
|
+
import { loadConfig, type Config } from '../src/config.js'
|
|
18
|
+
import { startEpcisExchange, type EpcisExchange } from '../src/epcis/exchange.js'
|
|
19
|
+
import { openPlatform, type Platform } from '../src/platform.js'
|
|
20
|
+
import { createServer as createApiServer } from '../src/server.js'
|
|
21
|
+
|
|
22
|
+
export type Json = Record<string, unknown>
|
|
23
|
+
|
|
24
|
+
export const utf8 = (text: string): Uint8Array => new TextEncoder().encode(text)
|
|
25
|
+
export const sha256 = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex')
|
|
26
|
+
|
|
27
|
+
/** The folder the test set-up provisioned the pinned GS1 files into. */
|
|
28
|
+
export const gs1Dir = (): string => process.env.DPP_GS1_ARTEFACTS_DIR as string
|
|
29
|
+
|
|
30
|
+
/* --------------------------------- documents ----------------------------- */
|
|
31
|
+
|
|
32
|
+
const pad = (n: number, width = 2): string => String(n).padStart(width, '0')
|
|
33
|
+
export const eventId = (n: number): string => `urn:uuid:00000000-0000-4000-8000-0000000002${pad(n)}`
|
|
34
|
+
export const item = (serial: string): string => `urn:epc:id:sgtin:9521234.012345.${serial}`
|
|
35
|
+
export const minute = (n: number, hour = 9): string => `2026-03-02T${pad(hour)}:${pad(n)}:00.000Z`
|
|
36
|
+
|
|
37
|
+
/** One synthetic observation of the identifiers given. Event `n` was recorded at minute `n`. */
|
|
38
|
+
export function objectEvent(n: number, identifiers: string[], fields: Json = {}): Json {
|
|
39
|
+
return { type: 'ObjectEvent', eventID: eventId(n), eventTime: minute(n, 8), eventTimeZoneOffset: '+00:00', recordTime: minute(n), epcList: identifiers, action: 'OBSERVE', bizStep: 'inspecting', disposition: 'active', ...fields }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/* Identifiers of the five-type document below, all under the demonstration prefix 952. */
|
|
43
|
+
export const CELL_A = item('CELL-A')
|
|
44
|
+
export const CELL_B = item('CELL-B')
|
|
45
|
+
export const MODULE = item('MODULE-1')
|
|
46
|
+
export const PACK = item('PACK-1')
|
|
47
|
+
/** A lot: a class of items, never one item. */
|
|
48
|
+
export const ELECTROLYTE_LOT = 'urn:epc:class:lgtin:9521234.033333.LOT7'
|
|
49
|
+
/** A pattern: every serial of one product. */
|
|
50
|
+
export const SCRAP_CLASS = 'urn:epc:idpat:sgtin:9521234.055555.*'
|
|
51
|
+
export const PALLET = 'urn:epc:id:sscc:9521234.0000000001'
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One event of each of the five EPCIS event types, in the order
|
|
55
|
+
* transformation, object, association, aggregation, transaction. The
|
|
56
|
+
* transformation takes two cells and a quantity of a lot and gives a module
|
|
57
|
+
* and a quantity of scrap, so the document names individual items and
|
|
58
|
+
* classes in every role an index entry can have. Events are numbered 31 to
|
|
59
|
+
* 35.
|
|
60
|
+
*/
|
|
61
|
+
export function fiveEventTypes(): Json[] {
|
|
62
|
+
const common = (n: number): Json => ({ eventID: eventId(n), eventTime: minute(n - 30, 8), eventTimeZoneOffset: '+00:00', recordTime: minute(n - 30) })
|
|
63
|
+
return [
|
|
64
|
+
{ type: 'TransformationEvent', ...common(31), inputEPCList: [CELL_A, CELL_B], inputQuantityList: [{ epcClass: ELECTROLYTE_LOT, quantity: 4, uom: 'EA' }], outputEPCList: [MODULE], outputQuantityList: [{ epcClass: SCRAP_CLASS, quantity: 0.5, uom: 'KGM' }], bizStep: 'assembling', disposition: 'in_progress', transformationID: 'urn:example:transformation:stage-1' },
|
|
65
|
+
{ type: 'ObjectEvent', ...common(32), epcList: [PACK], action: 'ADD', bizStep: 'commissioning', disposition: 'active' },
|
|
66
|
+
{ type: 'AssociationEvent', ...common(33), parentID: PACK, childEPCs: [MODULE], action: 'ADD', bizStep: 'installing', disposition: 'active' },
|
|
67
|
+
{ type: 'AggregationEvent', ...common(34), parentID: PALLET, childEPCs: [PACK], action: 'ADD', bizStep: 'packing', disposition: 'in_transit' },
|
|
68
|
+
{ type: 'TransactionEvent', ...common(35), bizTransactionList: [{ type: 'po', bizTransaction: 'urn:epcglobal:cbv:bt:9521234000018:PO-77' }], epcList: [PACK], action: 'ADD', bizStep: 'shipping', disposition: 'in_transit' },
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function epcisDocument(eventList: Json[], extra: Json = {}): Json {
|
|
73
|
+
return { '@context': [EPCIS_CONTEXT_IRI, { example: 'https://example.org/vocab/' }], type: 'EPCISDocument', schemaVersion: '2.0', creationDate: '2026-03-03T07:00:00.000Z', ...extra, epcisBody: { eventList } }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/* ---------------------------------- MongoDB ------------------------------ */
|
|
77
|
+
|
|
78
|
+
export interface TestMongo {
|
|
79
|
+
client: MongoClient
|
|
80
|
+
/** A database of its own for each call, so no test meets another's records. */
|
|
81
|
+
database(): Db
|
|
82
|
+
stop(): Promise<void>
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** One MongoDB node, in memory, as the reference deployment runs it: no replica set, so no multi-document transaction. */
|
|
86
|
+
export async function startMongo(): Promise<TestMongo> {
|
|
87
|
+
const mongod = await MongoMemoryServer.create()
|
|
88
|
+
const client = await MongoClient.connect(mongod.getUri())
|
|
89
|
+
let count = 0
|
|
90
|
+
return {
|
|
91
|
+
client,
|
|
92
|
+
database: () => client.db(`epcis_test_${process.pid}_${(count += 1)}`),
|
|
93
|
+
stop: async () => {
|
|
94
|
+
await client.close()
|
|
95
|
+
await mongod.stop()
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/* ----------------------------------- source ------------------------------ */
|
|
101
|
+
|
|
102
|
+
export interface SourceRequest {
|
|
103
|
+
path: string
|
|
104
|
+
/** The query as it was sent, undecoded. */
|
|
105
|
+
search: string
|
|
106
|
+
query: Record<string, string>
|
|
107
|
+
headers: IncomingHttpHeaders
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface SourceBehaviour {
|
|
111
|
+
/** Answer 401 unless the request carries exactly this Authorization header. */
|
|
112
|
+
requireAuthorization?: string
|
|
113
|
+
/** Called with the number of each page request, from 1. Return a status to answer it with that status and no page. */
|
|
114
|
+
failRequest?: (n: number) => number | undefined
|
|
115
|
+
/** Name the next page on this origin instead of the source's own. */
|
|
116
|
+
nextOrigin?: string
|
|
117
|
+
/** Answer this in place of an EPCIS page: a status, a media type and a body. */
|
|
118
|
+
answer?: { status: number; mediaType: string; body: string }
|
|
119
|
+
/** When a page names a next one, the time its token is good until, sent as GS1-Next-Page-Token-Expires. */
|
|
120
|
+
tokenExpires?: () => string
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface FixtureSource {
|
|
124
|
+
origin: string
|
|
125
|
+
/** The base address of the query interface. */
|
|
126
|
+
baseUrl: string
|
|
127
|
+
events: Json[]
|
|
128
|
+
behaviour: SourceBehaviour
|
|
129
|
+
/** Every request received, in order. */
|
|
130
|
+
requests: SourceRequest[]
|
|
131
|
+
close(): Promise<void>
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function startEpcisSource(events: Json[] = [], behaviour: SourceBehaviour = {}): Promise<FixtureSource> {
|
|
135
|
+
const requests: SourceRequest[] = []
|
|
136
|
+
let origin = ''
|
|
137
|
+
let pageRequests = 0
|
|
138
|
+
const source: FixtureSource = { origin: '', baseUrl: '', events: [...events], behaviour, requests, close: async () => undefined }
|
|
139
|
+
|
|
140
|
+
const server: Server = createServer((incoming, response) => {
|
|
141
|
+
const url = new URL(incoming.url ?? '/', origin)
|
|
142
|
+
const query = Object.fromEntries(url.searchParams)
|
|
143
|
+
requests.push({ path: url.pathname, search: url.search, query, headers: incoming.headers })
|
|
144
|
+
const settings = source.behaviour
|
|
145
|
+
if (settings.requireAuthorization != null && incoming.headers.authorization !== settings.requireAuthorization) {
|
|
146
|
+
response.writeHead(401, { 'www-authenticate': 'Bearer' }).end()
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
if (url.pathname !== '/epcis/events') {
|
|
150
|
+
response.writeHead(404).end()
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
pageRequests += 1
|
|
154
|
+
const failure = settings.failRequest?.(pageRequests)
|
|
155
|
+
if (failure != null) {
|
|
156
|
+
response.writeHead(failure, { 'content-type': 'application/problem+json' }).end('{"title":"the source is not available"}')
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
if (settings.answer != null) {
|
|
160
|
+
response.writeHead(settings.answer.status, { 'content-type': settings.answer.mediaType, 'GS1-EPCIS-Version': '2.0.1' }).end(settings.answer.body)
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const offset = query.nextPageToken == null ? 0 : Number(Buffer.from(query.nextPageToken, 'base64url').toString('utf8'))
|
|
164
|
+
const perPage = Math.max(1, Number(query.perPage ?? '30'))
|
|
165
|
+
const wanted = query.MATCH_anyEPC?.split('|')
|
|
166
|
+
const matched = source.events.filter((event) => wanted == null || (Array.isArray(event.epcList) && event.epcList.some((epc) => wanted.includes(String(epc)))))
|
|
167
|
+
const slice = matched.slice(offset, offset + perPage)
|
|
168
|
+
const headers: Record<string, string> = { 'content-type': 'application/ld+json', 'GS1-EPCIS-Version': '2.0.1', 'GS1-CBV-Version': '2.0.0' }
|
|
169
|
+
if (offset + perPage < matched.length) {
|
|
170
|
+
const parameters = new URLSearchParams(query)
|
|
171
|
+
parameters.set('nextPageToken', Buffer.from(String(offset + perPage), 'utf8').toString('base64url'))
|
|
172
|
+
headers.Link = `<${settings.nextOrigin ?? origin}/epcis/events?${parameters.toString()}>; rel="next"`
|
|
173
|
+
if (settings.tokenExpires != null) headers['GS1-Next-Page-Token-Expires'] = settings.tokenExpires()
|
|
174
|
+
}
|
|
175
|
+
const document = { '@context': [EPCIS_CONTEXT_IRI], type: 'EPCISQueryDocument', schemaVersion: '2.0', creationDate: '2026-03-03T07:00:00.000Z', epcisBody: { queryResults: { queryName: 'SimpleEventQuery', resultsBody: { eventList: slice } } } }
|
|
176
|
+
response.writeHead(200, headers).end(JSON.stringify(document))
|
|
177
|
+
})
|
|
178
|
+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
|
179
|
+
origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
|
|
180
|
+
source.origin = origin
|
|
181
|
+
source.baseUrl = `${origin}/epcis`
|
|
182
|
+
source.close = () =>
|
|
183
|
+
new Promise<void>((resolve) => {
|
|
184
|
+
server.closeAllConnections()
|
|
185
|
+
server.close(() => resolve())
|
|
186
|
+
})
|
|
187
|
+
return source
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/* ------------------------------------ the API ---------------------------- */
|
|
191
|
+
|
|
192
|
+
/** The configuration the EPCIS tests run under: the provisioned GS1 folder, never fetched into, and whatever a test adds. */
|
|
193
|
+
export const testConfig = (over: Record<string, string> = {}): Config =>
|
|
194
|
+
loadConfig({ NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false', DPP_GS1_ARTEFACTS_DIR: gs1Dir(), DPP_GS1_ARTEFACTS_OFFLINE: 'true', ...over })
|
|
195
|
+
|
|
196
|
+
export const developer: Session = { userId: 'developer', email: 'developer@localhost', name: 'Developer', brandIds: ['dev-brand'] }
|
|
197
|
+
|
|
198
|
+
export interface Answer {
|
|
199
|
+
status: number
|
|
200
|
+
headers: Headers
|
|
201
|
+
bytes: Uint8Array
|
|
202
|
+
text: string
|
|
203
|
+
body: any
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface TestApp {
|
|
207
|
+
base: string
|
|
208
|
+
platform: Platform
|
|
209
|
+
exchange: EpcisExchange
|
|
210
|
+
/** Every line start-up and the exchange logged. */
|
|
211
|
+
lines: string[]
|
|
212
|
+
/** Sent with every request below: the cookie of a signed-in user, for one. */
|
|
213
|
+
headers: Record<string, string>
|
|
214
|
+
get(path: string): Promise<Answer>
|
|
215
|
+
/** A JSON body. */
|
|
216
|
+
post(path: string, body: unknown): Promise<Answer>
|
|
217
|
+
/** A body sent as the bytes given, under the media type given. */
|
|
218
|
+
upload(path: string, bytes: Uint8Array, mediaType?: string, headers?: Record<string, string>): Promise<Answer>
|
|
219
|
+
close(): Promise<void>
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The API as main.ts assembles it, on a port of its own: the platform, the exchange opened beside it, and the server.
|
|
224
|
+
*
|
|
225
|
+
* `mode: 'live'` opens the platform as main.ts does, on the MongoDB the configuration names, and the exchange is then
|
|
226
|
+
* opened on the platform's own database and client unless a test hands it another. `signIn` turns sign-in on as main.ts
|
|
227
|
+
* does with a database: Better Auth on that same database, and no development session.
|
|
228
|
+
*/
|
|
229
|
+
export async function startApp(options: { config?: Config; mode?: 'live' | 'test'; signIn?: boolean; db?: Db; storage?: EpcisExchangeStorage; session?: Session | null; fetch?: typeof globalThis.fetch; lines?: string[]; now?: () => string } = {}): Promise<TestApp> {
|
|
230
|
+
const config = options.config ?? testConfig()
|
|
231
|
+
const lines = options.lines ?? []
|
|
232
|
+
const log = (line: string): void => void lines.push(line)
|
|
233
|
+
const platform = await openPlatform({ config, mode: options.mode ?? 'test', log })
|
|
234
|
+
const db = options.db ?? platform.db
|
|
235
|
+
const exchange = await startEpcisExchange({ config: config.epcis, ...(db == null ? {} : { db }), ...(options.storage == null ? {} : { storage: options.storage }), ...(options.fetch == null ? {} : { fetch: options.fetch }), ...(options.now == null ? {} : { now: options.now }), log })
|
|
236
|
+
if (options.signIn === true && platform.db == null) throw new Error('sign-in needs the platform on a database: start it with mode live and a reachable MONGO_URL')
|
|
237
|
+
const auth = options.signIn === true ? createAuth({ db: platform.db!, secret: config.authSecret, baseURL: config.publicUrl }) : undefined
|
|
238
|
+
const app = createApiServer({ platform, exchange, ...(auth != null ? { auth } : options.session === null ? {} : { devSession: options.session ?? developer }) })
|
|
239
|
+
const server = app.listen(0, '127.0.0.1')
|
|
240
|
+
await once(server, 'listening')
|
|
241
|
+
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
|
|
242
|
+
const answer = async (response: Response): Promise<Answer> => {
|
|
243
|
+
const bytes = new Uint8Array(await response.arrayBuffer())
|
|
244
|
+
const text = new TextDecoder().decode(bytes)
|
|
245
|
+
let body: unknown
|
|
246
|
+
try {
|
|
247
|
+
body = text === '' ? undefined : JSON.parse(text)
|
|
248
|
+
} catch {
|
|
249
|
+
body = undefined
|
|
250
|
+
}
|
|
251
|
+
return { status: response.status, headers: response.headers, bytes, text, body }
|
|
252
|
+
}
|
|
253
|
+
const started: TestApp = {
|
|
254
|
+
base,
|
|
255
|
+
platform,
|
|
256
|
+
exchange,
|
|
257
|
+
lines,
|
|
258
|
+
headers: {},
|
|
259
|
+
get: async (path) => answer(await fetch(`${base}${path}`, { headers: started.headers })),
|
|
260
|
+
post: async (path, body) => answer(await fetch(`${base}${path}`, { method: 'POST', headers: { ...started.headers, 'content-type': 'application/json' }, body: JSON.stringify(body) })),
|
|
261
|
+
upload: async (path, bytes, mediaType = 'application/ld+json', headers = {}) => answer(await fetch(`${base}${path}`, { method: 'POST', headers: { ...started.headers, 'content-type': mediaType, ...headers }, body: bytes as unknown as BodyInit })),
|
|
262
|
+
close: async () => {
|
|
263
|
+
server.closeAllConnections()
|
|
264
|
+
await new Promise<void>((resolve) => server.close(() => resolve()))
|
|
265
|
+
await exchange.close()
|
|
266
|
+
await platform.close()
|
|
267
|
+
},
|
|
268
|
+
}
|
|
269
|
+
return started
|
|
270
|
+
}
|