@meantjs/profile 0.0.0-stage → 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/CHANGELOG.md ADDED
@@ -0,0 +1,37 @@
1
+ # Changelog: @meantjs/profile
2
+
3
+ The five Candid Profile library packages (`@meantjs/profile`, `/format`, `/consent`, `/tools`, `/reconcile`) release together under one version and pin each other exactly; a version appears here even when this package did not change. Release steps: `docs/releasing.md` in the repository.
4
+
5
+ ## 0.1.0 — 2026-10-28
6
+
7
+ First published version.
8
+
9
+ Published under the `@meantjs` scope (D-051). Before any release, this package was `@candid-core/profile`.
10
+
11
+ - Validates Candid Profile v0 documents against the schema and the service's Candid interface, matches packs by Candid
12
+ subtyping (with the result-variant relaxation), merges layers by precedence and emits the resolved form
13
+ (`resolveService`, `validateProfile`, `matchPack`).
14
+ - Takes the service as `.did` source (compiled with `@candid-core/cli` 0.4.0) or as its candid-core `ContractEnvelope`.
15
+ - Ships the profile schema and the ICRC-1 and ICRC-2 packs as data (`./schema.json`, `./packs/*`); the Node entry's
16
+ defaults (`createSchemaValidator()`, `loadPacks()`, `candid-profile resolve --packs`) read these copies.
17
+ - Entries: `.` (Node), `./browser` (no Node built-in), `./address` (the address grammar, no dependency), and the
18
+ `candid-profile` CLI.
19
+ - TypeScript declarations for every entry.
20
+ - Names (spec §5.3, D-045): the experimental `names` and `named` tags and their checks (six errors and
21
+ `W_NAMED_UNPATTERNED`).
22
+ - Doc annotations (spec §9, proposal `docs/proposals/w1-doc-attributes.md`): `profileFromDocAttributes` turns the tags
23
+ an author writes as `.did` doc comments, as candid-core's `didToDocAttributes` reads them, into an `author` canister
24
+ profile. `DOC_ATTRIBUTES_VERSION` is the doc attributes version it reads (1). It needs a `@candid-core/cli` release
25
+ after 0.3.0 to be fed from `.did` text.
26
+ - The shipped schema is compiled ahead of time (`data/profile-v0.validate.mjs`, ajv's standalone code), so
27
+ `createSchemaValidator()` on it generates no code at run time: a page needs no CSP `'unsafe-eval'` (the cli's wasm
28
+ needs `'wasm-unsafe-eval'`). Its answers equal ajv's run-time compile on every profile in the repository and tens of
29
+ thousands of mutations of them. Another schema document is still compiled at run time, and ajv is loaded only then.
30
+ Each validator keeps its own `errors`. The browser bundle grows from 189.5 KB to 265.6 KB minified.
31
+ - Served profiles (spec §8.1, D-048): `readServedProfile(bytes, { canisterId })` checks the bytes a canister serves
32
+ as `icp:public candid:profile` (`E_SERVED` for anything but UTF-8 JSON of an `author` canister profile, at most
33
+ 1 MiB, bound to that canister or to none); `SERVED_SECTION`, `SERVED_METADATA` and `SERVED_MAX_BYTES` name the
34
+ section, its metadata path and its limit. In both entries.
35
+ - An `outcome` may give `default` alone (spec §5.3, D-049): the class of every reply of a method whose result has no
36
+ variant to select. The schema needs `classes` or `default`; on a result that reaches a variant, `default` alone
37
+ leaves every case to the default (`W_OUTCOME_UNCLASSIFIED`, info).
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,249 @@
1
- # Temporary Holding Version
1
+ # @meantjs/profile
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Validates Candid Profiles, matches packs to a service, merges layers and emits the resolved form that consumers read
4
+ (`docs/profile-v0.md` sections 7, 8 and 10). Dependencies, pinned exactly: `@candid-core/cli` 0.4.0 (wasm: `.did`
5
+ to Contract) and `ajv` 8.18.0.
6
+
7
+ ```sh
8
+ npm install @meantjs/profile
9
+ ```
10
+
11
+ - **Runs on:** Node 22 or later for the main entry and the `candid-profile` CLI. `@meantjs/profile/browser` is for
12
+ browser bundles (checked with esbuild, and in Chromium under a CSP without `'unsafe-eval'`; the cli's wasm needs
13
+ `'wasm-unsafe-eval'`, below). `@meantjs/profile/address` has no dependency and runs anywhere.
14
+ - **Module format:** ES modules only, with hand-written TypeScript declarations for every entry.
15
+ - **Spec:** [Candid Profile v0](https://github.com/B3Pay/Meant/blob/main/profile/docs/profile-v0.md). **Licence:** Apache-2.0.
16
+ - **Versions:** the five Candid Profile packages (`@meantjs/profile`, `/format`, `/consent`, `/tools`,
17
+ `/reconcile`) release together under one version and pin each other exactly; in 0.x a minor is breaking,
18
+ and so is any change to generated text ([releasing](https://github.com/B3Pay/Meant/blob/main/profile/docs/releasing.md)).
19
+
20
+ ```js
21
+ import { createSchemaValidator, resolveService, loadPacks, validateProfile } from "@meantjs/profile";
22
+
23
+ const validateSchema = await createSchemaValidator(); // the schema this package ships
24
+ const packs = await loadPacks(); // the standard packs it ships (ICRC-1, ICRC-2)
25
+ const r = await resolveService({
26
+ did: await readFile("ledger.did", "utf8"),
27
+ validateSchema,
28
+ profiles: [{ doc: authorProfile }], // applied as given (a pack here must match)
29
+ packs: packs.map(({ doc }) => ({ doc })), // tried; applied only if they match
30
+ });
31
+ r.ok; r.resolved; r.diagnostics; r.profiles; // r.resolved has the shape of fixtures/*.resolved.json
32
+ ```
33
+
34
+ Two inputs, exactly one per call: `did` (Candid source, compiled here with the pinned cli) or `envelope` (the
35
+ service's candid-core `ContractEnvelope`, as `candid-core-cli gen` writes it next to a generated module). With an
36
+ envelope the service is not compiled again, so the resolved form's `interface_id` is the one the app's generator
37
+ wrote (`test/envelope.test.mjs`: the same resolved form for the ledger `.did` and `examples/tokens.did` either way).
38
+ The envelope's identities are taken as written (nothing here can recompute them, so a hand-edited envelope keeps an
39
+ id that no longer describes it). Its graph is checked before anything walks it: every reference, the fields each
40
+ node kind needs, methods that name funcs, an actor, no opt that contains only itself, and the field-names table (it
41
+ must be there, and each name must hash to its field's id). One that fails is an `E_ENVELOPE` error with
42
+ `resolved: null`, and anything the checks still miss is reported the same way rather than thrown. Packs still compile their `binds.requires`, so the cli stays a
43
+ dependency. CLI: `candid-profile resolve --envelope app.envelope.json --packs`.
44
+
45
+ The defaults are the data the package ships (`data/`), so they work wherever it is installed. The same data is
46
+ exported for passing as documents:
47
+
48
+ ```js
49
+ import schema from "@meantjs/profile/schema.json" with { type: "json" }; // copy of spec/profile-v0.schema.json
50
+ import icrc1 from "@meantjs/profile/packs/icrc1.profile.json" with { type: "json" };
51
+ const validateSchema = await createSchemaValidator(schema); // a document, not a path
52
+ const r = await resolveService({ did, validateSchema, packs: [{ doc: icrc1 }] });
53
+ ```
54
+
55
+ `data/` is generated from the repository's `spec/` and `packs/` by `npm run data -w packages/resolver` (part of
56
+ `npm run fixtures`); `test/data.test.mjs` fails when it is stale. `@meantjs/profile/address` (`parseRelPath`, `parseAddress`, `idlHash`, `U32_MAX`) imports
57
+ nothing outside its own two modules, so a browser bundle may use it; the main entry loads Node built-ins, ajv and the
58
+ cli wasm.
59
+
60
+ `@meantjs/profile/browser` is the whole resolver for a browser bundle: the main entry's functions without the
61
+ ones that read files (`loadPacks`, the CLI, the default paths), plus the shipped data and the cli's wasm loader.
62
+
63
+ ```js
64
+ import { createSchemaValidator, resolveService, STANDARD_PACKS, initCompiler } from "@meantjs/profile/browser";
65
+
66
+ await initCompiler(wasmUrl); // optional: only when the bundler moves candid_core_wasm_bg.wasm
67
+ const validateSchema = await createSchemaValidator(); // the shipped schema; a document, never a path
68
+ const r = await resolveService({ did, validateSchema, profiles: [{ doc }], packs: STANDARD_PACKS.map(({ doc }) => ({ doc })) });
69
+ ```
70
+
71
+ Types: `src/index.d.mts`, `src/address.d.mts` and `src/browser.d.mts` (hand-written, each the `types` condition of
72
+ its entry; `scripts/types.test.mjs` keeps their names equal to the runtime exports, and `npm run types` compiles strict
73
+ consumers against them). `profileId` hashes with a plain-JavaScript SHA-256 (`src/sha256.mjs`, synchronous, compared with node:crypto in the
74
+ tests), so neither entry needs node:crypto.
75
+
76
+ **Content-Security-Policy.** The shipped schema is compiled ahead of time (`data/profile-v0.validate.mjs`, ajv's
77
+ standalone code, generated by `npm run data` and checked by `test/data.test.mjs`), so `createSchemaValidator()` on it,
78
+ or on any document equal to it, generates no code at run time: a page needs no `'unsafe-eval'`. The cli's wasm needs
79
+ `'wasm-unsafe-eval'` in `script-src`. Only another schema document is compiled by ajv at run time, with `new
80
+ Function`, and needs `'unsafe-eval'`. `test/csp.test.mjs` checks both: on Node with code generation from strings
81
+ disabled, and in Chromium under `script-src 'self' 'wasm-unsafe-eval'` (skipped without a Chrome or Chromium; set
82
+ `CHROME_PATH`).
83
+ `test/browser-entry.test.mjs` bundles the entry for the browser and fails on any `node:*` import or Node global
84
+ (the cli is left out of that bundle: it is its own published package, and it reads its wasm with a guarded
85
+ `import("node:fs/promises")` only on Node), checks the data against `data/`, and resolves `examples/` both ways.
86
+
87
+ `validateProfile(doc, { validateSchema, did, resolved })` is the single-profile validator (what `scripts/validate.mjs`
88
+ wraps). Source map: `iface.mjs` (Contract graph), `address.mjs`, `tags.mjs` (`TagIndex`, `LayeredTags`), `checks.mjs`,
89
+ `analyze.mjs` (index, merge, per-annotation checks), `doc-annotations.mjs`, `resolved.mjs`, `subtype.mjs`, `pack-match.mjs` (and `packs.mjs`,
90
+ which reads a directory), `schema-core.mjs` (and `schema.mjs`, which reads a path), `resolve.mjs`, `validate.mjs`,
91
+ `browser.mjs`.
92
+
93
+ ## Doc annotations (spec section 9)
94
+
95
+ An author can write the tags in the `.did` itself, as doc comments. candid-core reads them (doc attributes v1: one
96
+ `@name(key = value, ...)` syntax, malformed lines refused, each attribute handed out with the SourceInfo path of the
97
+ item it documents), and `profileFromDocAttributes` turns them into an `author` canister profile bound to the
98
+ interface's `interface_id`:
99
+
100
+ ```candid
101
+ type Tokens = record {
102
+ /// @amount(decimals = 8, symbol = "ICP")
103
+ e8s : nat64;
104
+ };
105
+ service : {
106
+ decimals : () -> (nat8) query;
107
+ /// Send tokens to another principal.
108
+ /// @intent(title = "Send", template = "Send {amount} to {to}")
109
+ /// @amount(at = "amount", decimals = query(decimals))
110
+ send : (record { to : principal; amount : nat }) -> (variant { Ok : nat; Err : text });
111
+ }
112
+ ```
113
+
114
+ ```js
115
+ import { didToDocAttributes } from "@candid-core/cli"; // a release after 0.3.0: 0.3.0 does not have it
116
+ import { profileFromDocAttributes, resolveService } from "@meantjs/profile";
117
+
118
+ const { ok, doc, diagnostics } = profileFromDocAttributes(await didToDocAttributes(did), { name: "my-ledger" });
119
+ const r = await resolveService({ did, validateSchema, profiles: doc ? [{ doc }] : [] });
120
+ ```
121
+
122
+ - Method docs: method tags (`intent`, `effect`, `idempotency`, `outcome`, `list`, `names`) apply to the method. Value
123
+ tags need `at`: `at = "amount"` for the arguments, `at = "->(0).Ok"` for the results, starting with `(i)` when the
124
+ tuple has more than one element. `@describe` without `at` describes the method.
125
+ - Declaration and field docs: `type:<Decl>` and `type:<Decl>.<field>`. A field of an inline actor type becomes a method
126
+ address (`inline(0).items[].price`): the method is found by its SourceInfo path, an `opt` adds nothing and a `vec`
127
+ adds `[]` (OQ-4). `at` reaches further inside (`@bytes(at = "subaccount", encoding = "hex")` on an account field).
128
+ - Values: text, numbers (whole only, kept exact; past 2^53 or for `range` bounds a decimal string), `true`/`false`,
129
+ identifiers as text (`unit = ns`), `query(m)`, `now()`, `caller()`, lists and records
130
+ (`classes = { Ok = success, "Err.TooOld" = fix_input }`).
131
+ - Prose becomes `describe.help` (lines joined, paragraphs kept), except on an integer the same doc gives no value tag:
132
+ a described integer is an agent input of plain digits (D-044), so that prose is reported (`I_DOC_PROSE`) instead.
133
+ - Only bare names that are profile tags are read. A dotted name (`@ui.hidden`) is another tool's; any other bare name
134
+ is left alone, with a warning when it is one or two letters from a tag (`@amout`).
135
+ - Errors (the profile is still returned with what could be placed): `E_DOC_TARGET` (a tag no v0 address reaches, such
136
+ as inside a func value or a callback service, or one in the wrong place), `E_DOC_VALUE` (a fraction, an unknown
137
+ call), `E_DOC_SYNTAX` (candid-core refused the comment), `E_DOC_INPUT` (not a doc attributes v1 response). Each
138
+ names the item's address, its SourceInfo `path` and `source`, and the doc line.
139
+
140
+ `didToDocAttributes` is new in the pinned `@candid-core/cli` 0.4.0; the tests read real responses it wrote
141
+ (`test/fixtures/doc-attributes/`, provenance in its `SOURCE.json`, regenerated with
142
+ `node scripts/doc-attributes-fixtures.mjs`, or with `--cli <path>` for a local build of candid-core's npm package). The proposal is `docs/proposals/w1-doc-attributes.md`.
143
+
144
+ ## Served profiles (spec section 8.1, D-048)
145
+
146
+ A canister serves its profile as the public custom section `icp:public candid:profile`. Reading the bytes is the
147
+ consumer's job (one certified `read_state` of `/canister/<id>/metadata/candid:service` and `.../candid:profile`;
148
+ `packages/kit` `fetch` does it with `@icp-sdk/core`); this package checks what came back:
149
+
150
+ ```js
151
+ import { readServedProfile, resolveService } from "@meantjs/profile";
152
+
153
+ const served = readServedProfile(profileBytes, { canisterId: "ryjl3-tyaaa-aaaaa-aaaba-cai" });
154
+ // served.ok: served.doc is the profile; otherwise served.diagnostics holds E_SERVED and nothing is applied
155
+ const r = await resolveService({ did: serviceText, profiles: served.ok ? [{ doc: served.doc }] : [] });
156
+ ```
157
+
158
+ - `E_SERVED` (`at`: `candid:profile`, or `label`): not a `Uint8Array`, over 1 MiB (`SERVED_MAX_BYTES`), not UTF-8, a
159
+ byte order mark, not JSON, not one object, a `kind` other than `canister`, an `origin` other than `author`, or a
160
+ `binds.canister_id` that is not `canisterId`. `canisterId: null` skips that last check, for a module that is not
161
+ installed yet (a module does not know the id it will run as); any other non-string throws.
162
+ - Binding is the resolver's usual rule (spec section 7): resolve against the `candid:service` the same canister
163
+ serves, so a profile for another interface is `rebound` or `stale` as any other.
164
+ - Tests: `test/served.test.mjs`; end to end on PocketIC in `packages/kit/pocketic/`.
165
+
166
+ ## CLI
167
+
168
+ ```sh
169
+ node packages/resolver/bin/candid-profile.mjs resolve <service.did> [--profile p.json ...] [--packs] [--packs-dir dir] [--verbose] [--quiet] > resolved.json
170
+ # after `npm ci` the bin is also linked: npx candid-profile resolve ...
171
+ ```
172
+
173
+ - `--profile` may repeat; a pack given this way must match (`E_PACK_NOT_MATCHED` otherwise).
174
+ - `--packs` tries every standard pack this package ships (or every pack in `--packs-dir`) and applies those that match; the others get `I_PACK_NOT_MATCHED` (info).
175
+ - stdout: the resolved form (also when diagnostics contain errors, as long as the `.did` compiles). stderr: applied profiles, counts, warnings and errors (`--verbose`: infos too).
176
+ - Exit code 0: no error diagnostic. 1: at least one. 2: usage or I/O.
177
+ - A `.did` with `import` is not followed yet; give the CLI a single file.
178
+
179
+ Real input: `test/fixtures/ledger.did`, the ICRC ledger `.did` of release `ledger-suite-icrc-2026-03-09`, the file the eval harness pins
180
+ (sha256 and URL in `test/fixtures/SOURCES.json`). `candid-profile resolve test/fixtures/ledger.did --packs` applies `icrc1` and `icrc2`,
181
+ with 0 errors, 0 warnings and 3 infos (two matches, and the `int16` `utc_offset_minutes` of ICRC-21 that no profile tags).
182
+
183
+ ## Merge (spec section 8)
184
+
185
+ Layers, highest first: `author`, `third_party`, `pack`, `inferred`. One `TagIndex` per layer.
186
+
187
+ - The first layer that has a tag at a position supplies it; the same tag lower down is dropped with `W_OVERRIDDEN`.
188
+ - Within a layer (also across several profiles of that layer): method position beats a `type:` edge beats a whole-declaration
189
+ tag. Two different values at one specificity: `E_CONFLICT`, the first one given stays. Equal values: `W_DUPLICATE`.
190
+ - Layer decides before specificity.
191
+ - `profiles` in the resolved form lists every applied profile, highest layer first. Each tag carries `origin` and `profile`.
192
+ - A stale canister profile (spec section 7) keeps its non-conversion tags but loses `amount`, `timestamp`, `duration`,
193
+ `account`, `subaccount`, `bytes` in the output.
194
+
195
+ ## Pack matching and Candid subtyping (spec section 7, D-005, D-019)
196
+
197
+ A pack applies when the service is a **subtype** of the Candid fragment in `binds.requires`, with result variants allowed to be wider.
198
+
199
+ ### Was an existing checker usable? No.
200
+
201
+ | Candidate | Finding (2026-10-09) |
202
+ |---|---|
203
+ | `@dfinity/didc` 0.0.4 (wasm of the Rust candid crates) | Exports `start`, `getServiceMethods`, `encode`, `decode` only. The subtype code is linked in (it backs `decode`) but there is no entry point that compares two services. |
204
+ | `@candid-core/cli` 0.2.0 (surveyed 2026-10-09; 0.3.0 since D-037 adds `projectDid` and `checkCompatible`, not surveyed) | Exports `init`, `didToContract`, `didToModule`. No compatibility check. |
205
+ | candid-core compatibility (b3hr4d/candid-core#247) | An open issue ("Interface projection and a live-compatibility check over written .did files"), not code. Its acceptance criteria ask for the same relation as here plus differential tests against upstream `candid`. |
206
+ | `@candid-core/schema` 0.3.0 (surveyed 2026-10-09) `wireSubtypeOfSchema` | An internal method of the binary decoder (not an export): it relates a wire type table to a runtime schema, not two Contracts. Read as a second opinion on the rules. |
207
+ | Rust `didc` 0.5.4 (binary from the local cargo bin; its linked candid revision was not determined) and the source of candid 0.10.37 (newest in the local cargo registry) | `didc check` is the oracle for the differential tests (below); the 0.10.37 `src/types/subtype.rs` was read for the rules. Neither is a runtime dependency. |
208
+
209
+ So `src/subtype.mjs` implements the relation over two candid-core Contract graphs (`Iface`), one per side, since a canister and a pack fragment are compiled separately.
210
+
211
+ ### Rules implemented
212
+
213
+ Source: Candid specification, "Upgrading and Subtyping > Rules" (https://github.com/dfinity/candid/blob/c7659ca/spec/Candid.md, the revision the Rust crate links to). `S <: T` means S can be used where T is expected.
214
+
215
+ | Spec subsection | Rule as implemented |
216
+ |---|---|
217
+ | Primitive Types | `t <: t`; `nat <: int`; `any <: reserved`; `empty <: any` |
218
+ | Vectors | `vec S <: vec T` if `S <: T` (`blob` is `vec nat8`) |
219
+ | Options | `opt S <: opt T` if `S <: T`; `null <: opt T`; `S <: opt T` if `S <: T` and T is not null, reserved or opt |
220
+ | Options, "unusual rules" | **Off by default** (`lossyOpt`). They make `opt S <: opt T` hold for unrelated S and T (the value decodes as null). The spec says they exist for transitivity and that tools should warn when used; for pack matching they would accept `fee : opt text` against a pack that says `opt nat`. With `lossyOpt: true` they are implemented as "always true" |
221
+ | Records | `record S <: record T` if every field of T is in S with a subtype, or is absent from S and its type is opt, null or reserved. Extra fields in S are ignored. Fields compare by id |
222
+ | Variants | `variant S <: variant T` if every case of S is in T with a subtype (S may have fewer cases) |
223
+ | Functions | `func S <: func T` if the annotations are equal, `tuple(T.args) <: tuple(S.args)` (contravariant) and `tuple(S.results) <: tuple(T.results)` (covariant); tuples follow the record rule over positions 0, 1, ... |
224
+ | Services | `service S <: service T` if every method of T is in S with a function subtype. Extra methods ignored; init args of a class ignored |
225
+ | (coinduction) | A pair met again while it is being decided is assumed true, so recursive types terminate |
226
+ | (bounds, profile spec section 11.6) | Depth 256 and 2,000,000 pair evaluations; beyond that the answer is "not a subtype" |
227
+
228
+ **D-019 relaxation.** For a variant reached through a method *result*, extra cases in the canister are allowed. "Reached through" is
229
+ a descent from the result by record fields, `opt`, `vec` and variant payloads, with covariant polarity. Entering a `func` or `service`
230
+ type resets to strict. Argument positions are always strict. The matcher reports every relaxed position
231
+ (`I_PACK_MATCHED` message and `matchPack(...).relaxed`).
232
+
233
+ **Not implemented, on purpose:** the Rust crate's catch-all that accepts `S <: opt T` for any S with only a warning (it is not a rule of the spec);
234
+ `service <: principal` (not in this revision of the spec; the Rust crate has it).
235
+
236
+ ### Verification
237
+
238
+ - **Facts (run 2026-10-09):** `test/subtype.test.mjs` holds 41 service pairs, each with the answer of the Rust `didc check` 0.5.4 and of the spec rules. With `lossyOpt: true` the checker answers like Rust on all 41; with it off it differs on exactly the 3 rows that need the unusual opt rules. A seeded differential test (250 random pairs, in the repository) runs when `didc` is installed and checks: never more permissive than `didc`, and identical to `didc` whenever `didc` does not report its special opt rule. Scratch runs during development (about 7,400 further random pairs; the "never more permissive" check on 2,800 of them) found no violation. In those runs `didc` used its special opt rule on about 13% of the pairs; where it accepted through that rule, this checker with `lossyOpt: true` also accepted in about 87% of the cases (the rest need the Rust catch-all, which is not a spec rule).
239
+ - **Label: assumption.** Rust `didc` and the spec could both be wrong in a way that this checker repeats. The candid-core decoder (`wireSubtypeOfSchema`) was read for the same rules but not run against this checker.
240
+ - **Open:** a Candid corner we did not exercise is `service <: principal` and quoted method names (OQ-3).
241
+
242
+ ### What happens after a match
243
+
244
+ A matched pack is applied to the **service's** types (addresses resolve against the service). Subtyping lets the service differ from the
245
+ fragment, so some annotations may name a position the service does not have, or have a shape a tag no longer fits. These are dropped with
246
+ `I_PACK_ANNOTATION_SKIPPED` instead of being reported as errors in the pack: an address that is gone (a result case the service removed,
247
+ an optional field it lacks), an `outcome` key that is not a case, a template placeholder inside an optional segment that is absent (the
248
+ segment renders empty), a tag that does not apply to the service's type (for example `account` on a record with an extra optional field),
249
+ and an `idempotency` whose stamp lost its `timestamp` tag. A placeholder outside an optional segment that cannot be resolved is dropped with its `intent`.
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/cli.mjs";
3
+
4
+ main(process.argv.slice(2), { stdout: process.stdout, stderr: process.stderr })
5
+ .then((code) => { process.exitCode = code; })
6
+ .catch((e) => { console.error(e); process.exitCode = 2; });