contractdiff 0.0.0-stage → 0.4.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -2
  3. package/dist/bin.js +4 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.js +24 -0
  6. package/dist/command-diff.js +310 -0
  7. package/dist/command-explain-cap.js +36 -0
  8. package/dist/command-explain-inline.js +17 -0
  9. package/dist/command-explain-name.js +31 -0
  10. package/dist/command-explain-operation.js +85 -0
  11. package/dist/command-explain-text.js +21 -0
  12. package/dist/command-explain.js +54 -0
  13. package/dist/command-lint.js +280 -0
  14. package/dist/command-migrate.js +70 -0
  15. package/dist/command-plugin.js +32 -0
  16. package/dist/command-props.js +116 -0
  17. package/dist/commands.js +7 -0
  18. package/dist/core/index.d.ts +2 -0
  19. package/dist/core/index.js +2 -0
  20. package/dist/core/model.d.ts +46 -0
  21. package/dist/core/model.js +1 -0
  22. package/dist/core/resolve.d.ts +22 -0
  23. package/dist/core/resolve.js +71 -0
  24. package/dist/diff-classify.js +30 -0
  25. package/dist/diff-contract.js +176 -0
  26. package/dist/diff-decisions.js +446 -0
  27. package/dist/diff-normalise.js +143 -0
  28. package/dist/diff-rules.js +109 -0
  29. package/dist/diff-schema.js +335 -0
  30. package/dist/diff-security.js +33 -0
  31. package/dist/diff-transitive.js +26 -0
  32. package/dist/diff-usage.js +59 -0
  33. package/dist/extract-normalise.js +85 -0
  34. package/dist/extract-roundtrip.js +28 -0
  35. package/dist/extract-standard.js +79 -0
  36. package/dist/gen-ts-ast.d.ts +135 -0
  37. package/dist/gen-ts-ast.js +52 -0
  38. package/dist/gen-ts-bundle.js +233 -0
  39. package/dist/gen-ts-comment.js +48 -0
  40. package/dist/gen-ts-context.d.ts +83 -0
  41. package/dist/gen-ts-context.js +45 -0
  42. package/dist/gen-ts-dict.d.ts +14 -0
  43. package/dist/gen-ts-dict.js +14 -0
  44. package/dist/gen-ts-discriminators.d.ts +7 -0
  45. package/dist/gen-ts-discriminators.js +117 -0
  46. package/dist/gen-ts-document.d.ts +12 -0
  47. package/dist/gen-ts-document.js +82 -0
  48. package/dist/gen-ts-enums.js +139 -0
  49. package/dist/gen-ts-helpers.js +30 -0
  50. package/dist/gen-ts-index.d.ts +49 -0
  51. package/dist/gen-ts-index.js +110 -0
  52. package/dist/gen-ts-operations.js +277 -0
  53. package/dist/gen-ts-print.js +113 -0
  54. package/dist/gen-ts-ref.d.ts +30 -0
  55. package/dist/gen-ts-ref.js +75 -0
  56. package/dist/gen-ts-schema.js +283 -0
  57. package/dist/gen-ts-text.d.ts +24 -0
  58. package/dist/gen-ts-text.js +98 -0
  59. package/dist/host.d.ts +145 -0
  60. package/dist/host.js +273 -0
  61. package/dist/index.d.ts +6 -0
  62. package/dist/index.js +5 -0
  63. package/dist/input-asyncapi.js +167 -0
  64. package/dist/input-buf.js +58 -0
  65. package/dist/input-jsonschema.js +165 -0
  66. package/dist/input-mcp.js +111 -0
  67. package/dist/input-overlay-jsonpath.js +265 -0
  68. package/dist/input-overlay.js +138 -0
  69. package/dist/input-protobuf.js +212 -0
  70. package/dist/input-swagger2.js +331 -0
  71. package/dist/inputs.js +8 -0
  72. package/dist/lint-code-read.js +129 -0
  73. package/dist/lint-code.d.ts +56 -0
  74. package/dist/lint-code.js +64 -0
  75. package/dist/lint-engine.d.ts +93 -0
  76. package/dist/lint-engine.js +87 -0
  77. package/dist/lint-functions.js +95 -0
  78. package/dist/lint-history.js +133 -0
  79. package/dist/lint-jsonpath.js +92 -0
  80. package/dist/lint-names.d.ts +11 -0
  81. package/dist/lint-names.js +2 -0
  82. package/dist/lint-redocly.js +141 -0
  83. package/dist/lint-rules.js +189 -0
  84. package/dist/lint-select.d.ts +33 -0
  85. package/dist/lint-select.js +129 -0
  86. package/dist/lint-since.js +20 -0
  87. package/dist/lint-spectral.js +167 -0
  88. package/dist/lint-stats.js +58 -0
  89. package/dist/migrate-hey-api.js +144 -0
  90. package/dist/migrate-literal.js +139 -0
  91. package/dist/migrate-openapi-fetch.js +62 -0
  92. package/dist/migrate-openapi-typescript.js +159 -0
  93. package/dist/migrate-orval.js +119 -0
  94. package/dist/migrate-shared.js +31 -0
  95. package/dist/openapi-typescript.d.ts +9 -0
  96. package/dist/openapi-typescript.js +36 -0
  97. package/dist/openapi.d.ts +20 -0
  98. package/dist/openapi.js +94 -0
  99. package/dist/plugin-express.js +66 -0
  100. package/dist/plugin-extract-hono.js +1 -0
  101. package/dist/plugin-extract-nest.js +1 -0
  102. package/dist/plugin-extract-openapi.js +246 -0
  103. package/dist/plugin-extract-standard-schema.js +42 -0
  104. package/dist/plugin-extract-trpc.js +1 -0
  105. package/dist/plugin-extract-ts-rest.js +77 -0
  106. package/dist/plugin-fastify.js +68 -0
  107. package/dist/plugin-fetch-client.js +172 -0
  108. package/dist/plugin-fetch-routes.js +110 -0
  109. package/dist/plugin-fetch-sample.js +155 -0
  110. package/dist/plugin-fetch-text.js +5 -0
  111. package/dist/plugin-fetch.js +19 -0
  112. package/dist/plugin-hono.js +42 -0
  113. package/dist/plugin-json-schema-build.js +289 -0
  114. package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
  115. package/dist/plugin-json-schema-dialect-gemini.js +29 -0
  116. package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
  117. package/dist/plugin-json-schema-dialect-mcp.js +13 -0
  118. package/dist/plugin-json-schema-dialect-openai.js +37 -0
  119. package/dist/plugin-json-schema-dialect.js +180 -0
  120. package/dist/plugin-json-schema.js +125 -0
  121. package/dist/plugin-markdown.js +114 -0
  122. package/dist/plugin-mcp-code.js +28 -0
  123. package/dist/plugin-mcp-tools.js +152 -0
  124. package/dist/plugin-mcp.js +107 -0
  125. package/dist/plugin-msw-files.js +50 -0
  126. package/dist/plugin-msw-sample.js +45 -0
  127. package/dist/plugin-msw-synth.js +116 -0
  128. package/dist/plugin-msw.js +30 -0
  129. package/dist/plugin-nest-code.js +68 -0
  130. package/dist/plugin-nest-contract.js +23 -0
  131. package/dist/plugin-nest.js +44 -0
  132. package/dist/plugin-server-code.js +61 -0
  133. package/dist/plugin-server-contract.js +48 -0
  134. package/dist/plugin-server-example.js +62 -0
  135. package/dist/plugin-server-router.js +77 -0
  136. package/dist/plugin-server-routes.js +155 -0
  137. package/dist/plugin-server-runtime.js +3 -0
  138. package/dist/plugin-server-sample.js +40 -0
  139. package/dist/plugin-swr-sample.js +21 -0
  140. package/dist/plugin-swr.js +40 -0
  141. package/dist/plugin-tanstack-query-sample.js +21 -0
  142. package/dist/plugin-tanstack-query.js +59 -0
  143. package/dist/plugin-types.js +80 -0
  144. package/dist/plugin-validator-code.js +41 -0
  145. package/dist/plugin-validator-names.js +27 -0
  146. package/dist/plugin-validator.js +103 -0
  147. package/dist/plugins.js +21 -0
  148. package/dist/props-emit.js +194 -0
  149. package/dist/props-generate.js +409 -0
  150. package/dist/props-judge.js +61 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +176 -0
  154. package/dist/props-shrink.js +75 -0
  155. package/dist/run-apply.js +25 -0
  156. package/dist/run-command.js +31 -0
  157. package/dist/run-commit.d.ts +51 -0
  158. package/dist/run-commit.js +48 -0
  159. package/dist/run-config.d.ts +193 -0
  160. package/dist/run-config.js +256 -0
  161. package/dist/run-diff.js +24 -0
  162. package/dist/run-extract.d.ts +13 -0
  163. package/dist/run-extract.js +21 -0
  164. package/dist/run-gen.d.ts +15 -0
  165. package/dist/run-gen.js +43 -0
  166. package/dist/run-header.js +37 -0
  167. package/dist/run-input.js +31 -0
  168. package/dist/run-load.js +32 -0
  169. package/dist/run-map.d.ts +41 -0
  170. package/dist/run-map.js +52 -0
  171. package/dist/run-plan.d.ts +31 -0
  172. package/dist/run-plan.js +35 -0
  173. package/dist/scaffold-seed.js +43 -0
  174. package/dist/scaffold-write.js +17 -0
  175. package/dist/scaffold.js +196 -0
  176. package/dist/testing-lint.js +43 -0
  177. package/dist/testing-owner.js +17 -0
  178. package/dist/testing-probe.js +25 -0
  179. package/dist/testing-rules.d.ts +65 -0
  180. package/dist/testing-rules.js +115 -0
  181. package/dist/testing.d.ts +32 -0
  182. package/dist/testing.js +79 -0
  183. package/package.json +108 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ofri Peretz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,229 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/ofri-peretz/burgee/tree/main/packages/contractdiff" target="blank">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ofri-peretz/burgee/main/brand-assets/contractdiff-lockup.svg" />
