@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,236 @@
1
+ // The form for eu-textile@1: textile passport data for one serialised item
2
+ // of clothing. Composition is a list of fibres, each with its share as a
3
+ // number. Care is one coded symbol for each of the five treatments. A test
4
+ // result is what was measured, the value and its unit, and a rating is a
5
+ // code from the profile's own scale. None of them is free text standing in
6
+ // for a structured value. Whether a property is public or restricted is
7
+ // read from the binding's list, not decided here.
8
+ import { ANY_UNIT } from './units'
9
+ import { address, certificate, code, contact, country, date, dateTime, decimal, entry, facility, fixed, group, langText, list, measurement, operator, organisation, PASSPORT_STATUSES, quantity, reference, referencedFiles, text, url, warranty, yesNo } from './fields'
10
+ import type { CodeSource, GroupField, SectorForm } from './form-model'
11
+
12
+ const careSymbol = (key: string, label: string, only: string) => code(key, label, { class: 'eutex:CareSymbolCode', only })
13
+
14
+ /** One test: the method, what it measured, and the result. `scored` adds the points a scoring method awards for it. */
15
+ const test = (scored: boolean): GroupField =>
16
+ entry('oea:TestExecution', [
17
+ url('id', 'Identifier of the test', { help: 'Optional. A web address that identifies this test, if it has one.' }),
18
+ code('oea:hasMethod', 'Test method', { class: 'oea:TestMethod', prefix: 'eutex:' }),
19
+ measurement('oea:hasResult', 'Result', 'eutex:'),
20
+ ...(scored ? [decimal('oea:awardedScore', 'Points awarded')] : []),
21
+ ])
22
+
23
+ /** A rating or a figure derived from the tests: its kind, then either a value with a unit or a class from a scale. */
24
+ const indicator = (classes: CodeSource): GroupField =>
25
+ entry('oea:Indicator', [code('oea:hasIndicatorKind', 'Kind', 'oea:IndicatorKind', { required: true }), quantity('oea:hasIndicatorValue', 'Value', ANY_UNIT), code('oea:hasCategoricalValue', 'Class', classes), text('oea:indicatorText', 'Text')])
26
+
27
+ const GENDER: CodeSource = { options: ['FEMALE', 'MALE', 'UNISEX'].map((value) => ({ value: `gs1:TargetConsumerGenderCode-${value}`, label: value[0] + value.slice(1).toLowerCase() })) }
28
+
29
+ export const TEXTILE_FORM: SectorForm = {
30
+ profile: 'eu-textile@1',
31
+ contexts: ['dpp-core-context.jsonld', 'textile-context.jsonld'],
32
+ type: ['gs1:Clothing', 'eutex:TextileApparel'],
33
+ serialMembers: ['schema:serialNumber'],
34
+ sections: [
35
+ {
36
+ title: 'The garment',
37
+ fields: [
38
+ list('gs1:productName', 'Product name', 'name', langText('', 'Name')),
39
+ list('gs1:productDescription', 'Description', 'description', langText('', 'Description')),
40
+ code('oec:hasProductCategory', 'Product group', 'oec:ProductCategory'),
41
+ code('schema:category', 'Textile category', 'eutex:TextileCategory'),
42
+ code('eutex:hasApparelSubcategory', 'Kind of clothing', 'eutex:ApparelSubcategory'),
43
+ text('eutex:garmentType', 'Garment'),
44
+ code('eutex:hasFabricType', 'Fabric', 'eutex:FabricType'),
45
+ code('gs1:targetConsumerGender', 'Made for', GENDER),
46
+ text('eutex:sizeRange', 'Sizes', { help: 'The range of sizes the model is made in, as the brand writes it.' }),
47
+ text('eutex:seasonCollection', 'Collection'),
48
+ quantity('gs1:netWeight', 'Net weight', ['KGM', 'GRM']),
49
+ date('gs1:productionDate', 'Made on'),
50
+ country('gs1:countryOfOrigin', 'Country of origin'),
51
+ ],
52
+ },
53
+ {
54
+ title: 'The passport',
55
+ fields: [
56
+ code('oec:passportStatus', 'Passport status', PASSPORT_STATUSES, { as: 'text' }),
57
+ text('oec:passportVersion', 'Passport version'),
58
+ date('oec:passportIssueDate', 'Passport issued on'),
59
+ dateTime('oec:lastUpdated', 'Last updated'),
60
+ url('oec:passportIdentifier', 'Passport identifier of the model', { help: 'Optional. A link for the same product at model level. It must not name another product.' }),
61
+ ],
62
+ },
63
+ {
64
+ title: 'Manufacturer, operator and sites',
65
+ description: 'Each party and each site is identified by a location number. A name is a label, and does not identify anything on its own.',
66
+ fields: [
67
+ organisation('gs1:manufacturer', 'Manufacturer'),
68
+ operator('oec:hasOperatorInformation', 'oec:hasOperatorRole'),
69
+ facility('eutex:hasSpinningFacility', 'Spinning'),
70
+ facility('eutex:hasWeavingFacility', 'Weaving or knitting'),
71
+ facility('eutex:hasDyeingFacility', 'Dyeing'),
72
+ facility('eutex:hasCutAndSewFacility', 'Cutting and sewing'),
73
+ facility('eutex:hasFinishingFacility', 'Finishing'),
74
+ ],
75
+ },
76
+ {
77
+ title: 'Composition',
78
+ description: 'One entry for each fibre, with its share of the weight as a number.',
79
+ fields: [
80
+ list(
81
+ 'gs1:textileMaterial',
82
+ 'Fibres',
83
+ 'fibre',
84
+ entry('gs1:TextileMaterialDetails', [
85
+ decimal('gs1:textileMaterialPercentage', 'Share', { typed: true, required: true, help: 'A percentage, from 0 to 100.' }),
86
+ langText('gs1:textileMaterialDescription', 'Fibre', { required: true }),
87
+ country('eutex:fiberOrigin', 'Country the fibre comes from', { as: 'text' }),
88
+ yesNo('eutex:isRecycledFiber', 'Recycled fibre'),
89
+ text('eutex:recycledContentSource', 'What it was recycled from'),
90
+ group('eutex:hasFiberCertification', 'Certificate', 'gs1:CertificationDetails', [text('gs1:certificationAgency', 'Issued by'), text('gs1:certificationStandard', 'Standard'), text('gs1:certificationValue', 'Certificate value')]),
91
+ ])
92
+ ),
93
+ group('oec:hasRecycledContentDetails', 'Recycled content', 'oec:RecycledContent', [
94
+ decimal('oec:recycledContent', 'Recycled share', { help: 'A fraction from 0 to 1.' }),
95
+ decimal('oec:preConsumerRecycledContent', 'From manufacturing waste', { help: 'A fraction from 0 to 1.' }),
96
+ decimal('oec:postConsumerRecycledContent', 'From used products', { help: 'A fraction from 0 to 1.' }),
97
+ ]),
98
+ list(
99
+ 'eutex:hasRecycledContentDeclaration',
100
+ 'Recycled content declarations',
101
+ 'declaration',
102
+ entry('eutex:RecycledContentDeclaration', [
103
+ url('id', 'Identifier of the declaration', { help: 'Optional. A web address that identifies this declaration, if it has one.' }),
104
+ decimal('eutex:secondaryMaterialFraction', 'Share of recycled material', { help: 'A percentage, from 0 to 100.' }),
105
+ code('eutex:hasWasteOriginType', 'Where the waste came from', 'eutex:WasteOriginType'),
106
+ code('eutex:hasRecycledSourceType', 'Recycling route', 'eutex:RecycledSourceType'),
107
+ code('eutex:hasChainOfCustodyMethod', 'Chain of custody', 'eutex:ChainOfCustodyMethod'),
108
+ yesNo('eutex:meetsTargetThreshold', 'Meets the target'),
109
+ group('eutex:hasVerificationCertification', 'Certificate', 'gs1:CertificationDetails', [text('gs1:certificationAgency', 'Issued by'), text('gs1:certificationStandard', 'Standard'), text('gs1:certificationIdentification', 'Certificate number')]),
110
+ ])
111
+ ),
112
+ ],
113
+ },
114
+ {
115
+ title: 'Care',
116
+ description: 'One symbol for each treatment, from the profile\'s care symbols.',
117
+ fields: [
118
+ group('eutex:hasCareInstructions', 'Care instructions', 'eutex:CareInstruction', [
119
+ url('id', 'Identifier of the care instructions', { help: 'Optional. A web address that identifies them, if they have one.' }),
120
+ careSymbol('eutex:hasWashingSymbol', 'Washing', 'Wash'),
121
+ careSymbol('eutex:hasBleachingSymbol', 'Bleaching', 'Bleach'),
122
+ careSymbol('eutex:hasDryingSymbol', 'Drying', '^(TumbleDry|DoNotTumbleDry|LineDry|DryFlat|DripDry)'),
123
+ careSymbol('eutex:hasIroningSymbol', 'Ironing', 'Iron|Steam'),
124
+ careSymbol('eutex:hasDryCleaningSymbol', 'Professional cleaning', 'DryClean|WetClean'),
125
+ langText('eutex:additionalCareInstructions', 'Further instructions'),
126
+ ]),
127
+ ],
128
+ },
129
+ {
130
+ title: 'Durability',
131
+ description: 'Each test is a method, what it measured and the result with its unit. A grade on a scale is a value in the unit "one".',
132
+ fields: [
133
+ group('eutex:hasDurabilityInfo', 'Durability', 'eutex:DurabilityInfo', [
134
+ url('id', 'Identifier of the durability record', { help: 'Optional. A web address that identifies it, if it has one.' }),
135
+ list('oea:hasSubAssessment', 'Tests', 'test', test(false)),
136
+ list('oea:hasIndicator', 'Ratings and figures', 'rating', indicator({ class: 'eutex:DurabilityClass' })),
137
+ ]),
138
+ group('eutex:hasRobustnessAssessment', 'Robustness after washing', 'eutex:RobustnessAssessment', [
139
+ url('id', 'Identifier of the assessment', { help: 'Optional. A web address that identifies it, if it has one.' }),
140
+ fixed('oea:hasMethod', reference('eutex:JRCRobustnessScoring')),
141
+ list('oea:hasSubAssessment', 'Tests', 'test', test(true), { help: 'At most three: spirality, dimensional change and appearance after washing.' }),
142
+ ]),
143
+ group('eutex:hasMicroplasticInfo', 'Microfibre shedding', 'eutex:MicroplasticInfo', [
144
+ url('id', 'Identifier of the record', { help: 'Optional. A web address that identifies it, if it has one.' }),
145
+ code('oea:hasMethod', 'Test method', { class: 'oea:TestMethod', prefix: 'eutex:' }),
146
+ measurement('oea:hasResult', 'Result', 'eutex:'),
147
+ group('oea:hasIndicator', 'Shedding risk', 'oea:Indicator', [fixed('oea:hasIndicatorKind', reference('eutex:SheddingRiskLevel')), code('oea:hasCategoricalValue', 'Level', 'eutex:MicroplasticRiskLevel')]),
148
+ decimal('eutex:syntheticFiberContent', 'Synthetic fibre share', { help: 'A percentage, from 0 to 100.' }),
149
+ langText('eutex:microplasticMitigationMeasures', 'What reduces shedding'),
150
+ ]),
151
+ ],
152
+ },
153
+ {
154
+ title: 'Environment and substances',
155
+ fields: [
156
+ decimal('oec:carbonFootprintTotal', 'Carbon footprint', { help: 'A number, in the unit named in the next field.' }),
157
+ text('oec:declaredUnit', 'Unit of the carbon footprint'),
158
+ url('oec:carbonFootprintStudyUrl', 'Carbon footprint study'),
159
+ quantity('eutex:hasWaterUsage', 'Water used in production', ['LTR']),
160
+ quantity('eutex:hasEnergyUsage', 'Energy used in production', ['KWH']),
161
+ decimal('eutex:productionWastePercentage', 'Production waste', { help: 'A percentage.' }),
162
+ yesNo('eutex:pfasFree', 'Free of PFAS'),
163
+ yesNo('eutex:biodegradable', 'Biodegradable'),
164
+ list(
165
+ 'eutex:hasSubstancesOfConcern',
166
+ 'Substances of concern',
167
+ 'substance',
168
+ entry('eutex:SubstanceOfConcern', [
169
+ url('id', 'Identifier of the entry', { help: 'Optional. A web address that identifies it, if it has one.' }),
170
+ code('eutex:hasSocType', 'Type', 'eutex:SubstanceOfConcernType', { required: true }),
171
+ text('schema:name', 'Name', { required: true }),
172
+ text('schema:iupacName', 'IUPAC name'),
173
+ text('oec:casNumber', 'CAS number'),
174
+ text('oec:ecNumber', 'EC number'),
175
+ decimal('eutex:substanceConcentration', 'Concentration', { help: 'A percentage of the weight.' }),
176
+ decimal('eutex:maxConcentration', 'Highest concentration', { help: 'A percentage of the weight.' }),
177
+ code('eutex:hasClpHazardCategory', 'Hazard category', 'eutex:CLPHazardCategory'),
178
+ text('oec:substanceLocation', 'Where in the garment'),
179
+ text('eutex:safeUseInstructions', 'Safe use'),
180
+ text('eutex:endOfLifeHandling', 'Handling at end of life'),
181
+ ])
182
+ ),
183
+ ],
184
+ },
185
+ {
186
+ title: 'Repair, take-back and recycling',
187
+ fields: [
188
+ yesNo('eutex:isRepairable', 'Can be repaired'),
189
+ url('eutex:repairGuideUrl', 'Repair guide'),
190
+ yesNo('eutex:sparePartsAvailable', 'Spare parts available'),
191
+ url('eutex:sparePartsUrl', 'Spare parts'),
192
+ list('eutex:hasRepairServices', 'Repair services', 'repair service', entry('gs1:Organization', [url('id', 'Identifier of the service', { help: 'Optional. A web address that identifies it, if it has one.' }), text('gs1:organizationName', 'Name', { required: true }), address(), contact()])),
193
+ yesNo('eutex:takeBackProgramAvailable', 'Take-back programme'),
194
+ group('eutex:hasTakeBackProgram', 'Take-back programme details', 'eutex:TakeBackProgram', [
195
+ url('id', 'Identifier of the programme', { help: 'Optional. A web address that identifies it, if it has one.' }),
196
+ url('eutex:takeBackUrl', 'Web address'),
197
+ langText('eutex:takeBackIncentive', 'What the customer gets'),
198
+ langText('eutex:endOfLifeDestination', 'What happens to returned items'),
199
+ ]),
200
+ list('gs1:consumerRecyclingInstructions', 'Recycling instructions', 'instruction', langText('', 'Instruction')),
201
+ group('oec:hasRepairabilityInfo', 'Repairability', 'oec:RepairabilityInfo', [
202
+ quantity('oec:hasSparePartsAvailability', 'Spare parts are available for', ['ANN', 'MON']),
203
+ yesNo('oec:diyRepairPossible', 'Can be repaired at home'),
204
+ url('oec:professionalRepairNetwork', 'Repair network'),
205
+ list('oea:hasIndicator', 'Ratings and figures', 'rating', indicator({ options: [] })),
206
+ ]),
207
+ ],
208
+ },
209
+ {
210
+ title: 'Certificates, documents and warranty',
211
+ fields: [
212
+ list('gs1:certification', 'Certificates', 'certificate', certificate()),
213
+ warranty(),
214
+ list(
215
+ 'oec:hasDocuments',
216
+ 'Documents',
217
+ 'document',
218
+ entry('oec:DocumentReference', [
219
+ url('id', 'Identifier of the document', { help: 'A web address that identifies the document, usually its own address.' }),
220
+ code('oec:hasDocumentType', 'Kind of document', 'oec:DocumentType'),
221
+ url('oec:documentUrl', 'Web address'),
222
+ text('schema:name', 'Title'),
223
+ text('oec:mimeType', 'File type'),
224
+ text('oec:languageCode', 'Language code'),
225
+ date('oec:issueDate', 'Issued on'),
226
+ ])
227
+ ),
228
+ referencedFiles(),
229
+ group('oec:hasAccessRights', 'Access rights statement', 'oec:AccessRights', [code('oec:hasAccessLevel', 'Access level', 'oec:AccessLevel')], {
230
+ help: 'A statement inside the document. It does not decide what this application publishes: that is the Public and Restricted labels.',
231
+ }),
232
+ text('oec:dataQualityAssessment', 'Data quality rating'),
233
+ ],
234
+ },
235
+ ],
236
+ }
@@ -0,0 +1,37 @@
1
+ // The UN/CEFACT unit codes the sector forms offer, with a name for each. A
2
+ // measurement is written with the code; the name is for the page. A form
3
+ // lists the codes that suit each measurement and never chooses one itself.
4
+
5
+ export const UNITS: Record<string, string> = {
6
+ KGM: 'kilogram',
7
+ GRM: 'gram',
8
+ MGM: 'milligram',
9
+ TNE: 'tonne',
10
+ LTR: 'litre',
11
+ MTQ: 'cubic metre',
12
+ MTR: 'metre',
13
+ CMT: 'centimetre',
14
+ MMT: 'millimetre',
15
+ AMH: 'ampere hour',
16
+ AMP: 'ampere',
17
+ VLT: 'volt',
18
+ OHM: 'ohm',
19
+ WTT: 'watt',
20
+ KWT: 'kilowatt',
21
+ WHR: 'watt hour',
22
+ KWH: 'kilowatt hour',
23
+ CEL: 'degree Celsius',
24
+ NEW: 'newton',
25
+ P1: 'per cent',
26
+ C62: 'one (a count or a grade)',
27
+ ANN: 'year',
28
+ MON: 'month',
29
+ DAY: 'day',
30
+ HUR: 'hour',
31
+ MIN: 'minute',
32
+ }
33
+
34
+ /** Every unit, for a measurement whose unit depends on what was measured. */
35
+ export const ANY_UNIT: string[] = Object.keys(UNITS)
36
+
37
+ export const unitName = (code: string): string => UNITS[code] ?? code
@@ -0,0 +1,345 @@
1
+ // EPCIS exchange as the pages see it: the shapes the API answers with under
2
+ // /api/epcis, and the words the pages put on them.
3
+ //
4
+ // The words matter more than usual here. An event on these pages is data a
5
+ // source supplied. A document that is "valid" passed a check of its format.
6
+ // It is not signed, and nothing verifies who observed an event or that it
7
+ // happened. Every label below is written so that a reader cannot take one
8
+ // for the other.
9
+ //
10
+ // Nothing in this file touches the page or the network, so the API's tests
11
+ // exercise it (apps/api/test/epcis-web.test.ts).
12
+
13
+ // ------------------------------------------------------------------ shapes
14
+
15
+ export interface EpcisFinding {
16
+ code: string
17
+ path: string
18
+ message: string
19
+ severity: 'error' | 'warning' | 'info'
20
+ }
21
+
22
+ export type EpcisProvenance = { kind: 'file'; filename?: string } | { kind: 'query'; origin: string; query: Record<string, string>; page: number }
23
+
24
+ export interface EpcisImportEvent {
25
+ pointer: string
26
+ eventId?: string
27
+ identity: string
28
+ identityKind: 'event-id' | 'local'
29
+ eventType: string
30
+ eventTime?: string
31
+ recordTime?: string
32
+ /** The members of the event the EPCIS schema does not name. They are kept as received. */
33
+ preservedExtensions: string[]
34
+ validation: { schema: 'pass' | 'fail'; findings: EpcisFinding[] }
35
+ arrival?: 'new' | 'duplicate' | 'new-observation' | 'conflict'
36
+ conflict?: { conflictId: string; state: 'open' | 'resolved'; resolution?: string }
37
+ errorDeclaration?: { reason?: string; resolution: 'resolved' | 'unresolved' }
38
+ }
39
+
40
+ export interface EpcisImportRecord {
41
+ importId: string
42
+ requestId: string
43
+ sourceId: string
44
+ receivedAt: string
45
+ mediaType: string
46
+ byteLength: number
47
+ sha256: string
48
+ sourceLocation: EpcisProvenance
49
+ state: 'received' | 'evaluated' | 'blocked'
50
+ /** Whether the document passed the format check. It says nothing about who made it. */
51
+ documentValidity: 'valid' | 'invalid'
52
+ findings: EpcisFinding[]
53
+ preservedExtensions: string[]
54
+ events: EpcisImportEvent[]
55
+ }
56
+
57
+ export interface EpcisImportSummary {
58
+ importId: string
59
+ sourceId: string
60
+ requestId: string
61
+ receivedAt: string
62
+ mediaType: string
63
+ byteLength: number
64
+ sha256: string
65
+ provenance: EpcisProvenance
66
+ state: EpcisImportRecord['state']
67
+ documentValidity: 'valid' | 'invalid'
68
+ events: number
69
+ findings: number
70
+ conflicts: number
71
+ }
72
+
73
+ export interface EpcisImportAnswer {
74
+ outcome: 'retained'
75
+ /** The request identifier had been used before for the same bytes. */
76
+ replayed: boolean
77
+ resumed: boolean
78
+ record: EpcisImportRecord
79
+ }
80
+
81
+ export interface EpcisSource {
82
+ sourceId: string
83
+ baseUrl: string
84
+ permittedOrigins: string[]
85
+ /** Plain http and private addresses are permitted for this source. For a source on the operator's own machine only. */
86
+ localTest: boolean
87
+ repeatListParameters: boolean
88
+ credentialConfigured: boolean
89
+ credentialScheme?: 'bearer' | 'basic' | 'header'
90
+ problem?: string
91
+ }
92
+
93
+ export interface EpcisStatus {
94
+ storage: 'mongodb' | 'file' | 'memory' | 'supplied'
95
+ artefacts: { dir: string; state: 'present' | 'fetched' | 'unavailable'; files: Array<{ fileName: string; outcome: string; reason?: string }>; remedy?: string }
96
+ recovery: { actions: Array<{ action: string }>; remaining: number }
97
+ sources: EpcisSource[]
98
+ policy: string
99
+ }
100
+
101
+ export interface EpcisEventCounts {
102
+ total: number
103
+ new: number
104
+ duplicate: number
105
+ newObservation: number
106
+ conflict: number
107
+ }
108
+
109
+ export interface EpcisPullPage {
110
+ sequence: number
111
+ page: number
112
+ importId: string
113
+ sha256: string
114
+ byteLength: number
115
+ documentValidity: 'valid' | 'invalid'
116
+ events: EpcisEventCounts
117
+ last: boolean
118
+ leniencies: string[]
119
+ }
120
+
121
+ export interface EpcisPullState {
122
+ pullId: string
123
+ sourceId: string
124
+ queryId: string
125
+ status: 'running' | 'exhausted' | 'stopped-at-limit' | 'failed'
126
+ pagesAcknowledged: number
127
+ runs: number
128
+ totals: { bytes: number; events: EpcisEventCounts }
129
+ completenessLimits: string[]
130
+ updatedAt: string
131
+ }
132
+
133
+ /** One run of a pull, as the module reports it. Every word in it is the module's. */
134
+ export interface EpcisPullResult {
135
+ outcome: string
136
+ reason: string
137
+ completion: 'exhausted' | 'stopped-at-limit' | 'failed'
138
+ /** True only when the source named no further page. Never a statement that the source's history is complete. */
139
+ exhausted: boolean
140
+ detail: string
141
+ status?: number
142
+ importRefusal?: string
143
+ sourceId: string
144
+ queryId: string
145
+ pull?: EpcisPullState
146
+ run: { run: number; resumed: boolean; pagesFetched: number; pagesAcknowledged: number; bytesRead: number }
147
+ pages: EpcisPullPage[]
148
+ events: EpcisEventCounts
149
+ localTest: boolean
150
+ leniencies: string[]
151
+ completenessLimits: string[]
152
+ }
153
+
154
+ export interface EpcisPullQuery {
155
+ matchAnyEPC?: string[]
156
+ eventTypes?: string[]
157
+ eventTime?: { from?: string; until?: string }
158
+ recordTime?: { from?: string }
159
+ eventIds?: string[]
160
+ perPage?: number
161
+ }
162
+
163
+ export interface EpcisEventEntry {
164
+ association: { identifier: string; granularity: 'instance' | 'class'; role: string; eventType: string; eventTime?: string; pointer: string; sourceId: string; importId: string; errorDeclared: boolean; quantity?: number; uom?: string }
165
+ source: { importId: string; sourceId: string; receivedAt: string; documentValidity: 'valid' | 'invalid'; state: string; provenance: EpcisProvenance; sha256: string }
166
+ event?: EpcisImportEvent
167
+ /** The event as the retained document holds it, extension members included. */
168
+ body?: unknown
169
+ }
170
+
171
+ export interface EpcisEventsAnswer {
172
+ identifier: string
173
+ granularity: 'instance' | 'class'
174
+ nature: 'supplied-data'
175
+ notice: string
176
+ events: EpcisEventEntry[]
177
+ next?: string
178
+ }
179
+
180
+ // ------------------------------------------------------------------ words
181
+
182
+ export type EpcisTone = 'pass' | 'fail' | 'warn' | 'neutral' | 'muted'
183
+
184
+ export interface Described {
185
+ tone: EpcisTone
186
+ title: string
187
+ lines: string[]
188
+ }
189
+
190
+ const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
191
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
192
+
193
+ /** What every list of events says above it. */
194
+ export const SUPPLIED_DATA_NOTICE =
195
+ 'These events are data a source supplied: a file someone uploaded, or pages pulled from a configured source. Nobody signed them here. Not the holder of this passport, not its brand and not the source. "Valid format" means the document passed a check of its shape. It does not mean the event happened, or that anyone verified who reported it.'
196
+
197
+ /** The label of a document's validity. It names the check that was made, so "valid" is never read as "verified". */
198
+ export function validityLabel(documentValidity: 'valid' | 'invalid'): { tone: EpcisTone; label: string } {
199
+ return documentValidity === 'valid' ? { tone: 'neutral', label: 'Valid format, unsigned' } : { tone: 'warn', label: 'Invalid format, unsigned' }
200
+ }
201
+
202
+ export function provenanceLabel(provenance: EpcisProvenance): string {
203
+ if (provenance.kind === 'file') return provenance.filename == null ? 'Uploaded file' : `Uploaded file ${provenance.filename}`
204
+ return `Page ${provenance.page} of a query to ${provenance.origin}`
205
+ }
206
+
207
+ export function countsLine(counts: EpcisEventCounts): string {
208
+ if (counts.total === 0) return 'No events.'
209
+ return `${plural(counts.total, 'event')}: ${counts.new} new, ${counts.duplicate} already held, ${counts.newObservation} observed again, ${counts.conflict} in conflict.`
210
+ }
211
+
212
+ /** How the events of one import arrived. */
213
+ export const eventCounts = (record: EpcisImportRecord): EpcisEventCounts => ({
214
+ total: record.events.length,
215
+ new: record.events.filter((event) => event.arrival === 'new').length,
216
+ duplicate: record.events.filter((event) => event.arrival === 'duplicate').length,
217
+ newObservation: record.events.filter((event) => event.arrival === 'new-observation').length,
218
+ conflict: record.events.filter((event) => event.arrival === 'conflict').length,
219
+ })
220
+
221
+ export const findingsOf = (record: EpcisImportRecord): EpcisFinding[] => [...record.findings, ...record.events.flatMap((event) => event.validation.findings)]
222
+
223
+ /** An upload the API kept: what is held, whether it passed the format check, and what that does and does not mean. */
224
+ export function describeRetained(answer: EpcisImportAnswer): Described {
225
+ const { record } = answer
226
+ const findings = findingsOf(record)
227
+ const open = record.events.filter((event) => event.conflict?.state === 'open').length
228
+ const lines = [`The exact bytes are kept: ${record.byteLength} bytes, SHA-256 ${record.sha256}.`]
229
+ if (answer.replayed) lines.push('This request identifier was already used for the same bytes, so this is the import made then. No second copy was kept.')
230
+ lines.push(
231
+ record.documentValidity === 'valid'
232
+ ? 'The document passed the format check. That is a check of its shape. It is not signed, and nothing here verifies who made it or that its events happened.'
233
+ : `The document was kept and did not pass the format check. ${plural(findings.length, 'finding')} say why. Its events are not listed against products.`
234
+ )
235
+ lines.push(countsLine(eventCounts(record)))
236
+ if (open > 0) lines.push(`${plural(open, 'event')} arrived with another body than the one already held under the same identifier. Both are kept until someone records a decision.`)
237
+ lines.push('Nothing was signed, issued or written to a passport.')
238
+ return { tone: record.documentValidity === 'valid' && open === 0 ? 'pass' : 'warn', title: answer.replayed ? 'Already retained' : 'Retained', lines }
239
+ }
240
+
241
+ /** An upload the API refused. `code`, `message` and `details` are the API's error, which carries the module's reason. */
242
+ export function describeRefusal(error: { code: string; message: string; details?: Record<string, unknown> }): Described {
243
+ const remedy = typeof error.details?.remedy === 'string' ? error.details.remedy : undefined
244
+ if (error.code === 'request-conflict') return { tone: 'fail', title: 'Refused: this request identifier is already used for other bytes', lines: [error.message, 'Nothing of this upload was kept. Choose the file again to send it as a new request.'] }
245
+ return { tone: 'fail', title: `Refused: ${error.code}`, lines: [error.message, ...(remedy == null ? [] : [remedy]), 'Nothing was kept.'] }
246
+ }
247
+
248
+ /**
249
+ * One run of a pull, in the module's own words: its outcome, reason and
250
+ * completion are shown as they are. The only thing added is the plain
251
+ * statement of whether the history is partial, which is never left to be
252
+ * inferred from a colour.
253
+ */
254
+ export function describePull(result: EpcisPullResult): Described & { partial: boolean } {
255
+ const partial = !result.exhausted
256
+ const lines = [result.detail]
257
+ lines.push(
258
+ partial
259
+ ? 'History is partial: this run ended before the source named a last page. What is held is what the pages retained so far carry.'
260
+ : 'The source named no further page for this query. That is the end of this query, and not a statement that the source holds nothing else.'
261
+ )
262
+ lines.push(`${plural(result.pages.length, 'page')} retained in this run. ${countsLine(result.events)}`)
263
+ if (result.run.resumed) lines.push(`This was run ${result.run.run}. It continued from where the run before it stopped.`)
264
+ if (result.localTest) lines.push('The local-test option is on for this source: plain http and private addresses were permitted.')
265
+ if (result.leniencies.length > 0) lines.push(`Accepted leniently: ${result.leniencies.join(', ')}.`)
266
+ for (const limit of result.completenessLimits) lines.push(`Not complete history: ${limit}.`)
267
+ lines.push('Nothing was signed, issued or written to a passport.')
268
+ const tone: EpcisTone = result.outcome === 'ok' ? 'pass' : result.outcome === 'partial-history' ? 'warn' : result.pages.length > 0 ? 'warn' : 'fail'
269
+ return { tone, title: `${result.outcome}: ${result.reason} (${result.completion})`, lines, partial }
270
+ }
271
+
272
+ /** A pull the API refused before anything was requested. */
273
+ export function describePullRefusal(error: { code: string; message: string; details?: Record<string, unknown> }): Described {
274
+ const remedy = typeof error.details?.remedy === 'string' ? error.details.remedy : undefined
275
+ return { tone: 'fail', title: `Refused: ${error.code}`, lines: [error.message, ...(remedy == null ? [] : [remedy]), 'Nothing was requested from the source, and nothing was kept.'] }
276
+ }
277
+
278
+ export function describeSource(source: EpcisSource): string[] {
279
+ const lines = [`Queries go to ${source.baseUrl}/events.`, `Requests may go to: ${source.permittedOrigins.join(', ')}.`]
280
+ lines.push(source.credentialConfigured ? `A credential is set on the server${source.credentialScheme == null ? '' : ` (${source.credentialScheme})`}. It is never sent to this page.` : 'No credential is set.')
281
+ if (source.localTest) lines.push('Local test is on: plain http and private addresses are permitted. Use it only for a source on your own machine.')
282
+ if (source.repeatListParameters) lines.push('Lists are sent as repeated parameters, which is recorded as a leniency.')
283
+ if (source.problem != null) lines.push(`This source cannot be pulled from as it is configured: ${source.problem}.`)
284
+ return lines
285
+ }
286
+
287
+ /** The extension members of an event, with their values as the retained document holds them. None is dropped: a name without a value is still listed. */
288
+ export function extensionMembers(entry: Pick<EpcisEventEntry, 'event' | 'body'>): Array<{ name: string; value: unknown; held: boolean }> {
289
+ const names = entry.event?.preservedExtensions ?? []
290
+ const body = isRecord(entry.body) ? entry.body : undefined
291
+ return names.map((name) => (body != null && Object.hasOwn(body, name) ? { name, value: body[name], held: true } : { name, value: undefined, held: false }))
292
+ }
293
+
294
+ /**
295
+ * The spellings of a passport's identifier that are searched for events. An
296
+ * event is found only under the exact identifier it writes, so the passport
297
+ * page says which spellings it looked for: the passport's own, and the same
298
+ * path at GS1's own resolver. An event that writes the product another way,
299
+ * as an EPC URN for one, is found by searching for that spelling.
300
+ */
301
+ export function passportSpellings(passportId: string): string[] {
302
+ const out = [passportId]
303
+ try {
304
+ const url = new URL(passportId)
305
+ const canonical = `https://id.gs1.org${url.pathname}`
306
+ if (/^\/01\/\d+/.test(url.pathname) && canonical !== passportId) out.push(canonical)
307
+ } catch {
308
+ // Not an address: only the identifier itself is searched.
309
+ }
310
+ return out
311
+ }
312
+
313
+ /** The media type an upload is sent under. The API refuses anything that is not one of the two EPCIS media types, in the module's words. */
314
+ export function mediaTypeOf(file: { name: string; type: string }): string {
315
+ const declared = file.type.split(';')[0]?.trim().toLowerCase() ?? ''
316
+ if (declared === 'application/ld+json' || declared === 'application/json') return declared
317
+ if (/\.jsonld$/i.test(file.name)) return 'application/ld+json'
318
+ if (/\.json$/i.test(file.name)) return 'application/json'
319
+ return declared === '' ? 'application/octet-stream' : declared
320
+ }
321
+
322
+ const entries = (text: string): string[] =>
323
+ text
324
+ .split(/[\n,]/)
325
+ .map((entry) => entry.trim())
326
+ .filter((entry) => entry !== '')
327
+
328
+ /** The query a pull form describes. A field left empty is left out, so the query asks for no more than was entered. */
329
+ export function queryFromForm(form: { identifiers: string; eventTypes: string; eventIds: string; from: string; until: string; perPage: string }): EpcisPullQuery {
330
+ const query: EpcisPullQuery = {}
331
+ if (entries(form.identifiers).length > 0) query.matchAnyEPC = entries(form.identifiers)
332
+ if (entries(form.eventTypes).length > 0) query.eventTypes = entries(form.eventTypes)
333
+ if (entries(form.eventIds).length > 0) query.eventIds = entries(form.eventIds)
334
+ const from = form.from.trim()
335
+ const until = form.until.trim()
336
+ if (from !== '' || until !== '') query.eventTime = { ...(from === '' ? {} : { from }), ...(until === '' ? {} : { until }) }
337
+ const perPage = Number(form.perPage.trim())
338
+ if (form.perPage.trim() !== '' && Number.isInteger(perPage) && perPage > 0) query.perPage = perPage
339
+ return query
340
+ }
341
+
342
+ /** Imports, the latest first. */
343
+ export const latestFirst = (imports: EpcisImportSummary[]): EpcisImportSummary[] => [...imports].sort((a, b) => (a.receivedAt < b.receivedAt ? 1 : a.receivedAt > b.receivedAt ? -1 : 0))
344
+
345
+ export const originalPath = (importId: string): string => `/api/epcis/imports/${encodeURIComponent(importId)}/original`