@zodiaceco/sdk 1.12.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 +165 -0
- package/README.md +175 -0
- package/dist/allow/index.d.mts +2 -0
- package/dist/allow/index.mjs +3 -0
- package/dist/allow-CzPpzclq.mjs +121 -0
- package/dist/allow-CzPpzclq.mjs.map +1 -0
- package/dist/api-C49DoaPC.mjs +144 -0
- package/dist/api-C49DoaPC.mjs.map +1 -0
- package/dist/cli/config.d.mts +90 -0
- package/dist/cli/config.mjs +2 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +574 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/config-D5ArAp07.mjs +126 -0
- package/dist/config-D5ArAp07.mjs.map +1 -0
- package/dist/index-DoZbhpS6.d.mts +63 -0
- package/dist/index.d.mts +256 -0
- package/dist/index.mjs +214 -0
- package/dist/index.mjs.map +1 -0
- package/dist/networks-BTW1qAAa.mjs +77 -0
- package/dist/networks-BTW1qAAa.mjs.map +1 -0
- package/dist/zodiac-os-codegen.d.ts +14 -0
- package/package.json +68 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
package/README.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# Zodiac OS SDK
|
|
2
|
+
|
|
3
|
+
Programmatically manage [Zodiac](https://www.zodiac.eco) account constellations.
|
|
4
|
+
|
|
5
|
+
## Getting started
|
|
6
|
+
|
|
7
|
+
### 1. Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @zodiaceco/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
### 2. Authorize project
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
zodiac init
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Opens a browser tab so you can sign in, pick the org you want to use, and approve a new API key. The key (and matching `ZODIAC_API_URL`) are written to a `.env` file in your project root — labeled after the directory so you can find and revoke it later from [app.zodiac.eco/admin/api-keys](https://app.zodiac.eco/admin/api-keys).
|
|
20
|
+
|
|
21
|
+
**IMPORTANT:** Make sure to add `.env` to your `.gitignore`.
|
|
22
|
+
|
|
23
|
+
### 3. Create a config file
|
|
24
|
+
|
|
25
|
+
Create a `zodiac.config.ts` in your project root.
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { defineConfig } from '@zodiaceco/sdk/cli/config'
|
|
29
|
+
|
|
30
|
+
export default defineConfig({
|
|
31
|
+
contracts: {
|
|
32
|
+
mainnet: {
|
|
33
|
+
dai: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 4. Pull your org data
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
# Pull everything (org data + contract ABIs)
|
|
43
|
+
zodiac pull
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
This generates typed data in `.zodiac/` at your project root with your org's users and accounts (workspace vaults plus accounts that have been applied via a constellation). Add `.zodiac/` to your `.gitignore`.
|
|
47
|
+
|
|
48
|
+
## Constellation API
|
|
49
|
+
|
|
50
|
+
The `constellation()` function is the main SDK entry point. It returns an API for declaring account constellations — the set of Safes, Roles mods, and users that make up your on-chain setup.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { constellation } from '@zodiaceco/sdk'
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Scoping to a workspace and chain
|
|
57
|
+
|
|
58
|
+
Each constellation is scoped to a single workspace and chain. The `workspace` option must be a valid workspace name from your org.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const eth = constellation({
|
|
62
|
+
workspace: 'GG',
|
|
63
|
+
label: 'Production',
|
|
64
|
+
chain: 1,
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Referencing existing accounts
|
|
69
|
+
|
|
70
|
+
Bracket access gives you existing Safes and Roles mods from the selected workspace — both **vault accounts** (manually-promoted entries surfaced in the workspace UI) and any **constellation accounts** previously created by a `push()`. The codegen records them under the same `accounts` map, marked with a `vault` flag for the subset that are also workspace vaults. Names auto-complete from the codegen output.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// Reference an existing Safe — no invocation needed
|
|
74
|
+
const ggDao = eth.safe['GG DAO']
|
|
75
|
+
|
|
76
|
+
// Reference an existing Roles mod
|
|
77
|
+
const ggDaoRoles = eth.roles['GG DAO Roles']
|
|
78
|
+
|
|
79
|
+
// Optionally invoke with overrides
|
|
80
|
+
const ggDaoOverridden = eth.safe['GG DAO']({ threshold: 5 })
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
> `bun push` runs `pull-org` first via the `prepush` hook, so re-pushing always sees the freshest existing-account values from your org.
|
|
84
|
+
|
|
85
|
+
### Creating new accounts
|
|
86
|
+
|
|
87
|
+
Use bracket access with a new label to create new nodes. Every mandatory field (`nonce`, `threshold`, `owners` for Safes; `nonce` for Roles mods) must be supplied explicitly — the SDK does not inject any runtime defaults. The type system surfaces a missing field as a compile-time error so you can't ship an incomplete spec.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// New Safe — nonce, threshold, owners are required
|
|
91
|
+
const newSafe = eth.safe['New Safe']({
|
|
92
|
+
nonce: 0n,
|
|
93
|
+
threshold: 2,
|
|
94
|
+
owners: [
|
|
95
|
+
eth.user['Alice Sample'],
|
|
96
|
+
'0xb8e48df6818d3cbc648b3e8ec248a4f547135f7a',
|
|
97
|
+
],
|
|
98
|
+
modules: [ggDaoRoles],
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
// New Roles mod targeting an existing Safe
|
|
102
|
+
const newRoles = eth.roles['New Roles']({
|
|
103
|
+
nonce: 0n,
|
|
104
|
+
target: ggDao,
|
|
105
|
+
})
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
When a bracket label matches an existing account from your codegen, all overrides become optional — you pass only the fields you want to change against the live configuration.
|
|
109
|
+
|
|
110
|
+
### Circular references between new nodes
|
|
111
|
+
|
|
112
|
+
New nodes can reference each other before either has been invoked — use the uninvoked factory as a forward reference:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
const safe = eth.safe['New Safe']({
|
|
116
|
+
nonce: 0n,
|
|
117
|
+
threshold: 1,
|
|
118
|
+
owners: [eth.user['Alice Sample']],
|
|
119
|
+
// Forward reference to a Roles mod that doesn't exist yet
|
|
120
|
+
modules: [eth.roles['New Roles']],
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
const roles = eth.roles['New Roles']({
|
|
124
|
+
nonce: 0n,
|
|
125
|
+
target: safe,
|
|
126
|
+
})
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
References are resolved by label at `push()` time, so both sides of the cycle must be included in the call.
|
|
130
|
+
|
|
131
|
+
### Referencing users
|
|
132
|
+
|
|
133
|
+
`eth.user[handle]` resolves a user to their personal Safe address on the current chain:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
const aliceAddress = eth.user['Alice Sample']
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Pushing the constellation
|
|
140
|
+
|
|
141
|
+
The `push()` function takes all nodes and sends them to the Zodiac OS API. Pass either a named object (keys become refs) or an array:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
import { push } from '@zodiaceco/sdk'
|
|
145
|
+
|
|
146
|
+
await push({ ggDao, ggDaoRoles, newSafe, newRoles })
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
All referenced nodes must be included in the `push()` call.
|
|
150
|
+
|
|
151
|
+
By default, `push()` creates an API client from the `ZODIAC_API_KEY` environment variable. You can pass a custom client:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
await push({ ggDao, newRoles }, { api: new ApiClient({ apiKey: '...' }) })
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## CLI reference
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
Usage: zodiac [options] [command]
|
|
161
|
+
|
|
162
|
+
Zodiac SDK CLI – pull org data and contract ABIs
|
|
163
|
+
|
|
164
|
+
Options:
|
|
165
|
+
-V, --version output the version number
|
|
166
|
+
-c, --config <path> path to the config file (default: "zodiac.config.ts")
|
|
167
|
+
-h, --help display help for command
|
|
168
|
+
|
|
169
|
+
Commands:
|
|
170
|
+
init Authorize this directory with a Zodiac org. Opens a browser to mint an API key and writes it to .env.
|
|
171
|
+
pull-org Fetch Zodiac users and accounts, generate TypeScript types
|
|
172
|
+
pull-contracts Fetch contract ABIs, generate typed permissions kit
|
|
173
|
+
pull Fetch Zodiac org and contracts ABI, generate SDK functions
|
|
174
|
+
help [command] display help for command
|
|
175
|
+
```
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as EVERYTHING, c as Scoping, i as ConditionFunction, l as TargetPermission, n as ChainPrefix, o as FunctionPermission, r as chainIdFor, s as Options, t as CHAIN_IDS, u as buildAllowKit } from "../index-DoZbhpS6.mjs";
|
|
2
|
+
export { CHAIN_IDS, ChainPrefix, ConditionFunction, EVERYTHING, FunctionPermission, Options, Scoping, TargetPermission, buildAllowKit, chainIdFor };
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { a as walkContracts, i as readAbi } from "./networks-BTW1qAAa.mjs";
|
|
2
|
+
import { Operator, ParameterType, c, coercePermission } from "zodiac-roles-sdk";
|
|
3
|
+
import { Interface, isError } from "ethers";
|
|
4
|
+
//#region src/allow/types.ts
|
|
5
|
+
const EVERYTHING = Symbol.for("@zodiaceco/allow-kit/EVERYTHING");
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/allow/runtime.ts
|
|
8
|
+
function buildAllowKit(abisDir, contractsConfig) {
|
|
9
|
+
const kit = {};
|
|
10
|
+
for (const node of walkContracts(contractsConfig)) {
|
|
11
|
+
const abi = readAbi(abisDir, node);
|
|
12
|
+
if (!abi) {
|
|
13
|
+
attachAt(kit, [node.chain, ...node.segments], missingAbiProxy(node));
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
attachAt(kit, [node.chain, ...node.segments], makeAllowContract(node.address, abi));
|
|
17
|
+
}
|
|
18
|
+
return kit;
|
|
19
|
+
}
|
|
20
|
+
function attachAt(root, segments, value) {
|
|
21
|
+
let cursor = root;
|
|
22
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
23
|
+
const seg = segments[i];
|
|
24
|
+
if (!(seg in cursor)) cursor[seg] = {};
|
|
25
|
+
cursor = cursor[seg];
|
|
26
|
+
}
|
|
27
|
+
cursor[segments[segments.length - 1]] = value;
|
|
28
|
+
}
|
|
29
|
+
function missingAbiProxy(node) {
|
|
30
|
+
const explain = () => {
|
|
31
|
+
throw new Error(`ABI missing for ${node.chain}.${node.segments.join(".")} (${node.address}). Run \`zodiac pull-contracts\` to fetch it, or paste the ABI JSON manually at <abisDir>/${node.chain}/${node.segments.join("/")}.json`);
|
|
32
|
+
};
|
|
33
|
+
return new Proxy({}, {
|
|
34
|
+
get: explain,
|
|
35
|
+
has: explain
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function makeAllowContract(address, abi) {
|
|
39
|
+
const iface = Interface.from(abi);
|
|
40
|
+
const lowerAddr = address.toLowerCase();
|
|
41
|
+
const allowEverything = (options) => ({
|
|
42
|
+
targetAddress: lowerAddr,
|
|
43
|
+
send: options?.send,
|
|
44
|
+
delegatecall: options?.delegatecall
|
|
45
|
+
});
|
|
46
|
+
const has = (name) => {
|
|
47
|
+
try {
|
|
48
|
+
const fn = iface.getFunction(name);
|
|
49
|
+
if (!fn) return false;
|
|
50
|
+
return fn.stateMutability !== "view" && fn.stateMutability !== "pure";
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (!isError(error, "INVALID_ARGUMENT")) throw error;
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
return new Proxy({}, {
|
|
57
|
+
get: (_target, prop) => {
|
|
58
|
+
if (prop === EVERYTHING) return allowEverything;
|
|
59
|
+
if (typeof prop !== "string") return void 0;
|
|
60
|
+
if (!has(prop)) return void 0;
|
|
61
|
+
return makeAllowFunction(iface.getFunction(prop), lowerAddr);
|
|
62
|
+
},
|
|
63
|
+
has: (_target, prop) => {
|
|
64
|
+
if (prop === EVERYTHING) return true;
|
|
65
|
+
return typeof prop === "string" && has(prop);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function makeAllowFunction(fn, targetAddress) {
|
|
70
|
+
const inputs = fn.inputs;
|
|
71
|
+
return (...args) => {
|
|
72
|
+
const scopings = args.slice(0, inputs.length);
|
|
73
|
+
const hasScopings = scopings.some((s) => s !== void 0 && s !== null);
|
|
74
|
+
const options = args[inputs.length] ?? {};
|
|
75
|
+
const condition = hasScopings ? c.calldataMatches(scopings, inputs)() : void 0;
|
|
76
|
+
return applyOptions(coercePermission({
|
|
77
|
+
targetAddress,
|
|
78
|
+
signature: fn.format("sighash"),
|
|
79
|
+
condition
|
|
80
|
+
}), options);
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const emptyCalldataMatches = {
|
|
84
|
+
paramType: ParameterType.Calldata,
|
|
85
|
+
operator: Operator.Matches,
|
|
86
|
+
children: []
|
|
87
|
+
};
|
|
88
|
+
const applyGlobalAllowance = (condition, allowanceCondition) => {
|
|
89
|
+
const base = condition ?? emptyCalldataMatches;
|
|
90
|
+
if (base.paramType !== ParameterType.Calldata || base.operator !== Operator.Matches) throw new Error("Global allowance can only be applied to calldata matches nodes");
|
|
91
|
+
return {
|
|
92
|
+
...base,
|
|
93
|
+
children: [...base.children ?? [], allowanceCondition]
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
const applyOptions = (permission, options) => {
|
|
97
|
+
let condition = permission.condition;
|
|
98
|
+
if (options.etherWithinAllowance) {
|
|
99
|
+
if (!options.send) throw new Error("`etherWithinAllowance` can only be used if `send` is allowed");
|
|
100
|
+
condition = applyGlobalAllowance(condition, {
|
|
101
|
+
paramType: ParameterType.None,
|
|
102
|
+
operator: Operator.EtherWithinAllowance,
|
|
103
|
+
compValue: options.etherWithinAllowance
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
if (options.callWithinAllowance) condition = applyGlobalAllowance(condition, {
|
|
107
|
+
paramType: ParameterType.None,
|
|
108
|
+
operator: Operator.CallWithinAllowance,
|
|
109
|
+
compValue: options.callWithinAllowance
|
|
110
|
+
});
|
|
111
|
+
return {
|
|
112
|
+
...permission,
|
|
113
|
+
send: options.send,
|
|
114
|
+
delegatecall: options.delegatecall,
|
|
115
|
+
condition
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
//#endregion
|
|
119
|
+
export { EVERYTHING as n, buildAllowKit as t };
|
|
120
|
+
|
|
121
|
+
//# sourceMappingURL=allow-CzPpzclq.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"allow-CzPpzclq.mjs","names":[],"sources":["../src/allow/types.ts","../src/allow/runtime.ts"],"sourcesContent":["import type { BigNumberish, BytesLike, ParamType } from 'ethers'\nimport type {\n Condition,\n FunctionPermission,\n TargetPermission,\n} from 'zodiac-roles-sdk'\n\nexport type Options = {\n send?: boolean\n delegatecall?: boolean\n etherWithinAllowance?: `0x${string}`\n callWithinAllowance?: `0x${string}`\n}\n\nexport type PrimitiveValue = BigNumberish | BytesLike | string | boolean\n\n// Signature matches `zodiac-roles-sdk` so values from `c.*` are assignable.\nexport type ConditionFunction<T = unknown> = (\n abiType: ParamType,\n _?: T\n) => Condition\n\ntype RequireAtLeastOne<T> = {\n [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>\n}[keyof T]\n\ntype ArrayElement<T extends readonly unknown[]> = T extends readonly (infer U)[]\n ? U\n : never\n\nexport type PrimitiveScoping<T extends PrimitiveValue> =\n | T\n | ConditionFunction<T>\n\nexport type ArrayScoping<T extends readonly any[]> =\n | readonly Scoping<ArrayElement<T>>[]\n | ConditionFunction<T>\n\nexport type StructScoping<T extends { [key: string]: any }> =\n | RequireAtLeastOne<{ [K in keyof T]?: Scoping<T[K]> }>\n | ConditionFunction<T>\n\nexport type Scoping<T> = T extends PrimitiveValue\n ? PrimitiveScoping<T>\n : T extends readonly any[]\n ? ArrayScoping<T>\n : T extends { [key: string]: any }\n ? StructScoping<T>\n : unknown\n\nexport type { FunctionPermission, TargetPermission }\n\nexport const EVERYTHING = Symbol.for('@zodiaceco/allow-kit/EVERYTHING')\nexport type EVERYTHING = typeof EVERYTHING\n","import { Interface, FunctionFragment, isError, type InterfaceAbi } from 'ethers'\nimport { c, coercePermission, ParameterType, Operator } from 'zodiac-roles-sdk'\nimport type {\n Condition,\n FunctionPermission,\n TargetPermission,\n} from 'zodiac-roles-sdk'\nimport { readAbi, walkContracts, type ContractNode } from './abi'\nimport { EVERYTHING, type Options } from './types'\n\nexport function buildAllowKit(\n abisDir: string,\n contractsConfig: Record<string, any>\n): Record<string, any> {\n const kit: Record<string, any> = {}\n for (const node of walkContracts(contractsConfig)) {\n const abi = readAbi(abisDir, node)\n if (!abi) {\n // Defer the error until the user touches this contract — otherwise an\n // ABI missing for one chain crashes all unrelated role definitions.\n attachAt(kit, [node.chain, ...node.segments], missingAbiProxy(node))\n continue\n }\n attachAt(\n kit,\n [node.chain, ...node.segments],\n makeAllowContract(node.address, abi as InterfaceAbi)\n )\n }\n return kit\n}\n\nfunction attachAt(root: Record<string, any>, segments: string[], value: any) {\n let cursor = root\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i]!\n if (!(seg in cursor)) cursor[seg] = {}\n cursor = cursor[seg]\n }\n cursor[segments[segments.length - 1]!] = value\n}\n\nfunction missingAbiProxy(node: ContractNode) {\n const explain = () => {\n throw new Error(\n `ABI missing for ${node.chain}.${node.segments.join('.')} ` +\n `(${node.address}). Run \\`zodiac pull-contracts\\` to fetch it, or ` +\n `paste the ABI JSON manually at <abisDir>/${node.chain}/${node.segments.join('/')}.json`\n )\n }\n return new Proxy(\n {},\n {\n get: explain,\n has: explain,\n }\n )\n}\n\nfunction makeAllowContract(\n address: `0x${string}`,\n abi: InterfaceAbi\n): Record<string | symbol, any> {\n const iface = Interface.from(abi)\n const lowerAddr = address.toLowerCase() as `0x${string}`\n\n const allowEverything = (options?: Options): TargetPermission => ({\n targetAddress: lowerAddr,\n send: options?.send,\n delegatecall: options?.delegatecall,\n })\n\n const has = (name: string) => {\n try {\n const fn = iface.getFunction(name)\n if (!fn) return false\n return fn.stateMutability !== 'view' && fn.stateMutability !== 'pure'\n } catch (error) {\n if (!isError(error as any, 'INVALID_ARGUMENT')) throw error\n return false\n }\n }\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n if (prop === EVERYTHING) return allowEverything\n if (typeof prop !== 'string') return undefined\n if (!has(prop)) return undefined\n const fn = iface.getFunction(prop)!\n return makeAllowFunction(fn, lowerAddr)\n },\n has: (_target, prop) => {\n if (prop === EVERYTHING) return true\n return typeof prop === 'string' && has(prop)\n },\n }\n )\n}\n\nfunction makeAllowFunction(\n fn: FunctionFragment,\n targetAddress: `0x${string}`\n): (...args: any[]) => FunctionPermission {\n const inputs = fn.inputs\n return (...args: any[]) => {\n const scopings = args.slice(0, inputs.length)\n const hasScopings = scopings.some((s) => s !== undefined && s !== null)\n const options: Options = args[inputs.length] ?? {}\n const condition = hasScopings\n ? c.calldataMatches(scopings, inputs)()\n : undefined\n const preset = {\n targetAddress,\n signature: fn.format('sighash'),\n condition,\n }\n return applyOptions(coercePermission(preset as any) as any, options)\n }\n}\n\nconst emptyCalldataMatches: Condition = {\n paramType: ParameterType.Calldata,\n operator: Operator.Matches,\n children: [],\n}\n\nconst applyGlobalAllowance = (\n condition: Condition | undefined,\n allowanceCondition: Condition\n): Condition => {\n const base = condition ?? emptyCalldataMatches\n if (\n base.paramType !== ParameterType.Calldata ||\n base.operator !== Operator.Matches\n ) {\n throw new Error(\n 'Global allowance can only be applied to calldata matches nodes'\n )\n }\n return {\n ...base,\n children: [...(base.children ?? []), allowanceCondition],\n }\n}\n\nconst applyOptions = (\n permission: FunctionPermission & { condition?: Condition },\n options: Options\n): FunctionPermission => {\n let condition = permission.condition\n if (options.etherWithinAllowance) {\n if (!options.send) {\n throw new Error(\n '`etherWithinAllowance` can only be used if `send` is allowed'\n )\n }\n condition = applyGlobalAllowance(condition, {\n paramType: ParameterType.None,\n operator: Operator.EtherWithinAllowance,\n compValue: options.etherWithinAllowance,\n })\n }\n if (options.callWithinAllowance) {\n condition = applyGlobalAllowance(condition, {\n paramType: ParameterType.None,\n operator: Operator.CallWithinAllowance,\n compValue: options.callWithinAllowance,\n })\n }\n return {\n ...permission,\n send: options.send,\n delegatecall: options.delegatecall,\n condition,\n }\n}\n"],"mappings":";;;;AAoDA,MAAa,aAAa,OAAO,IAAI,kCAAkC;;;AC1CvE,SAAgB,cACd,SACA,iBACqB;CACrB,MAAM,MAA2B,EAAE;AACnC,MAAK,MAAM,QAAQ,cAAc,gBAAgB,EAAE;EACjD,MAAM,MAAM,QAAQ,SAAS,KAAK;AAClC,MAAI,CAAC,KAAK;AAGR,YAAS,KAAK,CAAC,KAAK,OAAO,GAAG,KAAK,SAAS,EAAE,gBAAgB,KAAK,CAAC;AACpE;;AAEF,WACE,KACA,CAAC,KAAK,OAAO,GAAG,KAAK,SAAS,EAC9B,kBAAkB,KAAK,SAAS,IAAoB,CACrD;;AAEH,QAAO;;AAGT,SAAS,SAAS,MAA2B,UAAoB,OAAY;CAC3E,IAAI,SAAS;AACb,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,SAAS,GAAG,KAAK;EAC5C,MAAM,MAAM,SAAS;AACrB,MAAI,EAAE,OAAO,QAAS,QAAO,OAAO,EAAE;AACtC,WAAS,OAAO;;AAElB,QAAO,SAAS,SAAS,SAAS,MAAO;;AAG3C,SAAS,gBAAgB,MAAoB;CAC3C,MAAM,gBAAgB;AACpB,QAAM,IAAI,MACR,mBAAmB,KAAK,MAAM,GAAG,KAAK,SAAS,KAAK,IAAI,CAAC,IACnD,KAAK,QAAQ,4FAC2B,KAAK,MAAM,GAAG,KAAK,SAAS,KAAK,IAAI,CAAC,OACrF;;AAEH,QAAO,IAAI,MACT,EAAE,EACF;EACE,KAAK;EACL,KAAK;EACN,CACF;;AAGH,SAAS,kBACP,SACA,KAC8B;CAC9B,MAAM,QAAQ,UAAU,KAAK,IA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c,cAAc,YACjC,KAAK,aAAa,SAAS,QAE3B,OAAM,IAAI,MACR,iEACD;AAEH,QAAO;EACL,GAAG;EACH,UAAU,CAAC,GAAI,KAAK,YAAY,EAAE,EAAG,mBAAmB;EACzD;;AAGH,MAAM,gBACJ,YACA,YACuB;CACvB,IAAI,YAAY,WAAW;AAC3B,KAAI,QAAQ,sBAAsB;AAChC,MAAI,CAAC,QAAQ,KACX,OAAM,IAAI,MACR,+DACD;AAEH,cAAY,qBAAqB,WAAW;GAC1C,WAAW,cAAc;GACzB,UAAU,SAAS;GACnB,WAAW,QAAQ;GACpB,CAAC;;AAEJ,KAAI,QAAQ,oBACV,aAAY,qBAAqB,WAAW;EAC1C,WAAW,cAAc;EACzB,UAAU,SAAS;EACnB,WAAW,QAAQ;EACpB,CAAC;AAEJ,QAAO;EACL,GAAG;EACH,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB;EACD"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import assert from "assert";
|
|
4
|
+
//#region src/paths.ts
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the project's `.zodiac/` directory — the shared home for SDK
|
|
7
|
+
* codegen (`pull-org` emits the importable module here, `pull-contracts`
|
|
8
|
+
* writes `allow.d.ts` alongside it).
|
|
9
|
+
*
|
|
10
|
+
* Pass `rootDir` to anchor explicitly (CLI commands do this using the
|
|
11
|
+
* directory of the loaded `zodiac.config.ts`). Without a `rootDir`, walks
|
|
12
|
+
* up from `cwd` to the nearest `zodiac.config.{ts,js,mjs,cjs}` so runtime
|
|
13
|
+
* callers like `constellation()` work even when invoked from a subdirectory.
|
|
14
|
+
*/
|
|
15
|
+
function resolveZodiacDir(rootDir) {
|
|
16
|
+
return join(rootDir ?? findProjectRoot(), ".zodiac");
|
|
17
|
+
}
|
|
18
|
+
const CONFIG_FILENAMES = [
|
|
19
|
+
"zodiac.config.ts",
|
|
20
|
+
"zodiac.config.js",
|
|
21
|
+
"zodiac.config.mjs",
|
|
22
|
+
"zodiac.config.cjs"
|
|
23
|
+
];
|
|
24
|
+
function findProjectRoot() {
|
|
25
|
+
let dir = process.cwd();
|
|
26
|
+
while (dir !== dirname(dir)) {
|
|
27
|
+
if (CONFIG_FILENAMES.some((name) => existsSync(join(dir, name)))) return dir;
|
|
28
|
+
dir = dirname(dir);
|
|
29
|
+
}
|
|
30
|
+
return process.cwd();
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/api.ts
|
|
34
|
+
const DEFAULT_API_URL = "https://app.zodiac.eco/api/v1";
|
|
35
|
+
var ApiClient = class {
|
|
36
|
+
apiKey;
|
|
37
|
+
baseUrl;
|
|
38
|
+
_fetch;
|
|
39
|
+
headers;
|
|
40
|
+
constructor({ baseUrl = process.env.ZODIAC_API_URL ?? DEFAULT_API_URL, fetch: customFetch = fetch, headers = {}, apiKey = process.env.ZODIAC_API_KEY } = {}) {
|
|
41
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
42
|
+
this._fetch = customFetch;
|
|
43
|
+
this.headers = headers;
|
|
44
|
+
assert(apiKey, "No API key provided to the API client. Either pass it as the \"apiKey\" option or set the ZODIAC_API_KEY environment variable.");
|
|
45
|
+
this.apiKey = apiKey;
|
|
46
|
+
}
|
|
47
|
+
async postJson(endpoint, payload) {
|
|
48
|
+
const res = await this._fetch(`${this.baseUrl}/${endpoint}`, {
|
|
49
|
+
method: "POST",
|
|
50
|
+
headers: {
|
|
51
|
+
...this.headers,
|
|
52
|
+
"content-type": "application/json",
|
|
53
|
+
authorization: `Bearer ${this.apiKey}`
|
|
54
|
+
},
|
|
55
|
+
body: jsonStringify(payload)
|
|
56
|
+
});
|
|
57
|
+
if (!res.ok) await handleApiError(res);
|
|
58
|
+
return res.json();
|
|
59
|
+
}
|
|
60
|
+
async get(endpoint) {
|
|
61
|
+
const res = await this._fetch(`${this.baseUrl}/${endpoint}`, { headers: {
|
|
62
|
+
...this.headers,
|
|
63
|
+
authorization: `Bearer ${this.apiKey}`
|
|
64
|
+
} });
|
|
65
|
+
if (!res.ok) await handleApiError(res);
|
|
66
|
+
return res.json();
|
|
67
|
+
}
|
|
68
|
+
listAccounts() {
|
|
69
|
+
return this.get("accounts");
|
|
70
|
+
}
|
|
71
|
+
listUsers() {
|
|
72
|
+
return this.get("users");
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Applies an accounts specification to Zodiac OS.
|
|
76
|
+
*/
|
|
77
|
+
applyConstellation(workspaceId, payload) {
|
|
78
|
+
return this.postJson(`workspace/${workspaceId}/constellation/apply`, payload);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Resolves an accounts specification to Zodiac OS.
|
|
82
|
+
*/
|
|
83
|
+
resolveConstellation(workspaceId, payload) {
|
|
84
|
+
return this.postJson(`workspace/${workspaceId}/constellation/resolve`, payload);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
var ApiRequestError = class ApiRequestError extends Error {
|
|
88
|
+
status;
|
|
89
|
+
statusText;
|
|
90
|
+
details;
|
|
91
|
+
constructor(message, opts) {
|
|
92
|
+
super(ApiRequestError.composeMessage(message, opts.details));
|
|
93
|
+
this.name = "ApiRequestError";
|
|
94
|
+
this.status = opts.status;
|
|
95
|
+
this.statusText = opts.statusText;
|
|
96
|
+
this.details = opts.details;
|
|
97
|
+
if (opts.cause !== void 0) this.cause = opts.cause;
|
|
98
|
+
}
|
|
99
|
+
static composeMessage(message, details) {
|
|
100
|
+
if (details == null) return message;
|
|
101
|
+
let detailsString;
|
|
102
|
+
try {
|
|
103
|
+
detailsString = typeof details === "string" ? details : jsonStringify(details, 2);
|
|
104
|
+
} catch (_err) {
|
|
105
|
+
detailsString = String(details);
|
|
106
|
+
}
|
|
107
|
+
return `${message}\nDetails: ${detailsString}`;
|
|
108
|
+
}
|
|
109
|
+
toString() {
|
|
110
|
+
return `${this.name}: ${this.message}`;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
async function handleApiError(response) {
|
|
114
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
115
|
+
const errorData = await response.json();
|
|
116
|
+
let error;
|
|
117
|
+
try {
|
|
118
|
+
error = new ApiRequestError(errorData.error.message, {
|
|
119
|
+
status: response.status,
|
|
120
|
+
statusText: response.statusText,
|
|
121
|
+
details: errorData.error.details
|
|
122
|
+
});
|
|
123
|
+
} catch (jsonShapeError) {
|
|
124
|
+
error = new ApiRequestError(`Failed parsing error response: ${jsonShapeError}`, {
|
|
125
|
+
status: response.status,
|
|
126
|
+
statusText: response.statusText,
|
|
127
|
+
details: errorData
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
throw error;
|
|
131
|
+
} else throw new ApiRequestError(`${response.status} ${response.statusText}: ${response.url}`, {
|
|
132
|
+
status: response.status,
|
|
133
|
+
statusText: response.statusText
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** JSON.stringify with bigint support */
|
|
137
|
+
const jsonStringify = (value, indent) => JSON.stringify(value, (_, value) => {
|
|
138
|
+
if (typeof value === "bigint") return value.toString();
|
|
139
|
+
return value;
|
|
140
|
+
}, indent);
|
|
141
|
+
//#endregion
|
|
142
|
+
export { resolveZodiacDir as n, ApiClient as t };
|
|
143
|
+
|
|
144
|
+
//# sourceMappingURL=api-C49DoaPC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-C49DoaPC.mjs","names":[],"sources":["../src/paths.ts","../src/api.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/**\n * Resolve the project's `.zodiac/` directory — the shared home for SDK\n * codegen (`pull-org` emits the importable module here, `pull-contracts`\n * writes `allow.d.ts` alongside it).\n *\n * Pass `rootDir` to anchor explicitly (CLI commands do this using the\n * directory of the loaded `zodiac.config.ts`). Without a `rootDir`, walks\n * up from `cwd` to the nearest `zodiac.config.{ts,js,mjs,cjs}` so runtime\n * callers like `constellation()` work even when invoked from a subdirectory.\n */\nexport function resolveZodiacDir(rootDir?: string): string {\n return join(rootDir ?? findProjectRoot(), '.zodiac')\n}\n\nconst CONFIG_FILENAMES = [\n 'zodiac.config.ts',\n 'zodiac.config.js',\n 'zodiac.config.mjs',\n 'zodiac.config.cjs',\n]\n\nfunction findProjectRoot(): string {\n let dir = process.cwd()\n while (dir !== dirname(dir)) {\n if (CONFIG_FILENAMES.some((name) => existsSync(join(dir, name)))) return dir\n dir = dirname(dir)\n }\n return process.cwd()\n}\n","import type {\n ApplyConstellationPayload,\n ApplyConstellationResult,\n ResolveConstellationPayload,\n ResolveConstellationResult,\n ApiError as ApiErrorResponse,\n ListAccountsResult,\n ListUsersResult,\n} from '@zodiaceco/api-types'\nimport assert from 'assert'\nimport { UUID } from 'crypto'\n\nexport type Options = {\n workspace?: string\n apiKey?: string\n baseUrl?: string\n fetch?: typeof globalThis.fetch\n headers?: Record<string, string>\n}\n\nconst DEFAULT_API_URL = 'https://app.zodiac.eco/api/v1'\n\nexport class ApiClient {\n private apiKey: string\n private baseUrl: string\n private _fetch: typeof fetch\n private headers: Record<string, string>\n\n constructor({\n // Read `ZODIAC_API_URL`/`ZODIAC_API_KEY` lazily at construction time\n // rather than at module load: the CLI loads `.env` (and `init` writes a\n // fresh one) before the first client is created, so capturing them at\n // import time would bake in the default and ignore the user's config.\n baseUrl = process.env.ZODIAC_API_URL ?? DEFAULT_API_URL,\n fetch: customFetch = fetch,\n headers = {},\n apiKey = process.env.ZODIAC_API_KEY,\n }: Options = {}) {\n this.baseUrl = baseUrl.replace(/\\/$/, '')\n this._fetch = customFetch\n this.headers = headers\n\n assert(\n apiKey,\n 'No API key provided to the API client. Either pass it as the \"apiKey\" option or set the ZODIAC_API_KEY environment variable.'\n )\n\n this.apiKey = apiKey\n }\n\n protected async postJson(endpoint: string, payload: unknown) {\n const res = await this._fetch(`${this.baseUrl}/${endpoint}`, {\n method: 'POST',\n headers: {\n ...this.headers,\n 'content-type': 'application/json',\n authorization: `Bearer ${this.apiKey}`,\n },\n body: jsonStringify(payload),\n })\n if (!res.ok) {\n await handleApiError(res)\n }\n\n return res.json()\n }\n\n protected async get(endpoint: string) {\n const res = await this._fetch(`${this.baseUrl}/${endpoint}`, {\n headers: { ...this.headers, authorization: `Bearer ${this.apiKey}` },\n })\n\n if (!res.ok) {\n await handleApiError(res)\n }\n\n return res.json()\n }\n\n listAccounts(): Promise<ListAccountsResult> {\n return this.get('accounts')\n }\n\n listUsers(): Promise<ListUsersResult> {\n return this.get('users')\n }\n\n /**\n * Applies an accounts specification to Zodiac OS.\n */\n applyConstellation(\n workspaceId: UUID,\n payload: ApplyConstellationPayload\n ): Promise<ApplyConstellationResult> {\n return this.postJson(\n `workspace/${workspaceId}/constellation/apply`,\n payload\n )\n }\n\n /**\n * Resolves an accounts specification to Zodiac OS.\n */\n resolveConstellation(\n workspaceId: UUID,\n payload: ResolveConstellationPayload\n ): Promise<ResolveConstellationResult> {\n return this.postJson(\n `workspace/${workspaceId}/constellation/resolve`,\n payload\n )\n }\n}\n\nexport class ApiRequestError extends Error {\n public readonly status: number\n public readonly statusText: string\n public readonly details?: unknown\n\n constructor(\n message: string,\n opts: {\n status: number\n statusText: string\n details?: unknown\n cause?: unknown\n }\n ) {\n super(ApiRequestError.composeMessage(message, opts.details))\n this.name = 'ApiRequestError'\n this.status = opts.status\n this.statusText = opts.statusText\n this.details = opts.details\n if (opts.cause !== undefined) {\n ;(this as any).cause = opts.cause\n }\n }\n\n private static composeMessage(message: string, details?: unknown) {\n if (details == null) return message\n let detailsString: string\n try {\n detailsString =\n typeof details === 'string' ? details : jsonStringify(details, 2)\n } catch (_err) {\n detailsString = String(details)\n }\n return `${message}\\nDetails: ${detailsString}`\n }\n\n toString() {\n return `${this.name}: ${this.message}`\n }\n}\n\nasync function handleApiError(response: Response): Promise<never> {\n const contentType = response.headers.get('content-type')\n if (contentType?.includes('application/json')) {\n const errorData = (await response.json()) as ApiErrorResponse\n let error: ApiRequestError\n try {\n error = new ApiRequestError(errorData.error.message, {\n status: response.status,\n statusText: response.statusText,\n details: errorData.error.details,\n })\n } catch (jsonShapeError) {\n error = new ApiRequestError(\n `Failed parsing error response: ${jsonShapeError}`,\n {\n status: response.status,\n statusText: response.statusText,\n details: errorData,\n }\n )\n }\n throw error\n } else {\n throw new ApiRequestError(\n `${response.status} ${response.statusText}: ${response.url}`,\n {\n status: response.status,\n statusText: response.statusText,\n }\n )\n }\n}\n\n/** JSON.stringify with bigint support */\nconst jsonStringify = (value: unknown, indent?: number) =>\n JSON.stringify(\n value,\n (_, value) => {\n if (typeof value === 'bigint') {\n return value.toString()\n }\n\n return value\n },\n indent\n )\n"],"mappings":";;;;;;;;;;;;;;AAaA,SAAgB,iBAAiB,SAA0B;AACzD,QAAO,KAAK,WAAW,iBAAiB,EAAE,UAAU;;AAGtD,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACD;AAED,SAAS,kBAA0B;CACjC,IAAI,MAAM,QAAQ,KAAK;AACvB,QAAO,QAAQ,QAAQ,IAAI,EAAE;AAC3B,MAAI,iBAAiB,MAAM,SAAS,WAAW,KAAK,KAAK,KAAK,CAAC,CAAC,CAAE,QAAO;AACzE,QAAM,QAAQ,IAAI;;AAEpB,QAAO,QAAQ,KAAK;;;;ACVtB,MAAM,kBAAkB;AAExB,IAAa,YAAb,MAAuB;CACrB;CACA;CACA;CACA;CAEA,YAAY,EAKV,UAAU,QAAQ,IAAI,kBAAkB,iBACxC,OAAO,cAAc,OACrB,UAAU,EAAE,EACZ,SAAS,QAAQ,IAAI,mBACV,EAAE,EAAE;AACf,OAAK,UAAU,QAAQ,QAAQ,OAAO,GAAG;AACzC,OAAK,SAAS;AACd,OAAK,UAAU;AAEf,SACE,QACA,iIACD;AAED,OAAK,SAAS;;CAGhB,MAAgB,SAAS,UAAkB,SAAkB;EAC3D,MAAM,MAAM,MAAM,KAAK,OAAO,GAAG,KAAK,QAAQ,GAAG,YAAY;GA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