5
+ <img src="https://raw.githubusercontent.com/ofri-peretz/burgee/main/brand-assets/contractdiff-lockup-light.svg" alt="contractdiff" width="360" />
6
+ </picture>
7
+ </a>
8
+ </p>
2
9
 
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.
10
+ <p align="center">
11
+ What changed in an API contract, who it breaks, and the code on both sides of it.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/contractdiff"><img src="https://img.shields.io/npm/v/contractdiff?style=flat-square&color=0a6b47" alt="contractdiff on npm: the latest version" /></a>
16
+ <a href="https://www.npmjs.com/package/contractdiff"><img src="https://img.shields.io/npm/dm/contractdiff?style=flat-square" alt="contractdiff downloads per month on npm" /></a>
17
+ <a href="https://github.com/ofri-peretz/burgee/actions/workflows/quality.yml?query=branch%3Amain"><img src="https://img.shields.io/github/actions/workflow/status/ofri-peretz/burgee/quality.yml?branch=main&style=flat-square&label=Quality%20Gate" alt="Quality Gate: the CI status of main" /></a>
18
+ <a href="https://app.codecov.io/gh/ofri-peretz/burgee/components"><img src="https://img.shields.io/codecov/c/github/ofri-peretz/burgee/main?component=contractdiff&style=flat-square" alt="contractdiff line coverage: its Codecov component" /></a>
19
+ <a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/burgee"><img src="https://img.shields.io/ossf-scorecard/github.com/ofri-peretz/burgee?style=flat-square&label=OpenSSF%20Scorecard" alt="OpenSSF Scorecard for the repository" /></a>
20
+ <a href="https://www.npmjs.com/package/contractdiff?activeTab=code"><img src="https://img.shields.io/npm/unpacked-size/contractdiff?style=flat-square" alt="Unpacked size of the latest contractdiff release on npm" /></a>
21
+ <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/contractdiff/package.json"><img src="https://img.shields.io/badge/dependencies-4%20in%20family%2C%200%20outside-0a6b47?style=flat-square" alt="Four dependencies, all in the burgee family (bellpull, burgee, seniority, truefit), none outside it" /></a>
22
+ <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/contractdiff/package.json"><img src="https://img.shields.io/badge/types-included-blue?style=flat-square" alt="TypeScript types included for every entry point" /></a>
23
+ <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/contractdiff/package.json"><img src="https://img.shields.io/badge/Node.js-22.13%2B-green?style=flat-square" alt="Node.js 22.13+" /></a>
24
+ <a href="https://github.com/ofri-peretz/burgee/blob/main/packages/contractdiff/LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue?style=flat-square" alt="License: MIT" /></a>
25
+ <a href="https://www.npmjs.com/package/contractdiff#provenance"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fregistry.npmjs.org%2Fcontractdiff%2Flatest&query=%24.dist.attestations.provenance~&label=npm&style=flat-square&color=0a6b47" alt="npm provenance of the latest release, read live from its registry attestation" /></a>
26
+ </p>
27
+
28
+ <p align="center">
29
+ Docs: <a href="https://burgee.interlace.tools/docs/packages/contractdiff">https://burgee.interlace.tools/docs/packages/contractdiff</a><br />
30
+ Migrating from: <a href="https://github.com/ofri-peretz/burgee/tree/main/packages/contractdiff#migrating">openapi-typescript</a>
31
+ </p>
32
+
33
+ **contractdiff** reads an API contract (OpenAPI, Swagger 2.0, JSON Schema, AsyncAPI or an MCP tool
34
+ list) and does four things with it. `diff` says what a change breaks and for whom, under the
35
+ compatibility mode you pick. `lint` checks the contract's form with rules, Spectral and Redocly
36
+ rulesets included. `gen` writes code from it, one plugin per target: TypeScript types, truefit
37
+ validators, fetch and TanStack Query clients, MSW handlers and NestJS, Express, Fastify and Hono
38
+ servers. `extract` writes the contract back from the code. Every finding names its fix, as the same
39
+ record for a person, for `--json` and for a coding agent.
40
+
41
+ The `types` target writes what **openapi-typescript** writes, and `contractdiff migrate
42
+ openapi-typescript` turns its flags and `redocly.yaml` into a `contractdiff.config.json`, as
43
+ [Migrating](https://github.com/ofri-peretz/burgee/tree/main/packages/contractdiff#migrating) shows.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ npm install contractdiff
49
+ pnpm add contractdiff
50
+ yarn add contractdiff
51
+ bun add contractdiff
52
+ ```
53
+
54
+ Install it as a dev dependency (`-D`) of the project that owns the contract. The generated
55
+ validators import `truefit`, which comes with it.
56
+
57
+ ## Quick start
58
+
59
+ ```bash
60
+ npm install contractdiff
61
+ ```
62
+
63
+ ```js
64
+ import { mkdtempSync, writeFileSync } from "node:fs";
65
+ import { tmpdir } from "node:os";
66
+ import { join } from "node:path";
67
+ import { gen } from "contractdiff";
68
+
69
+ const dir = mkdtempSync(join(tmpdir(), "contractdiff-"));
70
+ const pet = { type: "object", required: ["name"], properties: { name: { type: "string" } } };
71
+ writeFileSync(
72
+ join(dir, "openapi.json"),
73
+ JSON.stringify({
74
+ openapi: "3.1.0",
75
+ info: { title: "Pets", version: "1.0.0" },
76
+ paths: {
77
+ "/pets/{id}": {
78
+ get: {
79
+ operationId: "getPet",
80
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
81
+ responses: { 200: { description: "A pet", content: { "application/json": { schema: pet } } } },
82
+ },
83
+ },
84
+ },
85
+ }),
86
+ );
87
+ writeFileSync(
88
+ join(dir, "contractdiff.config.json"),
89
+ JSON.stringify({ input: "openapi.json", targets: { types: { generator: "types", out: "src/api" } } }),
90
+ );
91
+
92
+ const report = await gen({ cwd: dir });
93
+ for (const file of report.files) console.log(`${file.action} ${file.path}`);
94
+ ```
95
+
96
+ ```text
97
+ write src/api/types.ts
98
+ write contractdiff.map.json
99
+ ```
100
+
101
+ That is `npx contractdiff gen` in a project with that config. `npx contractdiff diff
102
+ git:main:openapi.json openapi.json` compares the contract on `main` with the one in the working tree,
103
+ and exits 1 when the change breaks a caller.
104
+
105
+ ## What it does
106
+
107
+ - **`diff`** compares two versions of a contract, from files or `git:<ref>:<path>`, and classifies
108
+ each change as breaking, dangerous or safe for the side you name, under `backward`, `forward` or
109
+ `full` compatibility. `--transitive` checks a chain of releases.
110
+ - **`lint`** runs rules on a contract: its own `recommended` and `agent-ready` sets, and Spectral
111
+ and Redocly rulesets read as they are.
112
+ - **`gen`** writes code from the contract, one plugin per target, and records every file and symbol
113
+ it wrote in `contractdiff.map.json`, so the next run can tell its own files from yours.
114
+ - **`extract`** writes the contract back from your code, and `props` draws property tests from it.
115
+
116
+ ## Migrating
117
+
118
+ `npx contractdiff migrate openapi-typescript` reads the scripts that run openapi-typescript and its
119
+ `redocly.yaml`, writes `contractdiff.config.json` with a `types` target in openapi-typescript's
120
+ compatibility mode, and rewrites the script:
121
+
122
+ ```diff
123
+ "scripts": {
124
+ - "gen": "openapi-typescript openapi.yaml -o src/api/types.ts"
125
+ + "gen": "contractdiff gen"
126
+ }
127
+ ```
128
+
129
+ It prints what it changed and what it could not carry, then `npm uninstall openapi-typescript`.
130
+ The same command reads openapi-fetch, Hey API and orval configs.
131
+
132
+ ## Compatibility
133
+
134
+ Not graded: no incumbent's own suite runs against contractdiff through compat-oracle. The `types`
135
+ target is measured against openapi-typescript's output on the corpus in `benchmarks/apicontract`.
136
+
137
+ ## Benchmarks
138
+
139
+ Every number here is produced by `npm run bench` and published at [burgee.interlace.tools/docs/benchmarks](https://burgee.interlace.tools/docs/benchmarks).
140
+
141
+ No suite is graded against this package yet, so there is no compatibility number to quote.
142
+
143
+ ## For agents
144
+
145
+ - **`contractdiff explain <operation> --json`** prints one operation, message or tool with every
146
+ `$ref` resolved and its size capped, so an agent calls it from the contract and not from memory.
147
+ - **`contractdiff lint --ruleset agent-ready`** checks whether a contract can be used as tools.
148
+ - **`--json`, `--schema` and an MCP server** come from one declaration on burgee:
149
+ `contractdiff --mcp` serves the read-only commands as tools.
150
+ - **Exit codes are the contract.** `0` ok; `1` a finding, such as a breaking change; `2` a usage
151
+ error; `3` a config that did not load, with the field to fix.
152
+ - **The docs are machine-readable** at
153
+ [burgee.interlace.tools/llms.txt](https://burgee.interlace.tools/llms.txt).
154
+
155
+ ## API
156
+
157
+ | Import | What it gives you |
158
+ | :--------------------------------- | :--------------------------------------------------------------------------------- |
159
+ | `contractdiff` | `gen()`, `extract()`, `configSchema`, `MAP_FILE` and `program` |
160
+ | `contractdiff/core` | the contract model every adapter reads into, and the `$ref` resolver |
161
+ | `contractdiff/openapi` | the OpenAPI adapter |
162
+ | `contractdiff/openapi-typescript` | openapi-typescript's API over the `types` target |
163
+ | `contractdiff/testing` | `Plugin` and the conformance suite a plugin of your own runs |
164
+
165
+ The `contractdiff` bin is that API, declared once on burgee. `contractdiff plugin new <name>`
166
+ scaffolds a plugin that passes the conformance suite as written.
167
+
168
+ ## Requirements
169
+
170
+ Node 22.13 or later. git, for `diff` against a ref. TypeScript in the project, for `lint` rules on
171
+ code and for `extract` from TypeScript sources.
172
+
173
+ ## Where it sits
174
+
175
+ It hosts no plugin key of its own.
176
+
177
+ Nothing in this family builds on it yet, and it builds on `bellpull`, `burgee`, `seniority`, `truefit`.
178
+
179
+ ## The family
180
+
181
+ 14 packages, one repository, one release pipeline. Each installs and works on its own, and each owns
182
+ one job. Seven of them — `bellpull`, `closeout`, `linegauge`, `paratext`, `roundel`, `seniority`,
183
+ `truefit` — depend on nothing; the others depend only on packages in this table, and every
184
+ dependency points one way, down the [layers](https://burgee.interlace.tools/docs/concepts/family).
185
+
186
+ No package declares a dependency from outside the family; `react` and `react-reconciler` are
187
+ optional peers of `controlroom`, which npm does not install; `vitest` is an optional peer of
188
+ `oxmutate`, which npm does not install; `eslint` is an optional peer of `truepass`, which npm does
189
+ not install.
190
+ [`package-shape-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/package-shape-lock.test.ts)
191
+ holds that for every manifest, and
192
+ [`independence-install-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/independence-install-lock.test.ts)
193
+ installs each package alone and finds nothing but the family packages it declares.
194
+
195
+ Releases are published by one workflow through npm trusted publishing: no npm token is used, and
196
+ each release carries SLSA provenance, which `npm view <package> dist.attestations` shows.
197
+ [`trusted-publishing-lock`](https://github.com/ofri-peretz/burgee/blob/main/scripts/trusted-publishing-lock.test.ts)
198
+ keeps both true.
199
+
200
+ | Package | What it is | Migrates from |
201
+ | :-- | :-- | :-- |
202
+ | [burgee](https://burgee.interlace.tools/docs/packages/burgee) | The CLI framework: one declaration, every surface | commander, yargs and meow |
203
+ | [roundel](https://roundel.interlace.tools/docs) | Colour: one output policy, semantic tokens, a theme | chalk, colorette, kleur, picocolors, supports-color and yoctocolors |
204
+ | [flagstaff](https://flagstaff.interlace.tools/docs) | The frame loop: spinners, progress, boxes and tables | ora, log-update, boxen and cli-table3 |
205
+ | [caique](https://caique.interlace.tools/docs) | Prompts that are flags first, and never hang | @inquirer/core |
206
+ | [linegauge](https://linegauge.interlace.tools/docs) | Measuring, wrapping, truncating and slicing styled text | string-width, wrap-ansi, strip-ansi, slice-ansi, cli-truncate and widest-line |
207
+ | [paratext](https://paratext.interlace.tools/docs) | Hyperlinks, images, title, clipboard and notifications | ansi-escapes, terminal-link and term-img |
208
+ | [seniority](https://seniority.interlace.tools/docs) | Configuration precedence and discovery, with provenance | cosmiconfig, lilconfig, dotenv and rc |
209
+ | [closeout](https://closeout.interlace.tools/docs) | Exit handlers, terminal restore and a bounded shutdown | signal-exit, exit-hook, restore-cursor, cli-cursor and onetime |
210
+ | [bellpull](https://bellpull.interlace.tools/docs) | Subprocesses, and which executable actually ran | cross-spawn and which |
211
+ | [controlroom](https://controlroom.interlace.tools/docs) | Keyboard-driven terminal screens, inline or full-screen | ink |
212
+ | [oxmutate](https://oxmutate.interlace.tools/docs) | Mutation testing on the oxc engine, inside your own Vitest | Stryker |
213
+ | [truepass](https://burgee.interlace.tools/docs/packages/truepass) | Lint rules and a pre-push check that keep a test suite honest | @vitest/eslint-plugin |
214
+ | **contractdiff** (this package) | API contracts: breaking-change diff, lint, and code from the spec | openapi-typescript |
215
+ | [truefit](https://burgee.interlace.tools/docs/packages/truefit) | Validation whose schemas are data, with no eval | zod |
216
+
217
+ Every migration guide, and the family-wide [compatibility](https://burgee.interlace.tools/docs/compatibility)
218
+ and [benchmarks](https://burgee.interlace.tools/docs/benchmarks) pages, are on
219
+ [burgee.interlace.tools](https://burgee.interlace.tools/docs/packages).
220
+
221
+ ## Contributing
222
+
223
+ Issues and pull requests are welcome at [ofri-peretz/burgee](https://github.com/ofri-peretz/burgee/issues); read
224
+ [CONTRIBUTING.md](https://github.com/ofri-peretz/burgee/blob/main/CONTRIBUTING.md) first. Report a vulnerability privately, as
225
+ [SECURITY.md](https://github.com/ofri-peretz/burgee/blob/main/SECURITY.md) describes — never in a public issue.
226
+
227
+ ## Licence
228
+
229
+ MIT © Ofri Peretz — see [LICENSE](https://github.com/ofri-peretz/burgee/blob/main/packages/contractdiff/LICENSE).
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { run } from 'burgee';
3
+ import { program } from './cli.js';
4
+ await run(program);
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The published version, read from the manifest beside dist/ so `--version` cannot drift from npm. */
2
+ export declare const VERSION: string;
3
+ export declare const program: import("burgee").Manifest;
package/dist/cli.js ADDED
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { defineCommand, defineProgram } from 'burgee';
3
+ import { commands } from './commands.js';
4
+ import { extractCommand, genCommand } from './run-command.js';
5
+ export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
6
+ const planned = (name, description, phase, effects = 'read_only') => defineCommand({
7
+ name,
8
+ description,
9
+ effects,
10
+ run: () => {
11
+ throw new Error(`\`contractdiff ${name}\` is not implemented yet. fix: it lands in ${phase} (.sdlc/intents/contractdiff/roadmap.md)`);
12
+ },
13
+ });
14
+ export const program = defineProgram({
15
+ name: 'contractdiff',
16
+ version: VERSION,
17
+ description: 'Turn your specs into code and your code into specs, through plugins',
18
+ commands: [
19
+ genCommand,
20
+ extractCommand,
21
+ ...commands,
22
+ planned('check', 'Call sites in the code that disagree with the contract, found statically', 'Phase 7'),
23
+ ],
24
+ });
@@ -0,0 +1,310 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { defineCommand, ExitCode } from 'burgee';
6
+ import { parse as parseYaml } from 'seniority/yaml';
7
+ import { MODES, SIDES } from './diff-classify.js';
8
+ import { compareContracts, overall, sortFindings, summaryOf } from './diff-contract.js';
9
+ import { checkDecisions, isDate, withDecisions } from './diff-decisions.js';
10
+ import { compareTransitive } from './diff-transitive.js';
11
+ import { applyUsage, parseUsage } from './diff-usage.js';
12
+ import { breakingIn, bufIn, builtImages, LEVELS, refFix } from './input-buf.js';
13
+ import { builtinAdapters } from './inputs.js';
14
+ import { DECISION_SETTINGS, decisionSettingOf, UsageError } from './run-config.js';
15
+ const TEXT = Symbol.for('burgee.text');
16
+ export const noGit = (ref, path) => {
17
+ throw new Error(`cannot read \`git:${ref}:${path}\`: this build of contractdiff does not run git. fix: \`git show ${ref}:${path} > old.yaml\` and diff that file`);
18
+ };
19
+ const GIT = /^git:(?<ref>[^:]+):(?<path>.+)$/;
20
+ export const readContract = (spec, cwd, git, built = new Map()) => {
21
+ const match = GIT.exec(spec);
22
+ const { ref, path } = (match?.groups ?? {});
23
+ const file = path ?? spec;
24
+ const text = built.get(spec) ?? (ref === undefined ? readFileSync(resolve(cwd, spec), 'utf8') : git(ref, file, cwd));
25
+ let document;
26
+ try {
27
+ document = parseYaml(text);
28
+ }
29
+ catch (error) {
30
+ throw new Error(`cannot parse ${spec}: ${error.message}. fix: pass a JSON or YAML document`, { cause: error });
31
+ }
32
+ const found = Object.entries(builtinAdapters).find(([, adapter]) => adapter.detect(document));
33
+ if (found === undefined) {
34
+ throw new Error(`no input format reads ${spec}. fix: pass a document one of these reads: ${Object.keys(builtinAdapters).join(', ')}`);
35
+ }
36
+ return { label: spec, file, contract: found[1].read(document) };
37
+ };
38
+ const withBreaking = (comparison, breaking) => {
39
+ const findings = sortFindings([...comparison.findings, ...breaking]);
40
+ const summary = summaryOf(findings);
41
+ return { ...comparison, findings, summary, verdict: overall(summary) };
42
+ };
43
+ const findingOf = (annotation, level) => {
44
+ const where = annotation.path === '' ? `buf:${annotation.type}` : annotation.path;
45
+ return {
46
+ id: `buf:${annotation.type}`,
47
+ scheme: 'buf',
48
+ verdict: 'breaking',
49
+ effect: 'narrows',
50
+ operation: where,
51
+ source: annotation.path === '' ? where : `${annotation.path}:${String(annotation.line)}`,
52
+ document: 'new',
53
+ direction: 'request',
54
+ pointer: '',
55
+ before: undefined,
56
+ after: undefined,
57
+ fix: `${annotation.message} (buf breaking at --level ${level}): restore what changed, or release it as a new major version`,
58
+ };
59
+ };
60
+ export const bufFindings = async (options, level, breaking) => {
61
+ if (options.transitive === true)
62
+ throw new UsageError('--level compares two contracts. fix: drop --transitive, or run diff --level against each release');
63
+ const sides = [options.old, options.new];
64
+ const atRef = sides.find((spec) => GIT.test(spec));
65
+ if (atRef !== undefined)
66
+ throw new UsageError(`cannot judge ${atRef} at --level: buf reads a ref itself. ${refFix(atRef)}`);
67
+ for (const spec of sides) {
68
+ const { format } = readContract(spec, options.cwd, noGit, options.built).contract;
69
+ if (format !== 'protobuf')
70
+ throw new UsageError(`--level judges the wire encoding, and ${spec} reads as ${format}. fix: pass protobuf on both sides (a .proto, a buf module, or the image buf builds), or drop --level`);
71
+ }
72
+ const annotations = await breaking(options.new, options.old, level, options.cwd);
73
+ return annotations.map((annotation) => findingOf(annotation, level));
74
+ };
75
+ const COLUMN = 'non-breaking'.length;
76
+ const HASH_DIGITS = 8;
77
+ const LEVEL = { breaking: 'error', unknown: 'warning', dangerous: 'warning', 'non-breaking': 'note' };
78
+ const where = (finding) => [finding.payload ?? '', finding.pointer].filter((part) => part !== '').join(' ');
79
+ export const uriOf = (file) => (isAbsolute(file) ? pathToFileURL(file).href : file.replaceAll('\\', '/'));
80
+ const show = (value) => (value === undefined ? '-' : JSON.stringify(value));
81
+ const fileOf = (finding, files) => finding.document === 'new' ? files.nu.file : (files.releases?.get(finding.against) ?? files.old.file);
82
+ const resultOf = (finding, label, files) => ({
83
+ ruleId: finding.id,
84
+ level: LEVEL[finding.verdict],
85
+ message: { text: `${label}: ${finding.operation} ${where(finding)} ${show(finding.before)} -> ${show(finding.after)}. fix: ${finding.fix}` },
86
+ locations: [
87
+ {
88
+ physicalLocation: { artifactLocation: { uri: uriOf(fileOf(finding, files)) } },
89
+ logicalLocations: [{ fullyQualifiedName: `${finding.source}${finding.payload === undefined ? '' : ` ${finding.payload}`}${finding.pointer}` }],
90
+ },
91
+ ],
92
+ });
93
+ export const toSarif = (comparison, old, nu, releases) => {
94
+ const decisions = comparison.decisions ?? [];
95
+ const ids = [...new Set([...comparison.findings, ...decisions].map((finding) => finding.id))].sort();
96
+ return {
97
+ version: '2.1.0',
98
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
99
+ runs: [
100
+ {
101
+ tool: { driver: { name: 'contractdiff diff', rules: ids.map((id) => ({ id })) } },
102
+ results: [
103
+ ...comparison.findings.map((finding) => resultOf(finding, finding.verdict, { old, nu, releases })),
104
+ ...decisions.map((finding) => resultOf(finding, 'decision', { old, nu })),
105
+ ],
106
+ },
107
+ ],
108
+ };
109
+ };
110
+ const decisionLines = (decisions) => {
111
+ if (decisions.length === 0)
112
+ return [];
113
+ const level = decisions[0].verdict === 'breaking' ? 'error' : 'warn';
114
+ return [
115
+ '',
116
+ `decisions: ${String(decisions.length)} (--decisions ${level})`,
117
+ ...decisions.flatMap((finding) => [
118
+ ` ${level.padEnd(COLUMN)} ${finding.id} ${finding.operation} ${where(finding)} ${show(finding.before)} -> ${show(finding.after)}`,
119
+ ` ${''.padEnd(COLUMN)} fix: ${finding.fix}`,
120
+ ]),
121
+ ];
122
+ };
123
+ const notesOf = (finding) => [
124
+ finding.against === undefined ? '' : ` (against ${finding.against})`,
125
+ finding.note === undefined ? '' : ` (${finding.note})`,
126
+ finding.usedBy === undefined ? '' : ` (used by ${finding.usedBy.join(', ')})`,
127
+ ].join('');
128
+ const transitiveLine = (transitive) => `against ${String(transitive.against.length)} release(s), oldest first: ${transitive.against.join(', ')}; oldest broken: ${transitive.oldestBroken ?? 'none'}`;
129
+ export const toText = (comparison, old, nu) => {
130
+ const { summary, mode, side } = comparison;
131
+ const decisions = comparison.decisions ?? [];
132
+ if (comparison.findings.length === 0)
133
+ return [`no changes between ${old} and ${nu}`, ...decisionLines(decisions)].join('\n');
134
+ const lines = [
135
+ `${comparison.verdict}: ${String(summary.breaking)} breaking, ${String(summary.unknown)} unknown, ${summary.dangerous > 0 ? `${String(summary.dangerous)} dangerous, ` : ''}${String(summary['non-breaking'])} non-breaking (--mode ${mode} --side ${side})`,
136
+ ];
137
+ const operations = [...new Set(comparison.findings.map((finding) => finding.operation))];
138
+ if (comparison.transitive !== undefined)
139
+ lines.push(transitiveLine(comparison.transitive));
140
+ for (const operation of operations) {
141
+ const findings = comparison.findings.filter((finding) => finding.operation === operation);
142
+ lines.push('', `${operation} ${findings[0].source}`);
143
+ for (const finding of findings) {
144
+ lines.push(` ${finding.verdict.padEnd(COLUMN)} ${finding.id} ${where(finding)} ${show(finding.before)} -> ${show(finding.after)}${notesOf(finding)}`);
145
+ if (finding.verdict !== 'non-breaking')
146
+ lines.push(` ${''.padEnd(COLUMN)} fix: ${finding.fix}`);
147
+ }
148
+ }
149
+ return [...lines, ...decisionLines(decisions)].join('\n');
150
+ };
151
+ const BUMP = { breaking: 'major', unknown: 'major', dangerous: 'minor', 'non-breaking': 'minor' };
152
+ const writeChangeset = (cwd, pkg, comparison, labels) => {
153
+ const { old, nu } = labels;
154
+ if (comparison.findings.length === 0)
155
+ return undefined;
156
+ const body = comparison.findings.filter((finding) => finding.verdict !== 'non-breaking').map((finding) => `- ${finding.verdict}: \`${finding.id}\` in ${finding.operation} ${where(finding)}`);
157
+ const text = [`---`, `'${pkg}': ${BUMP[comparison.verdict]}`, `---`, '', `Contract changes from ${old} to ${nu}: ${comparison.verdict}.`, ...(body.length > 0 ? ['', ...body] : []), ''].join('\n');
158
+ const file = `.changeset/apicontract-diff-${createHash('sha256').update(text).digest('hex').slice(0, HASH_DIGITS)}.md`;
159
+ if (existsSync(resolve(cwd, file)))
160
+ return { file, changed: false };
161
+ mkdirSync(resolve(cwd, '.changeset'), { recursive: true });
162
+ writeFileSync(resolve(cwd, file), text);
163
+ return { file, changed: true };
164
+ };
165
+ const CONFIG = 'contractdiff.config.json';
166
+ const DATE_LENGTH = 10;
167
+ const settingAt = (ref, cwd, git) => {
168
+ try {
169
+ return decisionSettingOf(git(ref, CONFIG, cwd), CONFIG);
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ };
175
+ const settingFor = (options, git) => {
176
+ if (options.decisions !== undefined)
177
+ return options.decisions;
178
+ const { ref } = (GIT.exec(options.old)?.groups ?? {});
179
+ const atBase = ref === undefined ? undefined : settingAt(ref, options.cwd, git);
180
+ const file = resolve(options.cwd, CONFIG);
181
+ return atBase ?? (existsSync(file) ? decisionSettingOf(String(readFileSync(file)), CONFIG) : undefined) ?? 'warn';
182
+ };
183
+ const todayOf = (given) => {
184
+ if (given === undefined)
185
+ return new Date().toISOString().slice(0, DATE_LENGTH);
186
+ if (!isDate(given))
187
+ throw new UsageError(`--today takes a real date as YYYY-MM-DD, not ${given}. fix: pass a date such as --today 2027-01-01`);
188
+ return given;
189
+ };
190
+ const fails = (verdict) => verdict === 'breaking' || verdict === 'unknown';
191
+ const fixOf = (changed, verdict) => !fails(changed)
192
+ ? 'resolve each decision finding as its own fix line says, or run with `--decisions warn` while the contract catches up'
193
+ : `make each ${verdict} change compatible as its own fix line says, or release it as a major version`;
194
+ const VERSION_ORDER = new Intl.Collator('en', { numeric: true });
195
+ const CONTRACT_FILE = /\.(?:json|ya?ml)$/u;
196
+ const releasesOf = (spec, cwd, built) => {
197
+ const path = resolve(cwd, spec);
198
+ if (built.has(spec) || !existsSync(path) || !statSync(path).isDirectory())
199
+ return [spec];
200
+ return readdirSync(path)
201
+ .filter((name) => CONTRACT_FILE.test(name))
202
+ .sort(VERSION_ORDER.compare)
203
+ .map((name) => join(spec, name));
204
+ };
205
+ const sidesOf = (options, git) => {
206
+ const more = options.more ?? [];
207
+ const built = options.built ?? new Map();
208
+ if (options.transitive !== true) {
209
+ if (more.length > 0)
210
+ throw new UsageError(`diff compares two contracts, and was given ${String(more.length + 2)}. fix: pass --transitive to compare the last one with each before it, oldest first`);
211
+ return { olds: [readContract(options.old, options.cwd, git, built)], nu: readContract(options.new, options.cwd, git, built) };
212
+ }
213
+ const specs = [options.old, options.new, ...more];
214
+ const olds = specs.slice(0, -1).flatMap((spec) => releasesOf(spec, options.cwd, built));
215
+ if (olds.length === 0)
216
+ throw new UsageError(`no contract to compare with: ${specs.slice(0, -1).join(', ')} holds no .json, .yaml or .yml file. fix: pass the past releases' files, oldest first`);
217
+ return { olds: olds.map((spec) => readContract(spec, options.cwd, git, built)), nu: readContract(specs.at(-1), options.cwd, git, built) };
218
+ };
219
+ const usageOf = (file, cwd) => {
220
+ const path = resolve(cwd, file);
221
+ if (!existsSync(path))
222
+ throw new UsageError(`there is no usage file ${file}. fix: pass the path of a JSON file that says which operations callers use, or an contractdiff.map.json`);
223
+ return parseUsage(String(readFileSync(path)), file);
224
+ };
225
+ export const diff = (options) => {
226
+ const git = options.git ?? noGit;
227
+ const { olds, nu } = sidesOf(options, git);
228
+ const first = olds[0];
229
+ const last = olds.at(-1);
230
+ const compare = { mode: options.mode, side: options.side, dangerousBreaking: options.dangerousBreaking };
231
+ const latest = compareContracts(last.contract, nu.contract, compare);
232
+ const compared = options.transitive === true ? compareTransitive(olds, nu.contract, compare) : latest;
233
+ const used = options.usage === undefined ? compared : applyUsage(compared, usageOf(options.usage, options.cwd));
234
+ const changes = options.breaking === undefined ? used : withBreaking(used, options.breaking);
235
+ const level = settingFor(options, git);
236
+ const today = todayOf(options.today);
237
+ const comparison = level === 'off' ? { ...changes, decisions: [] } : withDecisions(changes, checkDecisions(last.contract, nu.contract, latest, { today, level, changeset: options.changeset !== undefined }), level);
238
+ const sarif = options.sarif === true ? toSarif(comparison, last, nu, new Map(olds.map((side) => [side.label, side.file]))) : undefined;
239
+ const old = first;
240
+ const written = options.changeset === undefined ? undefined : writeChangeset(options.cwd, options.changeset, comparison, { old: old.label, nu: nu.label });
241
+ const failed = fails(comparison.verdict);
242
+ const data = {
243
+ ...comparison,
244
+ old: old.label,
245
+ new: nu.label,
246
+ ...(sarif === undefined ? {} : { sarif }),
247
+ changed: written?.changed ?? false,
248
+ ...(written === undefined ? {} : { changeset: written.file }),
249
+ ...(failed
250
+ ? {
251
+ exitCode: ExitCode.RUNTIME,
252
+ fix: fixOf(changes.verdict, comparison.verdict),
253
+ }
254
+ : {}),
255
+ };
256
+ data[TEXT] = () => (sarif === undefined ? toText(comparison, old.label, nu.label) : JSON.stringify(sarif, undefined, 2));
257
+ return data;
258
+ };
259
+ const HERE = '.';
260
+ export const command = defineCommand({
261
+ name: 'diff',
262
+ description: 'What a contract change breaks, and for whom, under the compatibility mode you pick',
263
+ effects: 'idempotent',
264
+ examples: [
265
+ { command: 'contractdiff diff old.yaml new.yaml', description: 'what breaks for callers built on old.yaml' },
266
+ { command: 'contractdiff diff old.yaml new.yaml --mode full --sarif', description: 'both directions, for code scanning' },
267
+ { command: 'contractdiff diff releases/ openapi.yaml --transitive', description: 'what breaks for callers on any past release, the oldest named' },
268
+ ],
269
+ arguments: [
270
+ { name: 'old', description: 'the contract before: a file, or git:<ref>:<path>' },
271
+ { name: 'new', description: 'the contract after: a file, or git:<ref>:<path>' },
272
+ { name: 'more', variadic: true, required: false, description: 'with --transitive: more contracts, oldest first; the last is the new one, and a directory stands for its files in version order' },
273
+ ],
274
+ options: {
275
+ mode: { type: 'string', choices: MODES, description: 'backward: old peers keep working; forward: the side may move first; full: both (default backward)' },
276
+ side: { type: 'string', choices: SIDES, description: 'whose code the question is about (default caller)' },
277
+ sarif: { type: 'boolean', description: 'print SARIF 2.1.0 for code scanning instead of text' },
278
+ changeset: { type: 'string', description: 'write .changeset/<hash>.md bumping this package by the verdict', placeholder: 'package' },
279
+ decisions: {
280
+ type: 'string',
281
+ choices: DECISION_SETTINGS,
282
+ description: 'hold a change to the decision written in the contract: warn (default; prints, exit code unchanged), error (fails the run) or off. Read from the base ref\'s contractdiff.config.json first',
283
+ },
284
+ usage: { type: 'string', description: 'a JSON file of the operations and members callers use (or an contractdiff.map.json): a breaking change nobody uses is non-breaking', placeholder: 'file' },
285
+ transitive: { type: 'boolean', description: 'compare the last contract with every one before it, not only the last: findings say which release they break' },
286
+ level: { type: 'string', choices: LEVELS, description: 'protobuf only: also judge the wire encoding with buf breaking at this category; its findings count as breaking' },
287
+ dangerousBreaking: { type: 'boolean', description: 'report dangerous changes (a default changed, a value a reader may not expect) as breaking, so they fail the run' },
288
+ today: { type: 'string', description: 'the date x-sunset is judged against (default: today, UTC)', placeholder: 'YYYY-MM-DD' },
289
+ },
290
+ run: async ({ args, options }) => {
291
+ const sides = {
292
+ built: await builtImages([args.old, args.new, ...args.more], HERE, bufIn()),
293
+ cwd: HERE,
294
+ old: args.old,
295
+ new: args.new,
296
+ more: args.more,
297
+ transitive: options.transitive,
298
+ usage: options.usage,
299
+ mode: options.mode,
300
+ side: options.side,
301
+ sarif: options.sarif,
302
+ changeset: options.changeset,
303
+ decisions: options.decisions,
304
+ today: options.today,
305
+ dangerousBreaking: options.dangerousBreaking,
306
+ };
307
+ const level = options.level;
308
+ return diff(level === undefined ? sides : { ...sides, breaking: await bufFindings(sides, level, breakingIn()) });
309
+ },
310
+ });
@@ -0,0 +1,36 @@
1
+ export const bytesOf = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
2
+ const isContainer = (value) => typeof value === 'object' && value !== null;
3
+ const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
4
+ const slots = (slot) => {
5
+ const value = slot.holder[slot.key];
6
+ if (!isContainer(value))
7
+ return [];
8
+ const children = Object.keys(value).map((key) => slots({ holder: value, key, pointer: `${slot.pointer}/${token(key)}`, depth: slot.depth + 1 }));
9
+ return [slot, ...children.flat()];
10
+ };
11
+ const isEmpty = (value) => Object.keys(value).length === 0;
12
+ export const cap = (value, max, keep = 0) => {
13
+ let size = bytesOf(value);
14
+ if (size <= max)
15
+ return { value, cut: [] };
16
+ const root = { value: structuredClone(value) };
17
+ const order = slots({ holder: root, key: 'value', pointer: '', depth: 0 })
18
+ .filter((slot) => slot.depth >= keep)
19
+ .toSorted((a, b) => b.depth - a.depth);
20
+ const cut = [];
21
+ for (const slot of order) {
22
+ if (size <= max)
23
+ break;
24
+ const node = slot.holder[slot.key];
25
+ if (isEmpty(node))
26
+ continue;
27
+ const emptied = Array.isArray(node) ? [] : {};
28
+ size -= bytesOf(node) - bytesOf(emptied);
29
+ Object.defineProperty(slot.holder, slot.key, { value: emptied, enumerable: true });
30
+ for (let at = cut.length - 1; at >= 0; at--)
31
+ if (cut[at].startsWith(`${slot.pointer}/`))
32
+ cut.splice(at, 1);
33
+ cut.push(slot.pointer);
34
+ }
35
+ return { value: root.value, cut };
36
+ };