@tduyng/pi-claude 0.0.0-stage → 0.0.1

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,178 @@
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
+ Copyright 2026 tduyng
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # pi-claude
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
+ Claude Pro/Max subscription models in Pi, through the official Claude Code CLI. Pi keeps its own system prompt, tools, approvals, compaction and session tree. Claude Code is only the authenticated model transport.
4
+
5
+ The provider id is `claude`, and model ids are the same ids Pi uses for Anthropic. `/model claude/claude-opus-5` and `anthropic/claude-opus-5` name the same model. The catalog comes from `@earendil-works/pi-ai`, so new Claude models appear when Pi updates, without editing this extension.
6
+
7
+ ## Requirements
8
+
9
+ - Pi 1.4 or newer.
10
+ - Claude Code 2.1.281 or newer on `PATH`.
11
+ - A Claude Pro, Max, Team or Enterprise login: run `claude auth login`.
12
+ - `PI_CLAUDE_BIN` only when the binary is not named `claude`.
13
+
14
+ This extension never reads `~/.claude/.credentials.json`, never copies OAuth tokens, and never talks to the Anthropic API directly. Authentication and billing stay with the Claude Code CLI.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pi install /path/to/extensions/pi-claude
20
+ ```
21
+
22
+ For this repository the workspace already registers the extension in the root `package.json`.
23
+
24
+ ## Use
25
+
26
+ ```sh
27
+ pi --provider claude --model claude-opus-5
28
+ ```
29
+
30
+ Inside Pi:
31
+
32
+ ```text
33
+ /model claude/claude-opus-5
34
+ ```
35
+
36
+ `/claude status` shows the binary, login, MCP port and live processes. `/claude models` lists every id. `/claude clear` closes the warm processes.
37
+
38
+ ## What it sends
39
+
40
+ | Pi | Claude Code |
41
+ | ----------------- | ------------------------------------------------------------------------- |
42
+ | Pi system prompt | `--system-prompt-file`, replaces the default prompt |
43
+ | Pi tools | MCP server named `pi`, exposed as `mcp__pi__<tool>` |
44
+ | Pi tool execution | MCP call parked until Pi runs the tool, then the result resolves the call |
45
+ | Pi compaction | `DISABLE_AUTO_COMPACT=1`, Pi decides when to compact |
46
+ | Pi approvals | every tool call returns to Pi and runs there |
47
+
48
+ Claude Code's own system prompt, `CLAUDE.md`, rules, skills, slash commands, hooks, plugins, project MCP servers, auto memory, git snapshot, title generation and auto compaction are disabled with flags and environment variables.
49
+
50
+ ## Token and cache behavior
51
+
52
+ One Claude Code process runs per Pi session with `--input-format stream-json`. A normal turn writes only the new user message to stdin. A tool round parks the MCP calls and returns one Pi assistant message with the tool calls, then the next provider call delivers the results into the same process. Nothing is respawned, nothing is replayed, and the prompt cache prefix stays intact.
53
+
54
+ `--resume` is not used. Claude Code 2.1.69 changed how a resumed conversation rebuilds `messages[0]`, which invalidates the conversation cache on every turn. A live streaming process avoids that path completely.
55
+
56
+ A Pi abort sends Claude Code an `interrupt` control request instead of killing it, so the process and its cache survive. An abort during tool execution keeps the parked calls, and Pi's `Operation aborted` results resolve them on the next turn. An idle process lives for 60 minutes, the length of the prompt cache.
57
+
58
+ When Pi history diverges from the live process, for example after editing an earlier message, changing the model, changing the tool set or resuming a Pi session after a restart, the process is replaced and the existing Pi conversation is replayed once as a single user message. That one turn is a cold cache. Later turns are warm again.
59
+
60
+ ## Limitations
61
+
62
+ - Every request counts against the Claude subscription limits, exactly like Claude Code itself.
63
+ - Anthropic may treat a third-party harness prompt differently from Claude Code own prompt. If a turn fails with a third-party or extra-usage message, the rejection is about the prompt shape, not the CLI transport.
64
+ - One process per Pi session. Subagents with different prompts get their own process, up to eight alive at once.
65
+ - A model change, a thinking level change or a tool set change rebuilds the session on the next turn.
66
+ - Images in replayed history are attached to the replay message. New user images are sent normally.
67
+ - Claude Code needs a model id it recognizes. New models may need a newer Claude Code than the one installed.
68
+ - Claude Code caps MCP tool output and may move very large text to a file. Pi tools normally truncate before that cap.
69
+ - Usage is reported from Claude Code stream events. Monetary cost is Pi's API-equivalent estimate, not the subscription bill.
70
+
71
+ ## Configuration
72
+
73
+ | Variable | Meaning |
74
+ | --------------- | ----------------------------------------- |
75
+ | `PI_CLAUDE_BIN` | Claude Code executable. Default `claude`. |
76
+
77
+ ```sh
78
+ PI_CLAUDE_BIN=/home/you/.nix-profile/bin/claude pi
79
+ ```
80
+
81
+ ## Tests
82
+
83
+ ```sh
84
+ bun run test -- extensions/pi-claude
85
+ bun run typecheck
86
+ bun run lint:anti-slop
87
+ ```
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@tduyng/pi-claude",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Use Claude Pro/Max subscription models in Pi through the official Claude Code CLI, with Pi's own prompt and tools.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "claude",
11
+ "claude-code",
12
+ "models"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "author": "tduyng",
16
+ "type": "module",
17
+ "files": [
18
+ "src",
19
+ "!src/**/*.test.ts",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "peerDependencies": {
24
+ "@earendil-works/pi-ai": "*",
25
+ "@earendil-works/pi-coding-agent": "*"
26
+ },
27
+ "pi": {
28
+ "extensions": [
29
+ "./src/index.ts"
30
+ ]
31
+ },
32
+ "dependencies": {
33
+ "ata-validator": "^1.62.1"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://gitlab.com/tduyng/pi-agent.git",
38
+ "directory": "extensions/pi-claude"
39
+ },
40
+ "homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-claude#readme",
41
+ "bugs": "https://gitlab.com/tduyng/pi-agent/-/issues"
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,170 @@
1
+ import { execFile } from 'node:child_process'
2
+
3
+ import type { ThinkingLevelMap } from '@earendil-works/pi-ai'
4
+ import { ANTHROPIC_MODELS } from '@earendil-works/pi-ai/providers/anthropic.models'
5
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
6
+
7
+ import { startMcpServer, type McpServerHandle } from './mcp.js'
8
+ import { claudeBin } from './protocol.js'
9
+ import { allSessions, dropSessions, sweep } from './session.js'
10
+ import { createRuntime, streamClaude, type ClaudeRuntime } from './turn.js'
11
+
12
+ const PROVIDER_ID = 'claude'
13
+ const API_ID = 'claude'
14
+ const IDLE_MS = 60 * 60_000
15
+
16
+ type PiModelEntry = {
17
+ id: string
18
+ name: string
19
+ reasoning: boolean
20
+ thinkingLevelMap?: ThinkingLevelMap
21
+ input: ('text' | 'image')[]
22
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number }
23
+ contextWindow: number
24
+ maxTokens: number
25
+ }
26
+
27
+ function piModels(): PiModelEntry[] {
28
+ const models: PiModelEntry[] = []
29
+ for (const model of Object.values(ANTHROPIC_MODELS)) {
30
+ if (/-\d{8}$/.test(model.id)) continue
31
+ const input = model.input.filter((item): item is 'text' | 'image' => item === 'text' || item === 'image')
32
+ const entry: PiModelEntry = {
33
+ id: model.id,
34
+ name: model.name,
35
+ reasoning: model.reasoning,
36
+ input,
37
+ cost: {
38
+ input: model.cost.input,
39
+ output: model.cost.output,
40
+ cacheRead: model.cost.cacheRead,
41
+ cacheWrite: model.cost.cacheWrite
42
+ },
43
+ contextWindow: model.contextWindow,
44
+ maxTokens: model.maxTokens
45
+ }
46
+ if (model.thinkingLevelMap) entry.thinkingLevelMap = model.thinkingLevelMap
47
+ models.push(entry)
48
+ }
49
+ return models
50
+ }
51
+
52
+ function run(command: string, args: string[]): Promise<string> {
53
+ return new Promise((resolve) => {
54
+ execFile(command, args, { timeout: 10_000 }, (error, stdout, stderr) => {
55
+ if (error) {
56
+ resolve(`${error.message}${stderr.trim() ? `\n${stderr.trim()}` : ''}`)
57
+ return
58
+ }
59
+ resolve(stdout.trim())
60
+ })
61
+ })
62
+ }
63
+
64
+ export default function claude(pi: ExtensionAPI): void {
65
+ let mcp: McpServerHandle | undefined
66
+ let starting: Promise<McpServerHandle> | undefined
67
+ let sweeper: ReturnType<typeof setInterval> | undefined
68
+
69
+ async function ensureMcp(): Promise<McpServerHandle> {
70
+ if (mcp) return mcp
71
+ starting ??= startMcpServer()
72
+ .then((server) => {
73
+ mcp = server
74
+ starting = undefined
75
+ if (!sweeper) {
76
+ sweeper = setInterval(() => sweep(runtime.sessions, IDLE_MS), 60_000)
77
+ sweeper.unref()
78
+ }
79
+ return server
80
+ })
81
+ .catch((error: Error) => {
82
+ starting = undefined
83
+ throw error
84
+ })
85
+ return starting
86
+ }
87
+
88
+ const runtime: ClaudeRuntime = createRuntime(ensureMcp)
89
+ const models = piModels()
90
+
91
+ pi.registerProvider(PROVIDER_ID, {
92
+ name: 'Claude (subscription)',
93
+ baseUrl: 'claude://local',
94
+ apiKey: 'claude-code-login',
95
+ api: API_ID,
96
+ models,
97
+ streamSimple: (model, context, options) => streamClaude(runtime, model, context, options)
98
+ })
99
+
100
+ pi.on('session_shutdown', async () => {
101
+ dropSessions(runtime.sessions)
102
+ const server = mcp
103
+ mcp = undefined
104
+ starting = undefined
105
+ if (sweeper) clearInterval(sweeper)
106
+ sweeper = undefined
107
+ await server?.close()
108
+ })
109
+
110
+ process.once('exit', () => dropSessions(runtime.sessions))
111
+
112
+ const show = (text: string) =>
113
+ pi.sendMessage({ customType: 'claude', display: true, content: text }, { triggerTurn: false })
114
+
115
+ pi.registerCommand('claude', {
116
+ description: 'Status and model list for the Claude subscription bridge',
117
+ getArgumentCompletions: (prefix: string) =>
118
+ [
119
+ { value: 'status', label: 'status', description: 'binary, login and live sessions' },
120
+ { value: 'models', label: 'models', description: 'every Claude model the bridge exposes' },
121
+ { value: 'clear', label: 'clear', description: 'close every warm Claude Code process' },
122
+ { value: 'help', label: 'help', description: 'usage' }
123
+ ].filter((item) => item.value.startsWith(prefix.trim())),
124
+ handler: async (args: string) => {
125
+ const sub = args.trim().split(/\s+/).filter(Boolean)[0] ?? 'status'
126
+ if (sub === 'clear') {
127
+ dropSessions(runtime.sessions)
128
+ await show('claude: closed every warm Claude Code process.')
129
+ return
130
+ }
131
+ if (sub === 'models') {
132
+ await show(
133
+ [
134
+ `${models.length} model(s), provider id ${PROVIDER_ID}:`,
135
+ ...models.map((model) => ` ${PROVIDER_ID}/${model.id}`)
136
+ ].join('\n')
137
+ )
138
+ return
139
+ }
140
+ if (sub === 'help') {
141
+ await show(
142
+ [
143
+ 'Usage: /claude [status|models|clear|help]',
144
+ '',
145
+ '/login is not used. Authentication is Claude Code own login:',
146
+ ' claude auth login',
147
+ 'Then pick a model with /model, for example claude/claude-opus-5.',
148
+ 'PI_CLAUDE_BIN overrides the claude executable.'
149
+ ].join('\n')
150
+ )
151
+ return
152
+ }
153
+ const sessions = allSessions(runtime.sessions)
154
+ const parked = sessions.reduce((count, session) => count + session.parked.size, 0)
155
+ const version = await run(claudeBin(), ['--version'])
156
+ const auth = await run(claudeBin(), ['auth', 'status'])
157
+ await show(
158
+ [
159
+ `binary: ${claudeBin()}`,
160
+ `version: ${version || 'unknown'}`,
161
+ `login: ${auth || 'unknown'}`,
162
+ `MCP: ${mcp ? `127.0.0.1:${mcp.port}` : 'not running'}`,
163
+ `models: ${models.length}`,
164
+ `live processes: ${sessions.length}, parked tool calls: ${parked}`,
165
+ `prompt: Pi own system prompt and tools, Claude Code prompt and settings disabled`
166
+ ].join('\n')
167
+ )
168
+ }
169
+ })
170
+ }
package/src/json.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ import { Validator } from 'ata-validator'
4
+ import { t } from 'ata-validator/t'
5
+
6
+ const isStringArray = new Validator(t.array(t.string())).isValidObject
7
+ const isString = new Validator(t.string()).isValidObject
8
+ const isNumber = new Validator(t.number()).isValidObject
9
+ const isBoolean = new Validator(t.boolean()).isValidObject
10
+
11
+ export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject
12
+ export type JsonObject = { [key: string]: JsonValue }
13
+
14
+ const ObjectSchema = t.object({}, { additionalProperties: true })
15
+ const isObjectSchema = new Validator(ObjectSchema).isValidObject
16
+ const ArraySchema = t.array(t.any())
17
+ const isArraySchema = new Validator(ArraySchema).isValidObject
18
+
19
+ function isJsonObject<V>(value: V): value is V & JsonObject {
20
+ return isObjectSchema(value) && !Array.isArray(value)
21
+ }
22
+
23
+ export function jsonObject(value: JsonValue | undefined): JsonObject | undefined {
24
+ return isJsonObject(value) ? value : undefined
25
+ }
26
+
27
+ export function jsonArray(value: JsonValue | undefined): JsonValue[] | undefined {
28
+ if (!isArraySchema(value)) return undefined
29
+ return value
30
+ }
31
+
32
+ export function jsonStrings(value: JsonValue | undefined): string[] | undefined {
33
+ if (!isStringArray(value)) return undefined
34
+ return value
35
+ }
36
+
37
+ export function jsonText(object: JsonObject, key: string): string | undefined {
38
+ const value = object[key]
39
+ return isString(value) ? value : undefined
40
+ }
41
+
42
+ export function jsonNumber(object: JsonObject, key: string): number | undefined {
43
+ const value = object[key]
44
+ return isNumber(value) ? value : undefined
45
+ }
46
+
47
+ export function jsonBoolean(object: JsonObject, key: string): boolean | undefined {
48
+ const value = object[key]
49
+ return isBoolean(value) ? value : undefined
50
+ }
51
+
52
+ export function jsonFlag(object: JsonObject, key: string): boolean {
53
+ return jsonBoolean(object, key) === true
54
+ }
55
+
56
+ export function stableStringify(value: JsonValue): string {
57
+ return JSON.stringify(sortValue(value))
58
+ }
59
+
60
+ function sortValue(value: JsonValue): JsonValue {
61
+ if (Array.isArray(value)) return value.map(sortValue)
62
+ const object = jsonObject(value)
63
+ if (!object) return value
64
+ const sorted: JsonObject = {}
65
+ for (const key of Object.keys(object).toSorted()) {
66
+ const item = object[key]
67
+ if (item !== undefined) sorted[key] = sortValue(item)
68
+ }
69
+ return sorted
70
+ }
71
+
72
+ export function sha(value: string): string {
73
+ return createHash('sha256').update(value).digest('base64url')
74
+ }