@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.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -0,0 +1,368 @@
1
+ // The form for a passport under a profile held by a binding. The user
2
+ // enters one product document; the API validates the whole of it, splits it
3
+ // by the binding's list into a public part and a restricted part, signs
4
+ // only the public part and seals the rest.
5
+ //
6
+ // What the page is careful about:
7
+ //
8
+ // - the GTIN and serial are entered once, as the passport identifier's
9
+ // own parts, and the document's identity members are written from them;
10
+ // - every top-level property shows whether it will be public or
11
+ // restricted, before anything is sent, and the user confirms the public
12
+ // list under a warning that public means permanent;
13
+ // - a field left empty is absent from the document;
14
+ // - what the validator finds is shown at the field it concerns.
15
+ //
16
+ // A profile with no sector form here, such as a profile of your own, is
17
+ // written as a JSON document, with the same labelling and the same warning.
18
+ import { useMemo, useState, type ChangeEvent, type FormEvent, type ReactNode } from 'react'
19
+ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
20
+ import { Button } from '@/components/ui/button'
21
+ import { Input } from '@/components/ui/input'
22
+ import { Textarea } from '@/components/ui/textarea'
23
+ import { ErrorNotice, Field as Labelled, Mono } from '@/components/bits'
24
+ import { FieldView, type FieldContext } from '@/components/bound/field-view'
25
+ import { FindingLines, PublicDataWarning, TierBadge, ViewPanel } from '@/components/bound/pieces'
26
+ import { ApiError, api, type BoundProfile, type Finding, type ViewCheck } from '@/lib/api'
27
+ import { humaniseName } from '@/lib/bound/display'
28
+ import { buildDocument, codeClasses, emptyState, escapePointer, fieldPointerFor, isObject, labelsOf, parseDocument, splitPreview, stripComments, tierOf, type FormState, type Json, type Value } from '@/lib/bound/form-model'
29
+ import { sectorFormFor } from '@/lib/bound/forms'
30
+ import { identityFromDocument, mintIdentity, type IdentifierPolicy } from '@/lib/bound/identity'
31
+ import { useLoad } from '@/lib/use-load'
32
+
33
+ export interface BoundSubmission {
34
+ itemReference: string
35
+ serial: string
36
+ product: Json
37
+ }
38
+
39
+ interface Props {
40
+ profile: BoundProfile
41
+ policy: IdentifierPolicy
42
+ /** For an update: the passport's identifier, which cannot change. */
43
+ passportId?: string
44
+ /** For an update: the document as it stands, to start from. */
45
+ initialProduct?: Json
46
+ submitLabel: string
47
+ busy?: boolean
48
+ error?: unknown
49
+ onSubmit: (submission: BoundSubmission) => void
50
+ after?: ReactNode
51
+ }
52
+
53
+ interface Attempt {
54
+ state: FormState
55
+ rows: Map<string, number[]>
56
+ }
57
+
58
+ const IDENTITY = '/~identity'
59
+ const OTHERS = '/~others'
60
+
61
+ export function BoundPassportForm({ profile, policy, passportId, initialProduct, submitLabel, busy, error, onSubmit, after }: Props) {
62
+ const form = sectorFormFor(profile.id)
63
+ const fixed = passportId == null ? undefined : identityFromDocument(policy, passportId)
64
+ const [itemReference, setItemReference] = useState(fixed != null && 'itemReference' in fixed ? fixed.itemReference : '')
65
+ const [serial, setSerial] = useState(fixed != null && 'serial' in fixed ? fixed.serial : '')
66
+ const [state, setState] = useState<FormState>(() => (form != null && initialProduct != null ? parseDocument(form, initialProduct).state : emptyState()))
67
+ // Other properties, and for a profile with no sector form the whole document, are edited as JSON text.
68
+ const [othersText, setOthersText] = useState(() => (form != null && initialProduct != null ? jsonText(parseDocument(form, initialProduct).state.others) : ''))
69
+ const [documentText, setDocumentText] = useState(() => (form == null && initialProduct != null ? JSON.stringify(initialProduct, null, 2) : ''))
70
+ const [confirmed, setConfirmed] = useState(false)
71
+ const [loadNote, setLoadNote] = useState<string>()
72
+ const [attempt, setAttempt] = useState<Attempt>()
73
+ const codes = useLoad(() => (form == null ? Promise.resolve({}) : api.profileCodes(profile.id, codeClasses(form))), [profile.id])
74
+
75
+ const identity = mintIdentity(policy, itemReference.trim(), serial.trim())
76
+ const contexts = useMemo(() => (form == null ? [] : form.contexts.map((path) => profile.contexts.find((context) => context.path === path)?.uri).filter((uri): uri is string => uri != null)), [form, profile.contexts])
77
+ const others = useMemo(() => parseObject(othersText), [othersText])
78
+ const written = useMemo(() => parseObject(documentText), [documentText])
79
+
80
+ // The document as it would be sent now, and what stops it.
81
+ const built = useMemo(() => {
82
+ if (!identity.ok) return undefined
83
+ if (form == null) return written.ok && written.value != null ? { product: written.value, problems: [], rows: new Map<string, number[]>() } : undefined
84
+ return buildDocument(form, { ...state, others: others.ok ? (others.value ?? {}) : {} }, identity, contexts)
85
+ // The identity is rebuilt on every render; its parts are what matter.
86
+ // eslint-disable-next-line react-hooks/exhaustive-deps
87
+ }, [form, state, others, written, contexts, identity.ok, identity.ok ? identity.passportId : ''])
88
+ const preview = built == null ? undefined : splitPreview(built.product, profile.access)
89
+ const labels = useMemo(() => (form == null ? new Map<string, string>() : labelsOf(form)), [form])
90
+
91
+ // The validation of the last refused attempt, with each finding at the field it concerns.
92
+ const refusal = error instanceof ApiError ? error.details : undefined
93
+ const validation = (refusal?.publicView ?? refusal?.validation) as ViewCheck | undefined
94
+ const { placed, unplaced } = useMemo(() => {
95
+ const placed = new Map<string, Finding[]>()
96
+ const unplaced: Finding[] = []
97
+ for (const finding of validation?.findings ?? []) {
98
+ const at = form == null || attempt == null || finding.pointer == null ? undefined : fieldPointerFor(form, attempt.state, attempt.rows, finding.pointer)
99
+ if (at == null) unplaced.push(finding)
100
+ else placed.set(at, [...(placed.get(at) ?? []), finding])
101
+ }
102
+ return { placed, unplaced }
103
+ }, [validation, form, attempt])
104
+ const problems = useMemo(() => {
105
+ const map = new Map<string, string[]>()
106
+ for (const problem of built?.problems ?? []) map.set(problem.pointer, [...(map.get(problem.pointer) ?? []), problem.message])
107
+ return map
108
+ }, [built])
109
+
110
+ const engineDown = !profile.engine.available
111
+ const jsonProblem = form == null ? (written.ok ? (written.value == null ? 'Enter the product document.' : undefined) : written.problem) : others.ok ? undefined : others.problem
112
+ const blocked = !identity.ok || built == null || built.problems.length > 0 || jsonProblem != null || engineDown
113
+ const context: FieldContext = { codes: codes.data ?? {}, findings: placed, problems, disabled: busy }
114
+
115
+ function load(product: Json, source: string) {
116
+ const clean = stripComments(product)
117
+ const removed = JSON.stringify(product).includes('"_comment') ? ' Its note members, which the profile does not define, were removed.' : ''
118
+ setConfirmed(false)
119
+ setAttempt(undefined)
120
+ if (passportId == null) {
121
+ const named = identityFromDocument(policy, [clean.id, clean['@id']].find((value): value is string => typeof value === 'string'))
122
+ if ('problem' in named) {
123
+ setLoadNote(`${source} was not loaded. ${named.problem}`)
124
+ return
125
+ }
126
+ setItemReference(named.itemReference)
127
+ setSerial(named.serial)
128
+ }
129
+ if (form == null) {
130
+ setDocumentText(JSON.stringify(clean, null, 2))
131
+ setLoadNote(`${source} was loaded.${removed}`)
132
+ return
133
+ }
134
+ const parsed = parseDocument(form, clean)
135
+ setState(parsed.state)
136
+ setOthersText(jsonText(parsed.state.others))
137
+ setLoadNote(
138
+ `${source} was loaded.${removed} ${parsed.kept.length === 0 ? 'Every property is in a field of the form.' : `${parsed.kept.length} ${parsed.kept.length === 1 ? 'property is' : 'properties are'} kept as JSON under Other properties, because the form has no field that holds ${parsed.kept.length === 1 ? 'it' : 'them'} exactly: ${parsed.kept.join(', ')}.`}`
139
+ )
140
+ }
141
+
142
+ async function loadFile(event: ChangeEvent<HTMLInputElement>) {
143
+ const file = event.target.files?.[0]
144
+ event.target.value = ''
145
+ if (file == null) return
146
+ try {
147
+ const parsed: unknown = JSON.parse(await file.text())
148
+ if (!isObject(parsed)) throw new Error('it is not one JSON object')
149
+ load(parsed, file.name)
150
+ } catch (cause) {
151
+ setLoadNote(`${file.name} was not loaded: ${cause instanceof Error ? cause.message : String(cause)}.`)
152
+ }
153
+ }
154
+
155
+ function submit(event: FormEvent) {
156
+ event.preventDefault()
157
+ if (blocked || built == null || !identity.ok || !confirmed) return
158
+ setAttempt({ state: { ...state, others: others.ok ? (others.value ?? {}) : {} }, rows: built.rows })
159
+ onSubmit({ itemReference: itemReference.trim(), serial: serial.trim(), product: built.product })
160
+ }
161
+
162
+ const setValue = (key: string, value: Value): void => {
163
+ setState((current) => ({ ...current, values: { ...current.values, [key]: value } }))
164
+ setConfirmed(false)
165
+ }
166
+ const digits = Math.max(0, 12 - policy.prefix.length)
167
+
168
+ return (
169
+ <form onSubmit={submit} className="space-y-8">
170
+ {engineDown ? (
171
+ <Alert variant="destructive">
172
+ <AlertTitle>This profile cannot be written yet</AlertTitle>
173
+ <AlertDescription>
174
+ <p>The validation engine is not available, and a document that was not validated is never written. {profile.engine.problem}</p>
175
+ </AlertDescription>
176
+ </Alert>
177
+ ) : null}
178
+ {profile.demonstration ? (
179
+ <Alert>
180
+ <AlertTitle>Demonstration prefix</AlertTitle>
181
+ <AlertDescription>
182
+ <p>This platform issues under the GS1 demonstration prefix, so the API writes a notice first in every payload, saying the record describes no real product.</p>
183
+ </AlertDescription>
184
+ </Alert>
185
+ ) : null}
186
+
187
+ <div className="flex flex-wrap items-center gap-2">
188
+ {profile.examples.map((example) => (
189
+ <Button key={example.title} type="button" variant="outline" size="sm" onClick={() => load(example.product, `The example "${example.title}"`)} disabled={busy}>
190
+ Load example: {example.title}
191
+ </Button>
192
+ ))}
193
+ <label className="inline-flex cursor-pointer items-center gap-2 rounded-md border px-3 py-1.5 text-sm">
194
+ Load a document from a file
195
+ <input type="file" accept=".json,.jsonld,application/json,application/ld+json" className="sr-only" onChange={loadFile} disabled={busy} />
196
+ </label>
197
+ </div>
198
+ {loadNote == null ? null : <p className="text-sm text-muted-foreground">{loadNote}</p>}
199
+ {codes.error == null ? null : <p className="text-sm text-muted-foreground">The profile's code lists could not be loaded ({codes.error.message}). A coded value can still be typed, exactly as the profile's vocabulary spells it.</p>}
200
+
201
+ <fieldset className="space-y-4">
202
+ <legend className="mb-3 text-base font-semibold">Identifier</legend>
203
+ <p className="text-sm text-muted-foreground">
204
+ The GTIN and the serial are entered once, here. They make the passport identifier, and the document's own identifier, GTIN and serial are written from them, so the two cannot disagree. All of them are public.
205
+ </p>
206
+ <div className="grid gap-4 sm:grid-cols-2">
207
+ <Labelled label="Item reference" htmlFor="itemReference" required help={`The digits after the GS1 prefix ${policy.prefix}: ${digits} digits.`}>
208
+ <Input id="itemReference" value={itemReference} onChange={(e) => setItemReference(e.target.value)} required inputMode="numeric" pattern="[0-9]+" placeholder={'0'.repeat(digits)} disabled={busy || passportId != null} />
209
+ </Labelled>
210
+ <Labelled label="Serial" htmlFor="serial" required help="The item's serial, 1 to 20 characters.">
211
+ <Input id="serial" value={serial} onChange={(e) => setSerial(e.target.value)} required maxLength={20} disabled={busy || passportId != null} spellCheck={false} />
212
+ </Labelled>
213
+ </div>
214
+ {identity.ok ? (
215
+ <dl className="grid grid-cols-1 gap-x-4 gap-y-1 text-sm sm:grid-cols-[10rem_1fr]">
216
+ <dt className="text-muted-foreground">Passport identifier</dt>
217
+ <dd>
218
+ <Mono>{identity.passportId}</Mono>
219
+ </dd>
220
+ <dt className="text-muted-foreground">GTIN</dt>
221
+ <dd>
222
+ <Mono>{identity.gtin}</Mono>
223
+ </dd>
224
+ {form == null ? null : (
225
+ <>
226
+ <dt className="text-muted-foreground">Granularity</dt>
227
+ <dd>{state.granularity ? 'Item: one passport for one serialised item, as the identifier says.' : 'Not stated in the loaded document.'}</dd>
228
+ </>
229
+ )}
230
+ </dl>
231
+ ) : itemReference === '' && serial === '' ? null : (
232
+ <p className="text-sm text-destructive">{identity.problem}</p>
233
+ )}
234
+ <FindingLines findings={placed.get(IDENTITY)} />
235
+ </fieldset>
236
+
237
+ {form == null ? (
238
+ <JsonDocument profile={profile} identity={identity.ok ? identity.passportId : undefined} text={documentText} onChange={(text) => (setDocumentText(text), setConfirmed(false))} problem={documentText === '' ? undefined : jsonProblem} disabled={busy} />
239
+ ) : (
240
+ <>
241
+ {form.sections.map((section) => (
242
+ <fieldset key={section.title} className="space-y-4">
243
+ <legend className="mb-1 text-base font-semibold">{section.title}</legend>
244
+ {section.description == null ? null : <p className="text-sm text-muted-foreground">{section.description}</p>}
245
+ <div className="grid gap-4 sm:grid-cols-2">
246
+ {section.fields.map((field) => (
247
+ <FieldView key={field.key} field={field} value={state.values[field.key]} onChange={(value) => setValue(field.key, value)} pointer={`/${escapePointer(field.key)}`} context={context} tier={tierOf(profile.access, field.key)} />
248
+ ))}
249
+ </div>
250
+ </fieldset>
251
+ ))}
252
+ <fieldset className="space-y-2">
253
+ <legend className="mb-1 text-base font-semibold">Other properties</legend>
254
+ <p className="text-sm text-muted-foreground">Properties of the profile this form has no field for, as one JSON object. They are written exactly as they are here. A property the binding does not list as public is restricted.</p>
255
+ <Textarea value={othersText} onChange={(e) => (setOthersText(e.target.value), setConfirmed(false))} className="min-h-24 font-mono text-xs" spellCheck={false} placeholder="{ }" aria-label="Other properties, as JSON" disabled={busy} />
256
+ <FindingLines findings={placed.get(OTHERS)} problems={[...(others.ok ? [] : [others.problem]), ...(problems.get(OTHERS) ?? [])]} />
257
+ </fieldset>
258
+ </>
259
+ )}
260
+
261
+ <section className="space-y-4">
262
+ <h2 className="text-base font-semibold">Before you write it</h2>
263
+ <PublicDataWarning split={profile.access != null} />
264
+ {preview == null ? (
265
+ <p className="text-sm text-muted-foreground">Enter the identifier{form == null ? ' and the document' : ''} to see what will be public.</p>
266
+ ) : (
267
+ <div className="grid gap-4 sm:grid-cols-2">
268
+ <TierList tier="public" title="Public, on chain for good" names={preview.public} labels={labels} empty="Nothing." />
269
+ <TierList tier="restricted" title="Restricted, sealed off chain for the holder" names={preview.restricted} labels={labels} empty={profile.access == null ? 'This profile has no restricted part.' : 'Nothing.'} />
270
+ </div>
271
+ )}
272
+ <label className="flex items-start gap-2 text-sm">
273
+ <input type="checkbox" className="mt-1" checked={confirmed} onChange={(e) => setConfirmed(e.target.checked)} disabled={blocked || busy} />
274
+ <span>I have read the public list. Nothing in it, and nothing its values repeat or link to, has to stay private.</span>
275
+ </label>
276
+ </section>
277
+
278
+ {after}
279
+ {built != null && built.problems.length > 0 ? (
280
+ <ErrorNotice error={new Error(`${built.problems.length} ${built.problems.length === 1 ? 'field needs' : 'fields need'} attention before the document can be built. Each is marked above.`)} title="Check the form" />
281
+ ) : null}
282
+ {error == null ? null : <ErrorNotice error={error} title="The API refused it" />}
283
+ {validation == null ? null : (
284
+ <ViewPanel title={validation.view === 'public' ? 'The public part on its own' : 'The whole document'} check={validation}>
285
+ {unplaced.length === 0 || form == null ? null : <p className="text-xs text-muted-foreground">Findings that name a field are shown at that field. The ones listed here could not be placed.</p>}
286
+ </ViewPanel>
287
+ )}
288
+ <div className="flex items-center gap-3">
289
+ <Button type="submit" disabled={busy || blocked || !confirmed}>
290
+ {busy ? 'Working' : submitLabel}
291
+ </Button>
292
+ <span className="text-xs text-muted-foreground">
293
+ <span className="text-destructive">*</span> the profile's rules require it
294
+ </span>
295
+ </div>
296
+ </form>
297
+ )
298
+ }
299
+
300
+ const jsonText = (value: Json): string => (Object.keys(value).length === 0 ? '' : JSON.stringify(value, null, 2))
301
+
302
+ /** JSON text as one object: nothing for empty text, a problem for anything that is not an object. */
303
+ function parseObject(text: string): { ok: true; value?: Json } | { ok: false; problem: string } {
304
+ if (text.trim() === '') return { ok: true }
305
+ try {
306
+ const parsed: unknown = JSON.parse(text)
307
+ return isObject(parsed) ? { ok: true, value: parsed } : { ok: false, problem: 'This must be one JSON object.' }
308
+ } catch (cause) {
309
+ return { ok: false, problem: `This is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}` }
310
+ }
311
+ }
312
+
313
+ function TierList({ tier, title, names, labels, empty }: { tier: 'public' | 'restricted'; title: string; names: string[]; labels: Map<string, string>; empty: string }) {
314
+ return (
315
+ <div className="space-y-2 rounded-lg border p-3">
316
+ <div className="flex items-center gap-2 text-sm font-medium">
317
+ <TierBadge tier={tier} />
318
+ {title}
319
+ </div>
320
+ {names.length === 0 ? (
321
+ <p className="text-sm text-muted-foreground">{empty}</p>
322
+ ) : (
323
+ <ul className="space-y-1 text-sm">
324
+ {names.map((name) => (
325
+ <li key={name} className="flex flex-wrap items-baseline gap-x-2">
326
+ <span>{name === '@context' ? 'Contexts' : name === 'id' || name === '@id' ? 'Identifier' : name === 'type' || name === '@type' ? 'Type' : (labels.get(name) ?? humaniseName(name))}</span>
327
+ <Mono className="text-muted-foreground">{name}</Mono>
328
+ </li>
329
+ ))}
330
+ </ul>
331
+ )}
332
+ </div>
333
+ )
334
+ }
335
+
336
+ /** The whole product document as JSON, for a profile this application has no form for. */
337
+ function JsonDocument({ profile, identity, text, onChange, problem, disabled }: { profile: BoundProfile; identity?: string; text: string; onChange: (text: string) => void; problem?: string; disabled?: boolean }) {
338
+ function insertIdentity() {
339
+ if (identity == null) return
340
+ const parsed = parseObject(text)
341
+ const document: Json = parsed.ok ? (parsed.value ?? {}) : {}
342
+ // Only the identifier just entered goes in. Which contexts the document names, and everything else, is the author's.
343
+ onChange(JSON.stringify({ ...document, id: identity }, null, 2))
344
+ }
345
+ return (
346
+ <fieldset className="space-y-2">
347
+ <legend className="mb-1 text-base font-semibold">Product document</legend>
348
+ <p className="text-sm text-muted-foreground">
349
+ {profile.title} has no form in this application, so its product document is written as JSON, in the profile's own data model. Its identifier must name the same GTIN and serial as the passport identifier above.
350
+ </p>
351
+ <Textarea value={text} onChange={(e) => onChange(e.target.value)} className="min-h-64 font-mono text-xs" spellCheck={false} placeholder="{ }" aria-label="Product document, as JSON" disabled={disabled} />
352
+ {problem == null ? null : <p className="text-xs text-destructive">{problem}</p>}
353
+ {profile.contexts.length === 0 ? null : (
354
+ <p className="text-xs text-muted-foreground">
355
+ A document may name these contexts and no others:{' '}
356
+ {profile.contexts.map((context) => (
357
+ <Mono key={context.uri} className="mr-2">
358
+ {context.uri}
359
+ </Mono>
360
+ ))}
361
+ </p>
362
+ )}
363
+ <Button type="button" variant="outline" size="sm" onClick={insertIdentity} disabled={disabled || identity == null}>
364
+ Put the passport identifier into the document
365
+ </Button>
366
+ </fieldset>
367
+ )
368
+ }
@@ -0,0 +1,237 @@
1
+ // One field of a sector form, drawn from its definition: a control for a
2
+ // single value, a box of fields for a nested object, a list of rows for a
3
+ // repeated one. A field starts empty and stays out of the document until
4
+ // something is entered. Findings and problems appear under the field they
5
+ // concern.
6
+ import type { ReactNode } from 'react'
7
+ import { Button } from '@/components/ui/button'
8
+ import { Input } from '@/components/ui/input'
9
+ import { Label } from '@/components/ui/label'
10
+ import { Textarea } from '@/components/ui/textarea'
11
+ import { FindingLines, NativeSelect, TierBadge } from '@/components/bound/pieces'
12
+ import type { CodeLists, Finding } from '@/lib/api'
13
+ import { NODE_ID, escapePointer, referenceText, withReferenceText, type CodeSource, type Field, type GroupField, type LangValue, type QuantityValue, type Tier, type Value } from '@/lib/bound/form-model'
14
+ import { unitName } from '@/lib/bound/units'
15
+
16
+ export interface FieldContext {
17
+ codes: CodeLists
18
+ /** Findings of the last refused attempt, by the field they were placed at. */
19
+ findings: Map<string, Finding[]>
20
+ /** What stops the document being built, by field. */
21
+ problems: Map<string, string[]>
22
+ disabled?: boolean
23
+ }
24
+
25
+ interface FieldProps {
26
+ field: Field
27
+ value: Value
28
+ onChange: (value: Value) => void
29
+ /** The field's place in the form's values. */
30
+ pointer: string
31
+ context: FieldContext
32
+ /** Shown beside the label of a top-level property. */
33
+ tier?: Tier
34
+ }
35
+
36
+ const idOf = (pointer: string): string => `f${pointer.replace(/[^A-Za-z0-9]+/g, '-')}`
37
+ const textOf = (value: Value): string => (typeof value === 'string' ? value : typeof value === 'number' ? String(value) : '')
38
+
39
+ /** The choices for a code field: a fixed list, or the profile's own vocabulary narrowed to what the field is about. */
40
+ function optionsFor(source: CodeSource, codes: CodeLists): Array<{ value: string; label: string }> {
41
+ if ('options' in source) return source.options
42
+ const only = source.only == null ? undefined : new RegExp(source.only)
43
+ return (codes[source.class] ?? []).filter((option) => (source.prefix == null || option.value.startsWith(source.prefix)) && (only == null || only.test(option.value.slice(option.value.indexOf(':') + 1))))
44
+ }
45
+
46
+ function Shell({ field, pointer, context, tier, children, wide }: { field: Field; pointer: string; context: FieldContext; tier?: Tier; children: ReactNode; wide?: boolean }) {
47
+ return (
48
+ <div className={wide ? 'space-y-1.5 sm:col-span-2' : 'space-y-1.5'}>
49
+ <div className="flex flex-wrap items-center gap-2">
50
+ <Label htmlFor={idOf(pointer)}>
51
+ {field.label}
52
+ {field.required ? <span className="text-destructive" aria-hidden>*</span> : null}
53
+ </Label>
54
+ {tier == null ? null : <TierBadge tier={tier} />}
55
+ </div>
56
+ {children}
57
+ {field.help == null ? null : <p className="text-xs text-muted-foreground">{field.help}</p>}
58
+ <FindingLines findings={context.findings.get(pointer)} problems={context.problems.get(pointer)} />
59
+ </div>
60
+ )
61
+ }
62
+
63
+ export function FieldView({ field, value, onChange, pointer, context, tier }: FieldProps) {
64
+ const id = idOf(pointer)
65
+ const disabled = context.disabled
66
+ switch (field.kind) {
67
+ case 'text':
68
+ case 'url':
69
+ case 'date':
70
+ case 'dateTime':
71
+ case 'integer':
72
+ case 'decimal':
73
+ return (
74
+ <Shell field={field} pointer={pointer} context={context} tier={tier}>
75
+ <Input
76
+ id={id}
77
+ type={field.kind === 'date' ? 'date' : 'text'}
78
+ inputMode={field.kind === 'integer' ? 'numeric' : field.kind === 'decimal' ? 'decimal' : field.kind === 'url' ? 'url' : undefined}
79
+ value={field.kind === 'url' ? referenceText(value) : textOf(value)}
80
+ onChange={(e) => onChange(field.kind === 'url' ? withReferenceText(value, e.target.value) : e.target.value)}
81
+ placeholder={field.kind === 'url' ? 'https://' : field.kind === 'dateTime' ? '2026-11-02T09:30:00Z' : undefined}
82
+ disabled={disabled}
83
+ spellCheck={field.kind === 'text' ? undefined : false}
84
+ />
85
+ </Shell>
86
+ )
87
+ case 'longText':
88
+ return (
89
+ <Shell field={field} pointer={pointer} context={context} tier={tier} wide>
90
+ <Textarea id={id} value={textOf(value)} onChange={(e) => onChange(e.target.value)} disabled={disabled} />
91
+ </Shell>
92
+ )
93
+ case 'boolean':
94
+ return (
95
+ <Shell field={field} pointer={pointer} context={context} tier={tier}>
96
+ <NativeSelect id={id} value={value === true ? 'yes' : value === false ? 'no' : ''} onChange={(e) => onChange(e.target.value === 'yes' ? true : e.target.value === 'no' ? false : undefined)} disabled={disabled}>
97
+ <option value="">Not stated</option>
98
+ <option value="yes">Yes</option>
99
+ <option value="no">No</option>
100
+ </NativeSelect>
101
+ </Shell>
102
+ )
103
+ case 'langText': {
104
+ const text = (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : { value: '', language: '' }) as unknown as LangValue
105
+ return (
106
+ <Shell field={field} pointer={pointer} context={context} tier={tier} wide>
107
+ <div className="flex gap-2">
108
+ <Input id={id} value={text.value} onChange={(e) => onChange({ value: e.target.value, language: text.language })} disabled={disabled} />
109
+ <Input className="w-24 shrink-0" value={text.language} onChange={(e) => onChange({ value: text.value, language: e.target.value })} placeholder="Language" aria-label={`Language of ${field.label}`} disabled={disabled} spellCheck={false} />
110
+ </div>
111
+ </Shell>
112
+ )
113
+ }
114
+ case 'quantity': {
115
+ const quantity = (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : { value: '', unit: '' }) as unknown as QuantityValue
116
+ // A unit a loaded document used stays choosable, even when this form would not offer it.
117
+ const units = quantity.unit !== '' && !field.units.includes(quantity.unit) ? [quantity.unit, ...field.units] : field.units
118
+ return (
119
+ <Shell field={field} pointer={pointer} context={context} tier={tier}>
120
+ <div className="flex gap-2">
121
+ <Input id={id} inputMode="decimal" value={typeof quantity.value === 'number' ? String(quantity.value) : quantity.value} onChange={(e) => onChange({ value: e.target.value, unit: quantity.unit })} disabled={disabled} />
122
+ <NativeSelect className="w-44 shrink-0" value={quantity.unit} onChange={(e) => onChange({ value: quantity.value, unit: e.target.value })} aria-label={`Unit of ${field.label}`} disabled={disabled}>
123
+ <option value="">Unit</option>
124
+ {units.map((unit) => (
125
+ <option key={unit} value={unit}>
126
+ {unitName(unit)} ({unit})
127
+ </option>
128
+ ))}
129
+ </NativeSelect>
130
+ </div>
131
+ </Shell>
132
+ )
133
+ }
134
+ case 'code': {
135
+ const current = referenceText(value)
136
+ const set = (text: string): void => onChange(withReferenceText(value, text))
137
+ const offered = optionsFor(field.codes, context.codes)
138
+ const options = current !== '' && !offered.some((option) => option.value === current) ? [{ value: current, label: current }, ...offered] : offered
139
+ return (
140
+ <Shell field={field} pointer={pointer} context={context} tier={tier}>
141
+ {options.length === 0 ? (
142
+ // No list was loaded for this code. The code can still be written by hand, exactly as the profile's vocabulary spells it.
143
+ <Input id={id} value={current} onChange={(e) => set(e.target.value)} placeholder="A code from the profile's vocabulary" disabled={disabled} spellCheck={false} />
144
+ ) : (
145
+ <NativeSelect id={id} value={current} onChange={(e) => set(e.target.value)} disabled={disabled}>
146
+ <option value="">Not stated</option>
147
+ {options.map((option) => (
148
+ <option key={option.value} value={option.value}>
149
+ {option.label}
150
+ </option>
151
+ ))}
152
+ </NativeSelect>
153
+ )}
154
+ </Shell>
155
+ )
156
+ }
157
+ case 'country':
158
+ return (
159
+ <Shell field={field} pointer={pointer} context={context} tier={tier}>
160
+ <Input id={id} value={textOf(value)} onChange={(e) => onChange(e.target.value.toUpperCase())} maxLength={2} placeholder="Two letters, for example AU" disabled={disabled} spellCheck={false} />
161
+ </Shell>
162
+ )
163
+ case 'group':
164
+ return (
165
+ <fieldset className="space-y-3 rounded-lg border p-3 sm:col-span-2">
166
+ <legend className="flex items-center gap-2 px-1 text-sm font-medium">
167
+ {field.label}
168
+ {field.required ? <span className="text-destructive" aria-hidden>*</span> : null}
169
+ {tier == null ? null : <TierBadge tier={tier} />}
170
+ </legend>
171
+ {field.help == null ? null : <p className="text-xs text-muted-foreground">{field.help}</p>}
172
+ <FindingLines findings={context.findings.get(pointer)} problems={context.problems.get(pointer)} />
173
+ <GroupFields field={field} value={value} onChange={onChange} pointer={pointer} context={context} />
174
+ </fieldset>
175
+ )
176
+ case 'list': {
177
+ const rows = Array.isArray(value) ? value : []
178
+ const item = { ...field.item, key: field.key } as Field
179
+ const set = (row: number, next: Value): void => onChange(rows.map((entry, at) => (at === row ? next : entry)))
180
+ return (
181
+ <fieldset className="space-y-3 rounded-lg border p-3 sm:col-span-2">
182
+ <legend className="flex items-center gap-2 px-1 text-sm font-medium">
183
+ {field.label}
184
+ {field.required ? <span className="text-destructive" aria-hidden>*</span> : null}
185
+ {tier == null ? null : <TierBadge tier={tier} />}
186
+ </legend>
187
+ {field.help == null ? null : <p className="text-xs text-muted-foreground">{field.help}</p>}
188
+ <FindingLines findings={context.findings.get(pointer)} problems={context.problems.get(pointer)} />
189
+ {rows.map((entry, row) => (
190
+ <div key={row} className="space-y-2 rounded-md border border-dashed p-3">
191
+ <div className="flex items-center justify-between gap-2">
192
+ <span className="text-xs font-medium text-muted-foreground">
193
+ {field.itemLabel[0].toUpperCase() + field.itemLabel.slice(1)} {row + 1}
194
+ </span>
195
+ <Button type="button" variant="ghost" size="sm" onClick={() => onChange(rows.filter((_, at) => at !== row))} disabled={disabled}>
196
+ Remove
197
+ </Button>
198
+ </div>
199
+ {item.kind === 'group' ? (
200
+ <>
201
+ <FindingLines findings={context.findings.get(`${pointer}/${row}`)} problems={context.problems.get(`${pointer}/${row}`)} />
202
+ <GroupFields field={item} value={entry} onChange={(next) => set(row, next)} pointer={`${pointer}/${row}`} context={context} />
203
+ </>
204
+ ) : (
205
+ <div className="grid gap-3 sm:grid-cols-2">
206
+ <FieldView field={{ ...item, label: `${field.itemLabel[0].toUpperCase() + field.itemLabel.slice(1)} ${row + 1}` } as Field} value={entry} onChange={(next) => set(row, next)} pointer={`${pointer}/${row}`} context={context} />
207
+ </div>
208
+ )}
209
+ </div>
210
+ ))}
211
+ <Button type="button" variant="outline" size="sm" onClick={() => onChange([...rows, undefined])} disabled={disabled}>
212
+ Add {rows.length === 0 ? 'a' : 'another'} {field.itemLabel}
213
+ </Button>
214
+ </fieldset>
215
+ )
216
+ }
217
+ }
218
+ }
219
+
220
+ function GroupFields({ field, value, onChange, pointer, context }: { field: GroupField; value: Value; onChange: (value: Value) => void; pointer: string; context: FieldContext }) {
221
+ const group = (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}) as { [key: string]: Value }
222
+ const nodeId = group[NODE_ID]
223
+ return (
224
+ <div className="grid gap-3 sm:grid-cols-2">
225
+ {typeof nodeId !== 'string' ? null : (
226
+ // A loaded document gave this node an identifier. It is kept and can be edited; the form never makes one up.
227
+ <div className="space-y-1.5 sm:col-span-2">
228
+ <Label htmlFor={`${idOf(pointer)}-id`}>Identifier</Label>
229
+ <Input id={`${idOf(pointer)}-id`} value={nodeId} onChange={(e) => onChange({ ...group, [NODE_ID]: e.target.value })} disabled={context.disabled} spellCheck={false} />
230
+ </div>
231
+ )}
232
+ {field.fields.map((child) =>
233
+ child.kind === 'fixed' ? null : <FieldView key={child.key} field={child} value={group[child.key]} onChange={(next) => onChange({ ...group, [child.key]: next })} pointer={`${pointer}/${escapePointer(child.key)}`} context={context} />
234
+ )}
235
+ </div>
236
+ )
237
+ }