@percayso/identity-contracts 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # `@percayso/identity-contracts`
2
+
3
+ The published vocabulary of **Percayso ID**: identifiers, closed lifecycle states, the
4
+ closed refusal union, the evidence vocabulary, and a thin read-only client.
5
+
6
+ Wire types and decoders only. There is no server, no policy engine and no verifier
7
+ here — this package describes what crosses the wire, and nothing that decides.
8
+
9
+ > **`0.x`, and it means it.** The shape may change between minor versions while the
10
+ > API it describes is still being built. Pin the exact version.
11
+
12
+ ## What is in it
13
+
14
+ | Module | What it publishes |
15
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
16
+ | `ids` | Branded identifiers — Citizen ID, Application, Verification Case, Deployment, Piper Platform subject, Handle (canonical and display), Community email address, correlation reference |
17
+ | `application` | Application states and the transitions permitted between them |
18
+ | `citizen` | Citizen status, the Citizen record, a Citizen's names, and the `Personhood` union |
19
+ | `evidence` | Evidence facts, the outcome union, and the rule that a verification method never claims more than its facts support |
20
+ | `provisioning` | Provisioning-coordination states and Cayso's confirmation |
21
+ | `refusal` | The closed refusal union, whether a refusal is appealable, and `ContractResult` |
22
+ | `assertion` | The operations, the scope, the request an issuer is asked for, and the issuance record |
23
+ | `client` | Five reads over the routes above, at `@percayso/identity-contracts/client` |
24
+
25
+ ```ts
26
+ import {
27
+ parseCitizenId,
28
+ type ContractResult,
29
+ type Personhood,
30
+ } from "@percayso/identity-contracts";
31
+ import { createIdentityClient } from "@percayso/identity-contracts/client";
32
+ ```
33
+
34
+ Every invariant here is enforced **twice**: once as a shape that cannot be expressed,
35
+ and once as a value a decoder refuses. A type cannot police JSON that arrived from a
36
+ caller nobody controls, and a decoder cannot stop a programmer writing the wrong
37
+ identifier into the right field.
38
+
39
+ ## The dependency shape, and why
40
+
41
+ Assertion, assurance and operation types are **imported from `@cayso/contracts`**,
42
+ never restated — and this package has **no runtime dependencies**. Those two
43
+ requirements pull in opposite directions, so the resolution is written down rather
44
+ than left to whoever reads the manifest.
45
+
46
+ `@cayso/contracts` is declared as a **`peerDependency` and a `devDependency`**, both
47
+ pinned exactly to `0.6.1`. It is **never** a `dependency`.
48
+
49
+ - **Why not `dependencies`.** That would make it a runtime dependency — installed
50
+ transitively, resolvable to a second copy, and present in the dependency tree of
51
+ every consumer that only wanted a type.
52
+ - **Why not `devDependencies` alone.** Every Cayso type this package re-exposes
53
+ appears in its published `.d.ts` files. A consumer without `@cayso/contracts`
54
+ installed would get a typecheck failure at a name they never wrote. A peer
55
+ declaration says so at install time, where it will be read.
56
+ - **Why also `devDependencies`.** A peer range is not installed for this package's own
57
+ build and test run.
58
+ - **Why exact.** A range on a contract package is a contract that changes without a
59
+ version bump.
60
+
61
+ **Nothing is imported in value position.** Every `@cayso/contracts` import is
62
+ `import type`, and the packaging suite unpacks the real `npm pack` tarball and asserts
63
+ that no emitted `.js` module imports or requires it. Install this package with no peer
64
+ present and the JavaScript still runs; only the types go missing, which is exactly
65
+ what a peer declaration promises.
66
+
67
+ The cost is that a handful of Cayso runtime values are written out by hand — the
68
+ verification methods, the contract operations, the evidence-to-method rule. Each is
69
+ pinned to the sibling's by a test, in both directions, so a value added upstream fails
70
+ this package's test run rather than passing through it silently.
71
+
72
+ ## Licensing
73
+
74
+ This package is **Apache-2.0** and carries its own `LICENSE`.
75
+
76
+ **The grant covers this package's own files and nothing else.** It is not a licence to
77
+ the repository this package is built from, which is private and separately licensed.
78
+ Read it as covering what is in this tarball, because that is what it covers.
79
+
80
+ ## What it deliberately does not contain
81
+
82
+ - **No server, no policy engine, no verifier.** Wire types, closed unions and a thin
83
+ client. A verifier here would be a second implementation of a rule that belongs to
84
+ the service that owns it.
85
+ - **No write methods.** The client reads. A method posting to a route nobody serves
86
+ yet would look like a commitment.
87
+ - **No figures.** No Handle length bound, no assertion lifetime ceiling, no rate-limit
88
+ limit, no grant amount. The assertion decoder refuses an expiry that is not after
89
+ issuance and says nothing about how much after.
90
+ - **No authenticator policy.** No authenticator type, no "onboarding complete"
91
+ predicate, and no field that would carry one — so nothing here can declare onboarding
92
+ complete, and no fixture works by assuming a rule that has not been set.
93
+ - **No evidence-supplier vocabulary.** `EvidenceRoute` and `EvidencePolicyVersion` are
94
+ opaque versioned identifiers rather than closed unions, so no supplier's selection
95
+ identifier is shipped into every consumer.
96
+ - **No password, anywhere.** No password field, no reset path, no email-and-password
97
+ fallback — not behind a flag and not in a fixture. A test asserts that no published
98
+ name could hold one and that a closed record refuses one on the wire.
99
+ - **No rate-limit policy.** This package is the caller's side of a conversation. The
100
+ service that exposes these routes declares its own limits.
101
+
102
+ ## Publishing
103
+
104
+ Published manually, never on merge, and dry run by default.
105
+
106
+ ---
107
+
108
+ Percayso Communities Limited
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The Application: its closed lifecycle, its transitions, and the one state that
3
+ * creates a Citizen.
4
+ *
5
+ * §5.2 is the canon here, and it says three things this file has to make true rather
6
+ * than merely describe. "The Application and the Citizen are different records." "An
7
+ * Applicant must exist before a Citizen can, and **approval is the only transition
8
+ * that creates one**." "A retry creates a **new** Application linked to its
9
+ * predecessor. Evidence and decision history are never rewritten."
10
+ *
11
+ * ENFORCED TWICE, IN BOTH DIRECTIONS.
12
+ *
13
+ * The lifecycle is a closed union, so no state outside §5.2's diagram can be
14
+ * written; and `parseApplicationState` refuses any string outside the same list, so
15
+ * no state outside §5.2's diagram can arrive. §15 singles out one of those in
16
+ * particular — `applications` must not hold "a generic `pending` state" — and
17
+ * because `pending` is the state a reader most expects to find, `contract.test.ts`
18
+ * names it directly on both sides: it is not assignable, and it is refused.
19
+ *
20
+ * `ApprovedApplication` is the other half. It is a separate type whose `state` is
21
+ * the literal `"approved"` rather than an `ApplicationState`, which makes it
22
+ * unforgeable by widening: a `draft` Application is not assignable to it, so a
23
+ * function that creates a Citizen can ask for one and get §14.4's "No route, script,
24
+ * production fixture or flag creates a Citizen outside an Application" from the
25
+ * compiler. `parseApprovedApplication` is the runtime twin, and refuses every other
26
+ * state by name.
27
+ *
28
+ * WHAT THIS FILE DELIBERATELY DOES NOT CARRY.
29
+ *
30
+ * No transition performs anything. This package publishes the vocabulary, and the
31
+ * approval transaction belongs to the service — the one that commits the
32
+ * Application, Citizen, profile, Handle, email assignment, authenticators,
33
+ * provenance, document signal and coordination row together or not at all.
34
+ * `isApplicationTransitionPermitted` answers a question
35
+ * about the diagram; it does not move anything, and a consumer that treats a `true`
36
+ * from it as authority to transition has skipped the transaction §15 requires.
37
+ *
38
+ * No timers, no expiry figures. `draft --> expired` is in the diagram; how long a
39
+ * draft lives is not, and a figure invented here would become the one every
40
+ * consumer inherited.
41
+ */
42
+ import type { Millis } from "@cayso/contracts";
43
+ import { type ApplicationId, type CorrelationReference, type VerificationCaseId } from "./ids.js";
44
+ /**
45
+ * The Application lifecycle of §5.2, one member per node in its state diagram.
46
+ *
47
+ * There is no `pending`, and its absence is the point: §15 forbids `applications` a
48
+ * generic `pending` state, because "pending" collapses "nobody has submitted this
49
+ * yet", "a machine is looking at it" and "a Reviewer is looking at it" into one word
50
+ * that no Citizen-facing status text can honestly expand.
51
+ */
52
+ export type ApplicationState = "draft" | "submitted" | "automated_review" | "manual_review" | "approved" | "rejected" | "under_appeal" | "cancelled" | "expired";
53
+ /** Every Application state, in §5.2's order. A test that must cover them all reads this. */
54
+ export declare const APPLICATION_STATES: readonly ApplicationState[];
55
+ /**
56
+ * §5.2's diagram, transcribed edge for edge — and no edge that is not drawn there.
57
+ *
58
+ * The omissions carry the weight. `approved` has no outgoing edge, so an approved
59
+ * Application cannot be reopened, re-reviewed or quietly returned to `draft` to be
60
+ * decided again; whatever happens to the person afterwards happens to their Citizen
61
+ * record, under §5.3, and not by rewriting the decision that created it. `cancelled`
62
+ * and `expired` have none either: §5.2 gives a retry "a **new** Application linked
63
+ * to its predecessor", so the route out of a dead Application is a successor record
64
+ * and never a resurrection of this one. `rejected --> under_appeal` is the single
65
+ * exception, because an appeal is §8.6's designed route rather than a re-run.
66
+ */
67
+ export declare const APPLICATION_TRANSITIONS: Readonly<Record<ApplicationState, readonly ApplicationState[]>>;
68
+ /**
69
+ * Whether §5.2 draws this edge.
70
+ *
71
+ * A state with no outgoing edge is terminal for THIS Application, which is not the
72
+ * same as terminal for the person: `isRetryable` says which terminal states §5.2
73
+ * permits a successor from.
74
+ */
75
+ export declare const isApplicationTransitionPermitted: (from: ApplicationState, to: ApplicationState) => boolean;
76
+ /** Whether §5.2 draws no edge out of this state. */
77
+ export declare const isTerminalApplicationState: (state: ApplicationState) => boolean;
78
+ /**
79
+ * Whether a person whose Application reached this state may hold a successor one.
80
+ *
81
+ * `approved` is excluded, and that exclusion is CONTEXT.md's "One human, one
82
+ * Citizen" seen from the Application side: a successor to an approved Application
83
+ * would be a second road to a second Citizen record for the same human. §5.1's
84
+ * "Rejected, cancelled and expired people remain associated with their Application"
85
+ * names the other three exactly.
86
+ */
87
+ export declare const isRetryable: (state: ApplicationState) => boolean;
88
+ /** A state name from a wire value, or a refusal. */
89
+ export declare const parseApplicationState: (value: unknown, field?: string) => ApplicationState;
90
+ /**
91
+ * What a caller may be told about an Application.
92
+ *
93
+ * Every field is here because §15's `applications` row lists it: the closed
94
+ * lifecycle, "predecessor link for retries", "continuation state and expiry", and
95
+ * the "opaque local-subject correlation". Its "must not hold" column is enforced by
96
+ * what is absent — there is no legal-identity field, no name, no document number and
97
+ * no evidence, so a browser-visible Application view has nowhere to put one, and
98
+ * `readClosedRecord` refuses a caller that invents somewhere.
99
+ *
100
+ * There is no `citizenId`, and that absence is §5.1's "They do not become Citizens,
101
+ * and they are not partial ones" in the type system. An Applicant with a Citizen ID
102
+ * field that happens to be null is a partial Citizen; an Applicant with no such
103
+ * field cannot be mistaken for one, and no consumer can read one out of an
104
+ * Application "just in case it is approved". The approved Application is a witness
105
+ * that a Citizen may be created (`ApprovedApplication`), never a Citizen record.
106
+ */
107
+ export interface ApplicationSummary {
108
+ readonly applicationId: ApplicationId;
109
+ readonly state: ApplicationState;
110
+ /**
111
+ * The Application this one retries, or `null` for a first attempt. §5.2: a retry
112
+ * is a new record linked to its predecessor, so the link points backwards and the
113
+ * predecessor is never edited.
114
+ */
115
+ readonly predecessorApplicationId: ApplicationId | null;
116
+ /**
117
+ * The opaque correlation reference of §15, or `null`. It correlates this
118
+ * Application with the local Piper Platform surface that started it. It is not a
119
+ * Piper Platform subject, is never an assertion subject, and carries no authority
120
+ * — which is why it is a `CorrelationReference` and not either identifier type.
121
+ */
122
+ readonly correlationReference: CorrelationReference | null;
123
+ /** When continuation stops being possible, if this state has such a moment. */
124
+ readonly expiresAt: Millis | null;
125
+ }
126
+ /** An `ApplicationSummary` from a wire value, or a refusal. */
127
+ export declare const parseApplicationSummary: (value: unknown, field?: string) => ApplicationSummary;
128
+ /**
129
+ * An Application that reached `approved`, and the only thing that permits a Citizen
130
+ * record to exist.
131
+ *
132
+ * `state` is the literal `"approved"` rather than an `ApplicationState`. That single
133
+ * difference is what makes the type unforgeable by widening: a value typed as
134
+ * `ApplicationSummary` is not assignable here even when its state happens to be
135
+ * approved at runtime, so the only routes in are this parser and a literal written
136
+ * by hand — and a literal written by hand in production code is a reviewable line
137
+ * that says `state: "approved"` next to an Application nobody approved.
138
+ *
139
+ * It carries the `VerificationCaseId` because §15's `citizens` row requires an
140
+ * `approved_verification_case_id`: the Citizen record must be able to name the
141
+ * evidence case that justified it, and a witness that omitted it would let a Citizen
142
+ * be created with nothing to point at.
143
+ */
144
+ export interface ApprovedApplication {
145
+ readonly applicationId: ApplicationId;
146
+ readonly state: "approved";
147
+ readonly verificationCaseId: VerificationCaseId;
148
+ }
149
+ /**
150
+ * An `ApprovedApplication` from a wire value, or a refusal.
151
+ *
152
+ * Every other lifecycle state is refused here, including the ones a reader might
153
+ * think are nearly approved: `manual_review` is a Reviewer still looking, and
154
+ * `under_appeal` is §8.6's route that has not concluded. Neither creates a Citizen.
155
+ */
156
+ export declare const parseApprovedApplication: (value: unknown, field?: string) => ApprovedApplication;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The Application: its closed lifecycle, its transitions, and the one state that
3
+ * creates a Citizen.
4
+ *
5
+ * §5.2 is the canon here, and it says three things this file has to make true rather
6
+ * than merely describe. "The Application and the Citizen are different records." "An
7
+ * Applicant must exist before a Citizen can, and **approval is the only transition
8
+ * that creates one**." "A retry creates a **new** Application linked to its
9
+ * predecessor. Evidence and decision history are never rewritten."
10
+ *
11
+ * ENFORCED TWICE, IN BOTH DIRECTIONS.
12
+ *
13
+ * The lifecycle is a closed union, so no state outside §5.2's diagram can be
14
+ * written; and `parseApplicationState` refuses any string outside the same list, so
15
+ * no state outside §5.2's diagram can arrive. §15 singles out one of those in
16
+ * particular — `applications` must not hold "a generic `pending` state" — and
17
+ * because `pending` is the state a reader most expects to find, `contract.test.ts`
18
+ * names it directly on both sides: it is not assignable, and it is refused.
19
+ *
20
+ * `ApprovedApplication` is the other half. It is a separate type whose `state` is
21
+ * the literal `"approved"` rather than an `ApplicationState`, which makes it
22
+ * unforgeable by widening: a `draft` Application is not assignable to it, so a
23
+ * function that creates a Citizen can ask for one and get §14.4's "No route, script,
24
+ * production fixture or flag creates a Citizen outside an Application" from the
25
+ * compiler. `parseApprovedApplication` is the runtime twin, and refuses every other
26
+ * state by name.
27
+ *
28
+ * WHAT THIS FILE DELIBERATELY DOES NOT CARRY.
29
+ *
30
+ * No transition performs anything. This package publishes the vocabulary, and the
31
+ * approval transaction belongs to the service — the one that commits the
32
+ * Application, Citizen, profile, Handle, email assignment, authenticators,
33
+ * provenance, document signal and coordination row together or not at all.
34
+ * `isApplicationTransitionPermitted` answers a question
35
+ * about the diagram; it does not move anything, and a consumer that treats a `true`
36
+ * from it as authority to transition has skipped the transaction §15 requires.
37
+ *
38
+ * No timers, no expiry figures. `draft --> expired` is in the diagram; how long a
39
+ * draft lives is not, and a figure invented here would become the one every
40
+ * consumer inherited.
41
+ */
42
+ import { parseCorrelationReference, readApplicationId, readVerificationCaseId, } from "./ids.js";
43
+ import { readClosedRecord, readMember, refuseValue } from "./parse.js";
44
+ /** Every Application state, in §5.2's order. A test that must cover them all reads this. */
45
+ export const APPLICATION_STATES = Object.freeze([
46
+ "draft",
47
+ "submitted",
48
+ "automated_review",
49
+ "manual_review",
50
+ "approved",
51
+ "rejected",
52
+ "under_appeal",
53
+ "cancelled",
54
+ "expired",
55
+ ]);
56
+ /**
57
+ * §5.2's diagram, transcribed edge for edge — and no edge that is not drawn there.
58
+ *
59
+ * The omissions carry the weight. `approved` has no outgoing edge, so an approved
60
+ * Application cannot be reopened, re-reviewed or quietly returned to `draft` to be
61
+ * decided again; whatever happens to the person afterwards happens to their Citizen
62
+ * record, under §5.3, and not by rewriting the decision that created it. `cancelled`
63
+ * and `expired` have none either: §5.2 gives a retry "a **new** Application linked
64
+ * to its predecessor", so the route out of a dead Application is a successor record
65
+ * and never a resurrection of this one. `rejected --> under_appeal` is the single
66
+ * exception, because an appeal is §8.6's designed route rather than a re-run.
67
+ */
68
+ export const APPLICATION_TRANSITIONS = Object.freeze({
69
+ draft: Object.freeze(["submitted", "expired"]),
70
+ submitted: Object.freeze(["automated_review", "cancelled"]),
71
+ automated_review: Object.freeze([
72
+ "manual_review",
73
+ "approved",
74
+ "rejected",
75
+ ]),
76
+ manual_review: Object.freeze(["approved", "rejected"]),
77
+ rejected: Object.freeze(["under_appeal"]),
78
+ under_appeal: Object.freeze(["approved", "rejected"]),
79
+ approved: Object.freeze([]),
80
+ cancelled: Object.freeze([]),
81
+ expired: Object.freeze([]),
82
+ });
83
+ /**
84
+ * Whether §5.2 draws this edge.
85
+ *
86
+ * A state with no outgoing edge is terminal for THIS Application, which is not the
87
+ * same as terminal for the person: `isRetryable` says which terminal states §5.2
88
+ * permits a successor from.
89
+ */
90
+ export const isApplicationTransitionPermitted = (from, to) => APPLICATION_TRANSITIONS[from].includes(to);
91
+ /** Whether §5.2 draws no edge out of this state. */
92
+ export const isTerminalApplicationState = (state) => APPLICATION_TRANSITIONS[state].length === 0;
93
+ /**
94
+ * Whether a person whose Application reached this state may hold a successor one.
95
+ *
96
+ * `approved` is excluded, and that exclusion is CONTEXT.md's "One human, one
97
+ * Citizen" seen from the Application side: a successor to an approved Application
98
+ * would be a second road to a second Citizen record for the same human. §5.1's
99
+ * "Rejected, cancelled and expired people remain associated with their Application"
100
+ * names the other three exactly.
101
+ */
102
+ export const isRetryable = (state) => state === "rejected" || state === "cancelled" || state === "expired";
103
+ /** A state name from a wire value, or a refusal. */
104
+ export const parseApplicationState = (value, field = "state") => {
105
+ if (typeof value !== "string" ||
106
+ !APPLICATION_STATES.includes(value)) {
107
+ refuseValue(field, `must be one of the ${APPLICATION_STATES.length} Application states of §5.2`);
108
+ }
109
+ return value;
110
+ };
111
+ const APPLICATION_SUMMARY_FIELDS = Object.freeze([
112
+ "applicationId",
113
+ "state",
114
+ "predecessorApplicationId",
115
+ "correlationReference",
116
+ "expiresAt",
117
+ ]);
118
+ const readOptionalMillis = (record, field, key) => {
119
+ const value = record[key];
120
+ if (value === null) {
121
+ return null;
122
+ }
123
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
124
+ refuseValue(`${field}.${key}`, "must be null or a non-negative integer count of milliseconds");
125
+ }
126
+ return value;
127
+ };
128
+ /** An `ApplicationSummary` from a wire value, or a refusal. */
129
+ export const parseApplicationSummary = (value, field = "application") => {
130
+ const record = readClosedRecord(value, field, APPLICATION_SUMMARY_FIELDS);
131
+ const predecessor = record["predecessorApplicationId"];
132
+ const correlation = record["correlationReference"];
133
+ return {
134
+ applicationId: readApplicationId(record, field, "applicationId"),
135
+ state: readMember(record, field, "state", APPLICATION_STATES),
136
+ predecessorApplicationId: predecessor === null
137
+ ? null
138
+ : readApplicationId(record, field, "predecessorApplicationId"),
139
+ correlationReference: correlation === null
140
+ ? null
141
+ : parseCorrelationReference(typeof correlation === "string"
142
+ ? correlation
143
+ : refuseValue(`${field}.correlationReference`, "must be null or a string"), `${field}.correlationReference`),
144
+ expiresAt: readOptionalMillis(record, field, "expiresAt"),
145
+ };
146
+ };
147
+ const APPROVED_APPLICATION_FIELDS = Object.freeze([
148
+ "applicationId",
149
+ "state",
150
+ "verificationCaseId",
151
+ ]);
152
+ /**
153
+ * An `ApprovedApplication` from a wire value, or a refusal.
154
+ *
155
+ * Every other lifecycle state is refused here, including the ones a reader might
156
+ * think are nearly approved: `manual_review` is a Reviewer still looking, and
157
+ * `under_appeal` is §8.6's route that has not concluded. Neither creates a Citizen.
158
+ */
159
+ export const parseApprovedApplication = (value, field = "approvedApplication") => {
160
+ const record = readClosedRecord(value, field, APPROVED_APPLICATION_FIELDS);
161
+ const state = readMember(record, field, "state", APPLICATION_STATES);
162
+ if (state !== "approved") {
163
+ refuseValue(`${field}.state`, "must be approved. Approval is the only transition that creates a Citizen (§5.2)");
164
+ }
165
+ return {
166
+ applicationId: readApplicationId(record, field, "applicationId"),
167
+ state: "approved",
168
+ verificationCaseId: readVerificationCaseId(record, field, "verificationCaseId"),
169
+ };
170
+ };