square-sdk-cli 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +52 -9
- package/dist/square.js +448 -120
- package/package.json +8 -8
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may break).
|
|
6
|
+
|
|
7
|
+
## [0.2.0] - 2026-10-12
|
|
8
|
+
|
|
9
|
+
### ⚠️ Behavior changes (check scripts that use the CLI)
|
|
10
|
+
|
|
11
|
+
- **Write calls against production now need confirmation.** In a terminal you
|
|
12
|
+
are asked `Continue? [y/N]`; without a terminal (scripts, CI) the call is
|
|
13
|
+
refused unless you pass `--yes`. Reads (`get*`, `list*`, `search*`, …),
|
|
14
|
+
`--dry-run` and sandbox calls are unaffected.
|
|
15
|
+
- **`--stream` prints NDJSON**: one compact JSON object per line, instead of
|
|
16
|
+
pretty-printed multi-line objects.
|
|
17
|
+
- **Invalid environments are errors.** `--env`, `SQUARE_ENVIRONMENT` and
|
|
18
|
+
`config set --env` accept only `sandbox` or `production`; a typo like `prod`
|
|
19
|
+
used to fall back to sandbox silently.
|
|
20
|
+
- **Write calls get an automatic `idempotencyKey`** when none is given. The key
|
|
21
|
+
is printed to stderr; pass it back with `--idempotencyKey` to retry safely.
|
|
22
|
+
- **Unknown namespaces and methods exit 1** (e.g. `square bogus` used to print
|
|
23
|
+
help and exit 0).
|
|
24
|
+
- **`--json` must be a JSON object**; arrays and scalars are rejected.
|
|
25
|
+
- **The config file is validated on load**; a malformed profile now fails with
|
|
26
|
+
a message naming the file and the problem.
|
|
27
|
+
- **Field paths containing `__proto__`, `constructor` or `prototype` are rejected.**
|
|
28
|
+
|
|
29
|
+
### Added
|
|
30
|
+
|
|
31
|
+
- `--dry-run`: print the environment, method and request without sending it.
|
|
32
|
+
- `--json @file.json` and `--json -` read the request body from a file or stdin.
|
|
33
|
+
- `--field:str value` keeps a value as a string instead of JSON-coercing it
|
|
34
|
+
(e.g. `--address.postalCode:str 94103`).
|
|
35
|
+
- `--max-items <n>` and `--max-pages <n>` cap paging.
|
|
36
|
+
- `--yes` skips the production write confirmation.
|
|
37
|
+
- `config set` without `--token` prompts for the token with hidden input, and
|
|
38
|
+
`--token -` reads it from stdin, keeping tokens out of shell history.
|
|
39
|
+
- `config remove <profile>`.
|
|
40
|
+
- `config list` marks the default profile and shows each profile's environment.
|
|
41
|
+
- `square whoami`: shows the merchant, environment and token source in use.
|
|
42
|
+
- Help for namespaces (including nested ones like `square terminal actions`)
|
|
43
|
+
works without credentials.
|
|
44
|
+
- CI on GitHub Actions (typecheck, tests, build, node 18/20/22 smoke tests) and
|
|
45
|
+
a weekly run against the latest `square` SDK release.
|
|
46
|
+
- `bun run typecheck` script; `prepublishOnly` now runs it.
|
|
47
|
+
|
|
48
|
+
### Fixed
|
|
49
|
+
|
|
50
|
+
- `--json-output` had no effect; it now prints compact JSON.
|
|
51
|
+
- `square <namespace>` without credentials failed with "No authentication found"
|
|
52
|
+
instead of showing help.
|
|
53
|
+
|
|
54
|
+
### Changed
|
|
55
|
+
|
|
56
|
+
- `typescript` moved from `peerDependencies` to `devDependencies`, so installing
|
|
57
|
+
the CLI no longer warns about a missing peer.
|
|
58
|
+
- `@types/bun` pinned to `^1.4.3` instead of `latest`.
|
|
59
|
+
|
|
60
|
+
## [0.1.2] - 2026-06-21
|
|
61
|
+
|
|
62
|
+
### Changed
|
|
63
|
+
|
|
64
|
+
- Square API errors are shown in readable form (HTTP status, detail, field and
|
|
65
|
+
code) with actionable hints for common problems.
|
|
66
|
+
|
|
67
|
+
### Fixed
|
|
68
|
+
|
|
69
|
+
- README `list` examples now include the sort flags those endpoints require.
|
|
70
|
+
|
|
71
|
+
## [0.1.1] - 2026-06-19
|
|
72
|
+
|
|
73
|
+
### Added
|
|
74
|
+
|
|
75
|
+
- MIT `LICENSE` file.
|
|
76
|
+
- npm keywords for discoverability.
|
|
77
|
+
|
|
78
|
+
## [0.1.0] - 2026-06-19
|
|
79
|
+
|
|
80
|
+
### Added
|
|
81
|
+
|
|
82
|
+
- Initial release: every Square SDK namespace and method exposed by runtime
|
|
83
|
+
introspection, profile-based config, `--json` and `--field.path` request
|
|
84
|
+
building, automatic paging and `--stream`.
|
|
85
|
+
|
|
86
|
+
[0.2.0]: https://github.com/karthikdilliraj/square-sdk-cli/compare/v0.1.2...v0.2.0
|
|
87
|
+
[0.1.2]: https://github.com/karthikdilliraj/square-sdk-cli/compare/v0.1.1...v0.1.2
|
|
88
|
+
[0.1.1]: https://github.com/karthikdilliraj/square-sdk-cli/compare/45f2670...v0.1.1
|
|
89
|
+
[0.1.0]: https://github.com/karthikdilliraj/square-sdk-cli/tree/45f2670
|
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# square-sdk-cli
|
|
2
2
|
|
|
3
|
+
[](https://github.com/karthikdilliraj/square-sdk-cli/actions/workflows/ci.yml)
|
|
4
|
+
|
|
3
5
|
A command-line interface for the [Square API](https://developer.squareup.com/),
|
|
4
6
|
built with [Bun](https://bun.com). It exposes **every** Square SDK namespace and
|
|
5
7
|
method dynamically by introspecting the SDK at runtime — no hardcoded API list.
|
|
@@ -32,13 +34,19 @@ Credentials are stored on your machine at
|
|
|
32
34
|
Tokens are written with `0600` permissions and masked when read back.
|
|
33
35
|
|
|
34
36
|
```bash
|
|
35
|
-
square config set sandbox --
|
|
36
|
-
square config set prod
|
|
37
|
+
square config set sandbox --env sandbox # prompts for the token (hidden)
|
|
38
|
+
square config set prod --env production # same
|
|
39
|
+
pbpaste | square config set prod --token - --env production # token from stdin
|
|
37
40
|
square config use sandbox # set default profile
|
|
38
|
-
square config list
|
|
41
|
+
square config list # * marks the default; shows each environment
|
|
39
42
|
square config get sandbox # token shown masked
|
|
43
|
+
square config remove sandbox # delete a profile (clears the default if it was)
|
|
44
|
+
square whoami # check the token: merchant, environment, token source
|
|
40
45
|
```
|
|
41
46
|
|
|
47
|
+
Omitting `--token` (or passing `--token -`) keeps the token out of your shell
|
|
48
|
+
history. `--token <ACCESS_TOKEN>` inline still works.
|
|
49
|
+
|
|
42
50
|
Auth resolution order: `--profile <name>` → `--token` / `SQUARE_ACCESS_TOKEN`
|
|
43
51
|
env → default profile.
|
|
44
52
|
|
|
@@ -55,16 +63,33 @@ square payments --help
|
|
|
55
63
|
square terminal actions create --help
|
|
56
64
|
|
|
57
65
|
# Call methods
|
|
58
|
-
square
|
|
66
|
+
square locations list
|
|
67
|
+
square catalog list
|
|
68
|
+
square payments list --sortField CREATED_AT
|
|
69
|
+
square customers list --sortField DEFAULT --sortOrder ASC
|
|
59
70
|
square payments create --json '{"sourceId":"...","idempotencyKey":"..."}' --amountMoney.amount 100 --amountMoney.currency USD
|
|
60
|
-
square customers list --stream
|
|
71
|
+
square customers list --sortField DEFAULT --sortOrder ASC --stream
|
|
61
72
|
```
|
|
62
73
|
|
|
74
|
+
> Note: some `list` endpoints (e.g. `payments`, `customers`) require explicit
|
|
75
|
+
> sort flags — the Square SDK serializes a missing sort field as an empty string
|
|
76
|
+
> and the API rejects it with `INVALID_ENUM_VALUE ... sort_field`. Pass
|
|
77
|
+
> `--sortField` (and `--sortOrder` for `customers`) as shown above. Endpoints
|
|
78
|
+
> like `locations` and `catalog` need no arguments.
|
|
79
|
+
|
|
63
80
|
### Request body
|
|
64
81
|
|
|
65
|
-
- `--json '<json>'` — full request body as JSON
|
|
82
|
+
- `--json '<json>'` — full request body as a JSON object; `--json @body.json`
|
|
83
|
+
reads it from a file, `--json -` reads it from stdin
|
|
66
84
|
- `--field.path value` — set a field by dotted path (merged over `--json`;
|
|
67
85
|
numeric path segments create arrays; values are JSON-coerced, falling back to string)
|
|
86
|
+
- `--field.path:str value` — same, but the value is always kept as a string
|
|
87
|
+
(e.g. `--address.postalCode:str 94103`, which would otherwise become a number)
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
square payments create --json @payment.json --dry-run # preview, nothing sent
|
|
91
|
+
cat payment.json | square payments create --json -
|
|
92
|
+
```
|
|
68
93
|
|
|
69
94
|
### Flags
|
|
70
95
|
|
|
@@ -72,12 +97,29 @@ square customers list --stream
|
|
|
72
97
|
| --------------- | ------------------------------------------- |
|
|
73
98
|
| `--profile <n>` | use a named profile from config |
|
|
74
99
|
| `--token <t>` | Square API access token |
|
|
75
|
-
| `--env <e>` | `sandbox` or `production` (default sandbox) |
|
|
76
|
-
| `--json '<j>'` | JSON request body
|
|
100
|
+
| `--env <e>` | `sandbox` or `production` (default sandbox; anything else is an error) |
|
|
101
|
+
| `--json '<j>'` | JSON request body (`@file` or `-` for stdin) |
|
|
77
102
|
| `--json-output` | compact JSON output (no pretty print) |
|
|
78
|
-
| `--stream` | stream pageable results
|
|
103
|
+
| `--stream` | stream pageable results as NDJSON |
|
|
104
|
+
| `--dry-run` | print the request without sending it |
|
|
105
|
+
| `--max-items <n>` | stop paging after n items |
|
|
106
|
+
| `--max-pages <n>` | stop paging after n pages |
|
|
107
|
+
| `--yes` | skip the production write confirmation |
|
|
79
108
|
| `--help` | show help |
|
|
80
109
|
|
|
110
|
+
### Safety defaults
|
|
111
|
+
|
|
112
|
+
- **Production writes ask first.** Any call against `production` whose method
|
|
113
|
+
isn't a read (`get*`, `list*`, `search*`, `retrieve*`, `batchGet*`, …) asks
|
|
114
|
+
`Continue? [y/N]`. In scripts or CI (no terminal), it refuses unless you pass
|
|
115
|
+
`--yes`. `--dry-run` never prompts.
|
|
116
|
+
- **Automatic idempotency keys.** Write calls without an `idempotencyKey` get a
|
|
117
|
+
random one, printed to stderr. To retry safely, pass it back with
|
|
118
|
+
`--idempotencyKey <key>`. Endpoints that don't use a key ignore it.
|
|
119
|
+
- **Paging limits.** `list` calls fetch every page by default. Cap them with
|
|
120
|
+
`--max-items` or `--max-pages`. (`--limit` is still the API's own page-size
|
|
121
|
+
field.)
|
|
122
|
+
|
|
81
123
|
> Per-field help is structural only — the SDK's field schemas live in its
|
|
82
124
|
> `.d.ts` types and aren't available at runtime. Use `--json` for full bodies.
|
|
83
125
|
|
|
@@ -85,6 +127,7 @@ square customers list --stream
|
|
|
85
127
|
|
|
86
128
|
```bash
|
|
87
129
|
bun test # full suite (incl. SDK contract guard test)
|
|
130
|
+
bun run typecheck # tsc --noEmit
|
|
88
131
|
bun bin/square.ts <namespace> <method>
|
|
89
132
|
```
|
|
90
133
|
|
package/dist/square.js
CHANGED
|
@@ -6,11 +6,15 @@ var STRING_FLAGS = {
|
|
|
6
6
|
profile: "profile",
|
|
7
7
|
token: "token",
|
|
8
8
|
env: "env",
|
|
9
|
-
json: "json"
|
|
9
|
+
json: "json",
|
|
10
|
+
"max-items": "maxItems",
|
|
11
|
+
"max-pages": "maxPages"
|
|
10
12
|
};
|
|
11
13
|
var BOOL_FLAGS = {
|
|
12
14
|
"json-output": "jsonOutput",
|
|
13
15
|
stream: "stream",
|
|
16
|
+
"dry-run": "dryRun",
|
|
17
|
+
yes: "yes",
|
|
14
18
|
help: "help"
|
|
15
19
|
};
|
|
16
20
|
function parseArgs(argv) {
|
|
@@ -83,6 +87,9 @@ function handleFlag(key, val, flags) {
|
|
|
83
87
|
}
|
|
84
88
|
|
|
85
89
|
// src/merge.ts
|
|
90
|
+
import * as fs from "fs";
|
|
91
|
+
import { randomUUID } from "crypto";
|
|
92
|
+
var STRING_SUFFIX = ":str";
|
|
86
93
|
function coerce(value) {
|
|
87
94
|
try {
|
|
88
95
|
return JSON.parse(value);
|
|
@@ -90,8 +97,14 @@ function coerce(value) {
|
|
|
90
97
|
return value;
|
|
91
98
|
}
|
|
92
99
|
}
|
|
100
|
+
var FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
|
|
93
101
|
function deepSet(obj, path, value) {
|
|
94
102
|
const segments = path.split(".");
|
|
103
|
+
for (const seg of segments) {
|
|
104
|
+
if (FORBIDDEN_SEGMENTS.has(seg)) {
|
|
105
|
+
throw new Error(`Invalid field path "${path}": "${seg}" is not allowed`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
95
108
|
let current = obj;
|
|
96
109
|
for (let i = 0;i < segments.length - 1; i++) {
|
|
97
110
|
const seg = segments[i];
|
|
@@ -108,27 +121,54 @@ function deepSet(obj, path, value) {
|
|
|
108
121
|
function buildRequest(jsonStr, fields) {
|
|
109
122
|
let base = {};
|
|
110
123
|
if (jsonStr !== undefined) {
|
|
124
|
+
let parsed;
|
|
111
125
|
try {
|
|
112
|
-
|
|
113
|
-
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
114
|
-
base = parsed;
|
|
115
|
-
} else {
|
|
116
|
-
base = parsed;
|
|
117
|
-
}
|
|
126
|
+
parsed = JSON.parse(jsonStr);
|
|
118
127
|
} catch (e) {
|
|
119
128
|
const msg = e instanceof Error ? e.message : String(e);
|
|
120
129
|
throw new Error(`Invalid JSON: ${msg}`);
|
|
121
130
|
}
|
|
131
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
132
|
+
throw new Error("Invalid JSON: request body must be a JSON object");
|
|
133
|
+
}
|
|
134
|
+
base = parsed;
|
|
122
135
|
}
|
|
123
136
|
for (const field of fields) {
|
|
124
|
-
|
|
125
|
-
|
|
137
|
+
if (field.path.endsWith(STRING_SUFFIX)) {
|
|
138
|
+
deepSet(base, field.path.slice(0, -STRING_SUFFIX.length), field.value);
|
|
139
|
+
} else {
|
|
140
|
+
deepSet(base, field.path, coerce(field.value));
|
|
141
|
+
}
|
|
126
142
|
}
|
|
127
143
|
return base;
|
|
128
144
|
}
|
|
145
|
+
function readJsonArg(raw, readFile = (source) => fs.readFileSync(source, "utf8")) {
|
|
146
|
+
if (raw === "-")
|
|
147
|
+
return readFile(0);
|
|
148
|
+
if (raw.startsWith("@")) {
|
|
149
|
+
const file = raw.slice(1);
|
|
150
|
+
try {
|
|
151
|
+
return readFile(file);
|
|
152
|
+
} catch (e) {
|
|
153
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
154
|
+
throw new Error(`Cannot read --json file "${file}": ${msg}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return raw;
|
|
158
|
+
}
|
|
159
|
+
function ensureIdempotencyKey(request, methodName, newKey = randomUUID) {
|
|
160
|
+
if (/IdempotencyKey/.test(methodName))
|
|
161
|
+
return;
|
|
162
|
+
const body = request;
|
|
163
|
+
if (body["idempotencyKey"] !== undefined)
|
|
164
|
+
return;
|
|
165
|
+
const key = newKey();
|
|
166
|
+
body["idempotencyKey"] = key;
|
|
167
|
+
return key;
|
|
168
|
+
}
|
|
129
169
|
|
|
130
170
|
// src/config.ts
|
|
131
|
-
import * as
|
|
171
|
+
import * as fs2 from "fs";
|
|
132
172
|
import * as path from "path";
|
|
133
173
|
import * as os from "os";
|
|
134
174
|
function getConfigPath() {
|
|
@@ -141,24 +181,55 @@ function getConfigPath() {
|
|
|
141
181
|
}
|
|
142
182
|
async function load() {
|
|
143
183
|
const configPath = getConfigPath();
|
|
144
|
-
if (!
|
|
184
|
+
if (!fs2.existsSync(configPath)) {
|
|
145
185
|
return { profiles: {} };
|
|
146
186
|
}
|
|
147
|
-
const raw =
|
|
187
|
+
const raw = fs2.readFileSync(configPath, "utf8");
|
|
188
|
+
let parsed;
|
|
148
189
|
try {
|
|
149
|
-
|
|
150
|
-
return parsed;
|
|
190
|
+
parsed = JSON.parse(raw);
|
|
151
191
|
} catch (e) {
|
|
152
192
|
const msg = e instanceof Error ? e.message : String(e);
|
|
153
193
|
throw new Error(`Failed to parse config at ${configPath}: ${msg}`);
|
|
154
194
|
}
|
|
195
|
+
return validateConfig(parsed, configPath);
|
|
196
|
+
}
|
|
197
|
+
function isObject(value) {
|
|
198
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
199
|
+
}
|
|
200
|
+
function validateConfig(parsed, configPath) {
|
|
201
|
+
const fail = (problem) => {
|
|
202
|
+
throw new Error(`Invalid config at ${configPath}: ${problem}`);
|
|
203
|
+
};
|
|
204
|
+
if (!isObject(parsed))
|
|
205
|
+
fail("expected a JSON object");
|
|
206
|
+
const cfg = parsed;
|
|
207
|
+
const profiles = cfg["profiles"] ?? {};
|
|
208
|
+
if (!isObject(profiles))
|
|
209
|
+
fail(`"profiles" must be an object`);
|
|
210
|
+
for (const [name, profile] of Object.entries(profiles)) {
|
|
211
|
+
if (!isObject(profile))
|
|
212
|
+
fail(`profile "${name}" must be an object`);
|
|
213
|
+
const p = profile;
|
|
214
|
+
if (typeof p["token"] !== "string" || p["token"] === "") {
|
|
215
|
+
fail(`profile "${name}" is missing a "token"`);
|
|
216
|
+
}
|
|
217
|
+
if (p["environment"] !== "sandbox" && p["environment"] !== "production") {
|
|
218
|
+
fail(`profile "${name}" has environment ${JSON.stringify(p["environment"])}; expected "sandbox" or "production"`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const defaultProfile = cfg["defaultProfile"];
|
|
222
|
+
if (defaultProfile !== undefined && typeof defaultProfile !== "string") {
|
|
223
|
+
fail(`"defaultProfile" must be a string`);
|
|
224
|
+
}
|
|
225
|
+
return { ...cfg, profiles };
|
|
155
226
|
}
|
|
156
227
|
async function save(cfg) {
|
|
157
228
|
const configPath = getConfigPath();
|
|
158
229
|
const dir = path.dirname(configPath);
|
|
159
|
-
|
|
230
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
160
231
|
const content = JSON.stringify(cfg, null, 2);
|
|
161
|
-
|
|
232
|
+
fs2.writeFileSync(configPath, content, { mode: 384 });
|
|
162
233
|
}
|
|
163
234
|
async function setProfile(name, partial) {
|
|
164
235
|
const cfg = await load();
|
|
@@ -170,10 +241,6 @@ async function getProfile(name) {
|
|
|
170
241
|
const cfg = await load();
|
|
171
242
|
return cfg.profiles[name];
|
|
172
243
|
}
|
|
173
|
-
async function listProfiles() {
|
|
174
|
-
const cfg = await load();
|
|
175
|
-
return Object.keys(cfg.profiles);
|
|
176
|
-
}
|
|
177
244
|
async function useProfile(name) {
|
|
178
245
|
const cfg = await load();
|
|
179
246
|
if (!cfg.profiles[name]) {
|
|
@@ -182,15 +249,31 @@ async function useProfile(name) {
|
|
|
182
249
|
cfg.defaultProfile = name;
|
|
183
250
|
await save(cfg);
|
|
184
251
|
}
|
|
252
|
+
async function removeProfile(name) {
|
|
253
|
+
const cfg = await load();
|
|
254
|
+
if (!cfg.profiles[name]) {
|
|
255
|
+
throw new Error(`Profile "${name}" does not exist.`);
|
|
256
|
+
}
|
|
257
|
+
delete cfg.profiles[name];
|
|
258
|
+
const wasDefault = cfg.defaultProfile === name;
|
|
259
|
+
if (wasDefault)
|
|
260
|
+
delete cfg.defaultProfile;
|
|
261
|
+
await save(cfg);
|
|
262
|
+
return wasDefault;
|
|
263
|
+
}
|
|
185
264
|
|
|
186
265
|
// src/auth.ts
|
|
266
|
+
function parseEnvironment(value, source) {
|
|
267
|
+
if (value === "sandbox" || value === "production")
|
|
268
|
+
return value;
|
|
269
|
+
throw new Error(`Invalid ${source} "${value}". Expected "sandbox" or "production".`);
|
|
270
|
+
}
|
|
187
271
|
function resolveEnvironment(flags, env) {
|
|
188
|
-
if (flags.env)
|
|
189
|
-
return flags.env
|
|
190
|
-
}
|
|
272
|
+
if (flags.env !== undefined)
|
|
273
|
+
return parseEnvironment(String(flags.env), "--env");
|
|
191
274
|
const envVal = env["SQUARE_ENVIRONMENT"];
|
|
192
|
-
if (envVal
|
|
193
|
-
return "
|
|
275
|
+
if (envVal)
|
|
276
|
+
return parseEnvironment(envVal, "SQUARE_ENVIRONMENT");
|
|
194
277
|
return "sandbox";
|
|
195
278
|
}
|
|
196
279
|
function resolveAuth(flags, env, config) {
|
|
@@ -199,17 +282,21 @@ function resolveAuth(flags, env, config) {
|
|
|
199
282
|
if (!profile) {
|
|
200
283
|
throw new Error(`Profile "${flags.profile}" not found. Available profiles: ${Object.keys(config.profiles).join(", ") || "(none)"}`);
|
|
201
284
|
}
|
|
202
|
-
return { token: profile.token, environment: profile.environment };
|
|
285
|
+
return { token: profile.token, environment: profile.environment, source: `profile "${flags.profile}"` };
|
|
203
286
|
}
|
|
204
287
|
const token = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
|
|
205
288
|
if (token) {
|
|
206
289
|
const environment = resolveEnvironment(flags, env);
|
|
207
|
-
return { token, environment };
|
|
290
|
+
return { token, environment, source: flags.token ? "--token" : "SQUARE_ACCESS_TOKEN" };
|
|
208
291
|
}
|
|
209
292
|
if (config.defaultProfile) {
|
|
210
293
|
const profile = config.profiles[config.defaultProfile];
|
|
211
294
|
if (profile) {
|
|
212
|
-
return {
|
|
295
|
+
return {
|
|
296
|
+
token: profile.token,
|
|
297
|
+
environment: profile.environment,
|
|
298
|
+
source: `default profile "${config.defaultProfile}"`
|
|
299
|
+
};
|
|
213
300
|
}
|
|
214
301
|
}
|
|
215
302
|
throw new Error("No authentication found. Provide --token, set SQUARE_ACCESS_TOKEN, use --profile, or configure a default profile with `square config use <profile>`.");
|
|
@@ -278,6 +365,16 @@ function buildTree(client) {
|
|
|
278
365
|
const seen = new WeakSet;
|
|
279
366
|
return buildNode("root", client, seen, 0);
|
|
280
367
|
}
|
|
368
|
+
function findNamespace(tree, segments) {
|
|
369
|
+
let current = tree;
|
|
370
|
+
for (const seg of segments) {
|
|
371
|
+
const child = current.children.get(seg);
|
|
372
|
+
if (!child)
|
|
373
|
+
return;
|
|
374
|
+
current = child;
|
|
375
|
+
}
|
|
376
|
+
return current;
|
|
377
|
+
}
|
|
281
378
|
function resolvePath(tree, segments) {
|
|
282
379
|
if (segments.length === 0) {
|
|
283
380
|
const validTokens = [
|
|
@@ -306,6 +403,12 @@ function resolvePath(tree, segments) {
|
|
|
306
403
|
...current.methods.keys(),
|
|
307
404
|
...current.children.keys()
|
|
308
405
|
];
|
|
406
|
+
if (current === tree) {
|
|
407
|
+
return {
|
|
408
|
+
error: `Unknown namespace "${methodName}". Valid options: ${validTokens.join(", ")}`,
|
|
409
|
+
validTokens
|
|
410
|
+
};
|
|
411
|
+
}
|
|
309
412
|
return {
|
|
310
413
|
error: `Unknown method "${methodName}" on namespace "${current.name}". Valid: ${validTokens.join(", ")}`,
|
|
311
414
|
validTokens
|
|
@@ -313,6 +416,10 @@ function resolvePath(tree, segments) {
|
|
|
313
416
|
}
|
|
314
417
|
return { node: current, method };
|
|
315
418
|
}
|
|
419
|
+
var READ_ONLY_PREFIX = /^(get|list|search|retrieve|batchGet|bulkRetrieve|calculate|info|changes|deprecatedGet|deprecatedBatchGet|v1List|v1Retrieve)/;
|
|
420
|
+
function isReadOnlyMethod(name) {
|
|
421
|
+
return READ_ONLY_PREFIX.test(name);
|
|
422
|
+
}
|
|
316
423
|
|
|
317
424
|
// src/execute.ts
|
|
318
425
|
function isPage(value) {
|
|
@@ -321,34 +428,40 @@ function isPage(value) {
|
|
|
321
428
|
const v = value;
|
|
322
429
|
return Symbol.asyncIterator in value && typeof v["hasNextPage"] === "function" && "data" in v;
|
|
323
430
|
}
|
|
324
|
-
async function
|
|
325
|
-
const
|
|
326
|
-
let page = firstPage;
|
|
327
|
-
while (true) {
|
|
328
|
-
results.push(...page.data);
|
|
329
|
-
if (!page.hasNextPage())
|
|
330
|
-
break;
|
|
331
|
-
page = await page.getNextPage();
|
|
332
|
-
}
|
|
333
|
-
return results;
|
|
334
|
-
}
|
|
335
|
-
async function* streamPages(firstPage) {
|
|
431
|
+
async function* iteratePages(firstPage, options) {
|
|
432
|
+
const { maxItems, maxPages } = options;
|
|
336
433
|
let page = firstPage;
|
|
434
|
+
let pages = 1;
|
|
435
|
+
let items = 0;
|
|
337
436
|
while (true) {
|
|
338
437
|
for (const item of page.data) {
|
|
438
|
+
if (maxItems !== undefined && items >= maxItems)
|
|
439
|
+
return;
|
|
339
440
|
yield item;
|
|
441
|
+
items++;
|
|
340
442
|
}
|
|
341
443
|
if (!page.hasNextPage())
|
|
342
|
-
|
|
444
|
+
return;
|
|
445
|
+
if (maxPages !== undefined && pages >= maxPages)
|
|
446
|
+
return;
|
|
447
|
+
if (maxItems !== undefined && items >= maxItems)
|
|
448
|
+
return;
|
|
343
449
|
page = await page.getNextPage();
|
|
450
|
+
pages++;
|
|
344
451
|
}
|
|
345
452
|
}
|
|
453
|
+
async function collectPages(firstPage, options) {
|
|
454
|
+
const results = [];
|
|
455
|
+
for await (const item of iteratePages(firstPage, options))
|
|
456
|
+
results.push(item);
|
|
457
|
+
return results;
|
|
458
|
+
}
|
|
346
459
|
function execute(method, request, options) {
|
|
347
460
|
if (options.stream) {
|
|
348
461
|
return async function* () {
|
|
349
462
|
const result = await Promise.resolve(method.fn(request));
|
|
350
463
|
if (isPage(result)) {
|
|
351
|
-
yield*
|
|
464
|
+
yield* iteratePages(result, options);
|
|
352
465
|
} else {
|
|
353
466
|
yield result;
|
|
354
467
|
}
|
|
@@ -357,7 +470,7 @@ function execute(method, request, options) {
|
|
|
357
470
|
return (async () => {
|
|
358
471
|
const result = await Promise.resolve(method.fn(request));
|
|
359
472
|
if (isPage(result)) {
|
|
360
|
-
return collectPages(result);
|
|
473
|
+
return collectPages(result, options);
|
|
361
474
|
}
|
|
362
475
|
return result;
|
|
363
476
|
})();
|
|
@@ -377,19 +490,72 @@ function print(value, options = {}) {
|
|
|
377
490
|
write(JSON.stringify(value, bigIntReplacer, 2));
|
|
378
491
|
}
|
|
379
492
|
}
|
|
493
|
+
var STATUS_REASON = {
|
|
494
|
+
400: "Bad Request",
|
|
495
|
+
401: "Unauthorized",
|
|
496
|
+
403: "Forbidden",
|
|
497
|
+
404: "Not Found",
|
|
498
|
+
405: "Method Not Allowed",
|
|
499
|
+
409: "Conflict",
|
|
500
|
+
422: "Unprocessable Entity",
|
|
501
|
+
429: "Too Many Requests",
|
|
502
|
+
500: "Internal Server Error",
|
|
503
|
+
503: "Service Unavailable"
|
|
504
|
+
};
|
|
505
|
+
function hintFor(e) {
|
|
506
|
+
const field = e.field ?? "";
|
|
507
|
+
if (e.code === "INVALID_ENUM_VALUE" && /^sort_/.test(field)) {
|
|
508
|
+
if (field === "sort_field")
|
|
509
|
+
return "This list endpoint needs an explicit sort field, e.g. `--sortField CREATED_AT`.";
|
|
510
|
+
if (field === "sort_order")
|
|
511
|
+
return "This list endpoint needs an explicit sort order, e.g. `--sortOrder ASC`.";
|
|
512
|
+
}
|
|
513
|
+
switch (e.code) {
|
|
514
|
+
case "UNAUTHORIZED":
|
|
515
|
+
case "ACCESS_TOKEN_EXPIRED":
|
|
516
|
+
case "ACCESS_TOKEN_REVOKED":
|
|
517
|
+
case "AUTHENTICATION_ERROR":
|
|
518
|
+
return "Check your access token (`square config set <profile> --token ...` or $SQUARE_ACCESS_TOKEN).";
|
|
519
|
+
case "FORBIDDEN":
|
|
520
|
+
case "INSUFFICIENT_SCOPES":
|
|
521
|
+
return "Your token lacks the OAuth scope/permission for this endpoint.";
|
|
522
|
+
case "NOT_FOUND":
|
|
523
|
+
return "The referenced resource does not exist in this environment (sandbox vs production?).";
|
|
524
|
+
case "RATE_LIMITED":
|
|
525
|
+
return "You hit the API rate limit — retry after a short delay.";
|
|
526
|
+
case "VALUE_EMPTY":
|
|
527
|
+
case "MISSING_REQUIRED_PARAMETER":
|
|
528
|
+
return e.field ? `Provide the required field: \`--${camelize(e.field)} <value>\` or via \`--json\`.` : "A required field is missing — pass it with `--<field> <value>` or `--json`.";
|
|
529
|
+
default:
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function camelize(field) {
|
|
534
|
+
return field.split(".").map((seg) => seg.replace(/_([a-z])/g, (_, c) => c.toUpperCase())).join(".");
|
|
535
|
+
}
|
|
380
536
|
function renderError(err, options = {}) {
|
|
381
537
|
const write = options.writeFn ?? ((msg) => process.stderr.write(msg + `
|
|
382
538
|
`));
|
|
383
539
|
if (err instanceof SquareError) {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
540
|
+
const status = err.statusCode;
|
|
541
|
+
const reason = status ? STATUS_REASON[status] : undefined;
|
|
542
|
+
const statusText = status ? `HTTP ${status}${reason ? " " + reason : ""}` : "request failed";
|
|
543
|
+
write(`✗ Square API request failed (${statusText})`);
|
|
544
|
+
const errors = err.errors ?? [];
|
|
545
|
+
for (const e of errors) {
|
|
546
|
+
write("");
|
|
547
|
+
write(` • ${e.detail ?? e.code}`);
|
|
548
|
+
if (e.field)
|
|
549
|
+
write(` field: ${e.field}`);
|
|
550
|
+
write(` code: ${e.category} / ${e.code}`);
|
|
551
|
+
const hint = hintFor(e);
|
|
552
|
+
if (hint)
|
|
553
|
+
write(` hint: ${hint}`);
|
|
388
554
|
}
|
|
389
555
|
} else if (err instanceof Error) {
|
|
390
|
-
write(
|
|
556
|
+
write(`✗ Error: ${err.message}`);
|
|
391
557
|
} else {
|
|
392
|
-
write(
|
|
558
|
+
write(`✗ Error: ${String(err)}`);
|
|
393
559
|
}
|
|
394
560
|
return 1;
|
|
395
561
|
}
|
|
@@ -400,9 +566,13 @@ Global flags:
|
|
|
400
566
|
--profile <name> Use a named profile from config
|
|
401
567
|
--token <token> Square API access token
|
|
402
568
|
--env <environment> "sandbox" or "production" (default: sandbox)
|
|
403
|
-
--json <json> JSON body for the request
|
|
569
|
+
--json <json> JSON body for the request (@file or - for stdin)
|
|
404
570
|
--json-output Output as compact JSON (no pretty print)
|
|
405
|
-
--stream Stream pageable results item
|
|
571
|
+
--stream Stream pageable results as NDJSON (one item per line)
|
|
572
|
+
--dry-run Print the request that would be sent, without sending it
|
|
573
|
+
--max-items <n> Stop paging after n items
|
|
574
|
+
--max-pages <n> Stop paging after n pages
|
|
575
|
+
--yes Skip the confirmation for write calls in production
|
|
406
576
|
--help Show this help message
|
|
407
577
|
`.trim();
|
|
408
578
|
function renderRootHelp(tree) {
|
|
@@ -420,30 +590,33 @@ function renderRootHelp(tree) {
|
|
|
420
590
|
}
|
|
421
591
|
lines.push("");
|
|
422
592
|
lines.push("Built-in commands:");
|
|
423
|
-
lines.push(" config set <profile> --token <tok
|
|
593
|
+
lines.push(" config set <profile> [--token <tok>|-] --env <env> Create/update a profile");
|
|
594
|
+
lines.push(" (omit --token to be prompted)");
|
|
424
595
|
lines.push(" config get <profile> Show profile (token masked)");
|
|
425
|
-
lines.push(" config list List
|
|
596
|
+
lines.push(" config list List profiles (* marks the default)");
|
|
426
597
|
lines.push(" config use <profile> Set default profile");
|
|
598
|
+
lines.push(" config remove <profile> Delete a profile");
|
|
599
|
+
lines.push(" whoami Show the merchant for the current token");
|
|
427
600
|
lines.push("");
|
|
428
601
|
lines.push(GLOBAL_FLAGS);
|
|
429
602
|
return lines.join(`
|
|
430
603
|
`);
|
|
431
604
|
}
|
|
432
|
-
function renderNamespaceHelp(node) {
|
|
605
|
+
function renderNamespaceHelp(node, path2 = node.name) {
|
|
433
606
|
const lines = [];
|
|
434
|
-
lines.push(`Namespace: ${
|
|
607
|
+
lines.push(`Namespace: ${path2}`);
|
|
435
608
|
lines.push("");
|
|
436
609
|
if (node.children.size > 0) {
|
|
437
610
|
lines.push("Sub-namespaces:");
|
|
438
611
|
for (const [name] of node.children) {
|
|
439
|
-
lines.push(` ${
|
|
612
|
+
lines.push(` ${path2} ${name}`);
|
|
440
613
|
}
|
|
441
614
|
lines.push("");
|
|
442
615
|
}
|
|
443
616
|
if (node.methods.size > 0) {
|
|
444
617
|
lines.push("Methods:");
|
|
445
618
|
for (const [name, method] of node.methods) {
|
|
446
|
-
lines.push(` ${
|
|
619
|
+
lines.push(` ${path2} ${name} (arity: ${method.arity})`);
|
|
447
620
|
}
|
|
448
621
|
lines.push("");
|
|
449
622
|
}
|
|
@@ -462,6 +635,8 @@ function renderMethodHelp(namespaceName, methodName, arity) {
|
|
|
462
635
|
lines.push(" --json '<json>' Full request body as JSON");
|
|
463
636
|
lines.push(" --<field.path> <value> Set a field in the request by dotted path");
|
|
464
637
|
lines.push(` e.g. --amountMoney.amount 100`);
|
|
638
|
+
lines.push(" --<field.path>:str <value> Same, but keep the value a string (no JSON coercion)");
|
|
639
|
+
lines.push(` e.g. --address.postalCode:str 94103`);
|
|
465
640
|
lines.push("");
|
|
466
641
|
lines.push(`Note: arity hint = ${arity} (optional params may not be counted)`);
|
|
467
642
|
lines.push(" Always pass a request object (even if empty).");
|
|
@@ -471,100 +646,203 @@ function renderMethodHelp(namespaceName, methodName, arity) {
|
|
|
471
646
|
`);
|
|
472
647
|
}
|
|
473
648
|
|
|
649
|
+
// src/prompt.ts
|
|
650
|
+
import * as fs3 from "fs";
|
|
651
|
+
import * as readline from "readline";
|
|
652
|
+
function isInteractive() {
|
|
653
|
+
return Boolean(process.stdin.isTTY && process.stderr.isTTY);
|
|
654
|
+
}
|
|
655
|
+
async function confirm(question) {
|
|
656
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
657
|
+
const answer = await new Promise((resolve) => rl.question(question, resolve));
|
|
658
|
+
rl.close();
|
|
659
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
660
|
+
}
|
|
661
|
+
function secret(question) {
|
|
662
|
+
return new Promise((resolve, reject) => {
|
|
663
|
+
const stdin = process.stdin;
|
|
664
|
+
let value = "";
|
|
665
|
+
const finish = (err) => {
|
|
666
|
+
stdin.off("data", onData);
|
|
667
|
+
stdin.setRawMode(false);
|
|
668
|
+
stdin.pause();
|
|
669
|
+
process.stderr.write(`
|
|
670
|
+
`);
|
|
671
|
+
if (err)
|
|
672
|
+
reject(err);
|
|
673
|
+
else
|
|
674
|
+
resolve(value);
|
|
675
|
+
};
|
|
676
|
+
const onData = (chunk) => {
|
|
677
|
+
for (const ch of chunk) {
|
|
678
|
+
if (ch === "\r" || ch === `
|
|
679
|
+
`)
|
|
680
|
+
return finish();
|
|
681
|
+
if (ch === "\x03")
|
|
682
|
+
return finish(new Error("Cancelled"));
|
|
683
|
+
if (ch === "" || ch === "\b") {
|
|
684
|
+
value = value.slice(0, -1);
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
value += ch;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
process.stderr.write(question);
|
|
691
|
+
stdin.setRawMode(true);
|
|
692
|
+
stdin.setEncoding("utf8");
|
|
693
|
+
stdin.resume();
|
|
694
|
+
stdin.on("data", onData);
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
function readStdin() {
|
|
698
|
+
return fs3.readFileSync(0, "utf8");
|
|
699
|
+
}
|
|
700
|
+
var terminalPrompter = { isInteractive, confirm, secret, readStdin };
|
|
701
|
+
|
|
474
702
|
// src/cli.ts
|
|
475
703
|
var defaultDeps = {
|
|
476
|
-
createClient
|
|
704
|
+
createClient,
|
|
705
|
+
prompter: terminalPrompter
|
|
477
706
|
};
|
|
478
707
|
async function run(argv, deps = defaultDeps, stdoutWrite, stderrWrite) {
|
|
479
708
|
const stdout = stdoutWrite ?? ((msg) => process.stdout.write(msg + `
|
|
480
709
|
`));
|
|
481
710
|
const stderr = stderrWrite ?? ((msg) => process.stderr.write(msg + `
|
|
482
711
|
`));
|
|
712
|
+
const prompter = deps.prompter ?? terminalPrompter;
|
|
483
713
|
const parsed = parseArgs(argv);
|
|
484
714
|
const { positionals, flags, fields } = parsed;
|
|
485
715
|
if (positionals[0] === "config") {
|
|
486
|
-
return runConfigCommand(positionals.slice(1), flags, stdout, stderr);
|
|
716
|
+
return runConfigCommand(positionals.slice(1), flags, prompter, stdout, stderr);
|
|
487
717
|
}
|
|
488
|
-
if (
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
stdout(renderRootHelp(tree2));
|
|
494
|
-
return 0;
|
|
495
|
-
}
|
|
496
|
-
if (positionals.length === 1) {
|
|
497
|
-
const nsNode = tree2.children.get(positionals[0]);
|
|
498
|
-
if (nsNode) {
|
|
499
|
-
stdout(renderNamespaceHelp(nsNode));
|
|
500
|
-
return 0;
|
|
501
|
-
}
|
|
502
|
-
} else {
|
|
503
|
-
const resolveResult2 = resolvePath(tree2, positionals);
|
|
504
|
-
if (!("error" in resolveResult2)) {
|
|
505
|
-
stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), resolveResult2.method.name, resolveResult2.method.arity));
|
|
506
|
-
return 0;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
stdout(renderRootHelp(tree2));
|
|
510
|
-
return 0;
|
|
511
|
-
} catch {
|
|
512
|
-
stdout("Square SDK CLI\n\nUse `square --help` for available namespaces.");
|
|
718
|
+
if (positionals[0] === "whoami") {
|
|
719
|
+
if (flags.help) {
|
|
720
|
+
stdout(`Usage: square whoami [--profile <name>] [--json-output]
|
|
721
|
+
|
|
722
|
+
Show the merchant, environment, and token source in use.`);
|
|
513
723
|
return 0;
|
|
514
724
|
}
|
|
725
|
+
return runWhoami(deps, flags, stdout, stderr);
|
|
726
|
+
}
|
|
727
|
+
const shapeTree = buildTree(deps.createClient({ token: "dummy", environment: "sandbox" }));
|
|
728
|
+
if (positionals.length === 0) {
|
|
729
|
+
stdout(renderRootHelp(shapeTree));
|
|
730
|
+
return 0;
|
|
731
|
+
}
|
|
732
|
+
const nsNode = findNamespace(shapeTree, positionals);
|
|
733
|
+
if (nsNode) {
|
|
734
|
+
stdout(renderNamespaceHelp(nsNode, positionals.join(" ")));
|
|
735
|
+
return 0;
|
|
736
|
+
}
|
|
737
|
+
const shapeResult = resolvePath(shapeTree, positionals);
|
|
738
|
+
if (flags.help) {
|
|
739
|
+
if ("error" in shapeResult) {
|
|
740
|
+
stdout(renderRootHelp(shapeTree));
|
|
741
|
+
} else {
|
|
742
|
+
stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), shapeResult.method.name, shapeResult.method.arity));
|
|
743
|
+
}
|
|
744
|
+
return 0;
|
|
745
|
+
}
|
|
746
|
+
if ("error" in shapeResult) {
|
|
747
|
+
stderr(`Error: ${shapeResult.error}`);
|
|
748
|
+
return 1;
|
|
515
749
|
}
|
|
516
750
|
let auth;
|
|
517
751
|
try {
|
|
518
|
-
|
|
519
|
-
const env = process.env;
|
|
520
|
-
auth = resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
|
|
752
|
+
auth = await resolveAuthFromFlags(flags);
|
|
521
753
|
} catch (e) {
|
|
522
|
-
|
|
523
|
-
return exitCode;
|
|
524
|
-
}
|
|
525
|
-
const client = deps.createClient(auth);
|
|
526
|
-
const tree = buildTree(client);
|
|
527
|
-
if (positionals.length === 1) {
|
|
528
|
-
const nsNode = tree.children.get(positionals[0]);
|
|
529
|
-
if (nsNode) {
|
|
530
|
-
stdout(renderNamespaceHelp(nsNode));
|
|
531
|
-
return 0;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
if (positionals.length < 2) {
|
|
535
|
-
stdout(renderRootHelp(tree));
|
|
536
|
-
return 0;
|
|
754
|
+
return renderError(e, { writeFn: stderr });
|
|
537
755
|
}
|
|
538
|
-
const resolveResult = resolvePath(
|
|
756
|
+
const resolveResult = resolvePath(buildTree(deps.createClient(auth)), positionals);
|
|
539
757
|
if ("error" in resolveResult) {
|
|
540
758
|
stderr(`Error: ${resolveResult.error}`);
|
|
541
|
-
stderr(`Valid options: ${resolveResult.validTokens.join(", ")}`);
|
|
542
759
|
return 1;
|
|
543
760
|
}
|
|
544
761
|
let request;
|
|
762
|
+
let maxItems;
|
|
763
|
+
let maxPages;
|
|
545
764
|
try {
|
|
546
|
-
|
|
765
|
+
maxItems = parseLimit(flags.maxItems, "--max-items");
|
|
766
|
+
maxPages = parseLimit(flags.maxPages, "--max-pages");
|
|
767
|
+
if (flags.json !== undefined && typeof flags.json !== "string") {
|
|
768
|
+
throw new Error("--json requires a value: a JSON string, @file, or - for stdin");
|
|
769
|
+
}
|
|
770
|
+
request = buildRequest(flags.json === undefined ? undefined : readJsonArg(flags.json), fields);
|
|
547
771
|
} catch (e) {
|
|
548
772
|
renderError(e, { writeFn: stderr });
|
|
549
773
|
return 1;
|
|
550
774
|
}
|
|
775
|
+
const raw = flags.jsonOutput === true;
|
|
776
|
+
const methodName = resolveResult.method.name;
|
|
777
|
+
const readOnly = isReadOnlyMethod(methodName);
|
|
778
|
+
const generatedKey = readOnly ? undefined : ensureIdempotencyKey(request, methodName);
|
|
779
|
+
if (flags.dryRun) {
|
|
780
|
+
print({
|
|
781
|
+
dryRun: true,
|
|
782
|
+
environment: auth.environment,
|
|
783
|
+
method: positionals.join(" "),
|
|
784
|
+
request
|
|
785
|
+
}, { raw, writeFn: stdout });
|
|
786
|
+
return 0;
|
|
787
|
+
}
|
|
788
|
+
if (auth.environment === "production" && !readOnly && !flags.yes) {
|
|
789
|
+
const command = positionals.join(" ");
|
|
790
|
+
if (!prompter.isInteractive()) {
|
|
791
|
+
stderr(`✗ Error: Refusing to run "${command}" against PRODUCTION without confirmation. Pass --yes to proceed.`);
|
|
792
|
+
return 1;
|
|
793
|
+
}
|
|
794
|
+
const ok = await prompter.confirm(`About to run "${command}" against PRODUCTION. Continue? [y/N] `);
|
|
795
|
+
if (!ok) {
|
|
796
|
+
stderr("Aborted.");
|
|
797
|
+
return 1;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
if (generatedKey)
|
|
801
|
+
stderr(`Using idempotencyKey ${generatedKey} (pass --idempotencyKey to retry safely)`);
|
|
551
802
|
try {
|
|
552
803
|
const streamMode = flags.stream === true;
|
|
553
|
-
const result = execute(resolveResult.method, request, { stream: streamMode });
|
|
804
|
+
const result = execute(resolveResult.method, request, { stream: streamMode, maxItems, maxPages });
|
|
554
805
|
if (streamMode) {
|
|
555
806
|
for await (const item of result) {
|
|
556
|
-
stdout(JSON.stringify(item, bigIntReplacer
|
|
807
|
+
stdout(JSON.stringify(item, bigIntReplacer));
|
|
557
808
|
}
|
|
558
809
|
} else {
|
|
559
810
|
const value = await result;
|
|
560
|
-
print(value, { writeFn: stdout });
|
|
811
|
+
print(value, { raw, writeFn: stdout });
|
|
561
812
|
}
|
|
562
813
|
return 0;
|
|
563
814
|
} catch (e) {
|
|
564
815
|
return renderError(e, { writeFn: stderr });
|
|
565
816
|
}
|
|
566
817
|
}
|
|
567
|
-
async function
|
|
818
|
+
async function resolveAuthFromFlags(flags) {
|
|
819
|
+
const config = await load();
|
|
820
|
+
const env = process.env;
|
|
821
|
+
return resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
|
|
822
|
+
}
|
|
823
|
+
async function runWhoami(deps, flags, stdout, stderr) {
|
|
824
|
+
try {
|
|
825
|
+
const auth = await resolveAuthFromFlags(flags);
|
|
826
|
+
const client = deps.createClient(auth);
|
|
827
|
+
const { merchant } = await client.merchants.get({ merchantId: "me" });
|
|
828
|
+
print({
|
|
829
|
+
environment: auth.environment,
|
|
830
|
+
tokenSource: auth.source,
|
|
831
|
+
merchant: {
|
|
832
|
+
id: merchant?.id,
|
|
833
|
+
businessName: merchant?.businessName,
|
|
834
|
+
country: merchant?.country,
|
|
835
|
+
currency: merchant?.currency,
|
|
836
|
+
status: merchant?.status,
|
|
837
|
+
mainLocationId: merchant?.mainLocationId
|
|
838
|
+
}
|
|
839
|
+
}, { raw: flags.jsonOutput === true, writeFn: stdout });
|
|
840
|
+
return 0;
|
|
841
|
+
} catch (e) {
|
|
842
|
+
return renderError(e, { writeFn: stderr });
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
async function runConfigCommand(args, flags, prompter, stdout, stderr) {
|
|
568
846
|
const subcommand = args[0];
|
|
569
847
|
switch (subcommand) {
|
|
570
848
|
case "set": {
|
|
@@ -573,12 +851,33 @@ async function runConfigCommand(args, flags, stdout, stderr) {
|
|
|
573
851
|
stderr("Usage: square config set <profile> --token <token> [--env <environment>]");
|
|
574
852
|
return 1;
|
|
575
853
|
}
|
|
576
|
-
|
|
577
|
-
|
|
854
|
+
let environment = "sandbox";
|
|
855
|
+
try {
|
|
856
|
+
if (flags.env !== undefined)
|
|
857
|
+
environment = parseEnvironment(String(flags.env), "--env");
|
|
858
|
+
} catch (e) {
|
|
859
|
+
return renderError(e, { writeFn: stderr });
|
|
860
|
+
}
|
|
861
|
+
let token;
|
|
862
|
+
try {
|
|
863
|
+
if (flags.token === "-") {
|
|
864
|
+
token = prompter.readStdin().trim();
|
|
865
|
+
} else if (typeof flags.token === "string") {
|
|
866
|
+
token = flags.token;
|
|
867
|
+
} else if (prompter.isInteractive()) {
|
|
868
|
+
token = (await prompter.secret("Access token: ")).trim();
|
|
869
|
+
} else {
|
|
870
|
+
stderr("Error: --token is required for config set (use --token - to read it from stdin)");
|
|
871
|
+
return 1;
|
|
872
|
+
}
|
|
873
|
+
} catch (e) {
|
|
874
|
+
return renderError(e, { writeFn: stderr });
|
|
875
|
+
}
|
|
876
|
+
if (!token) {
|
|
877
|
+
stderr("Error: token is empty");
|
|
578
878
|
return 1;
|
|
579
879
|
}
|
|
580
|
-
|
|
581
|
-
await setProfile(profileName, { token: flags.token, environment });
|
|
880
|
+
await setProfile(profileName, { token, environment });
|
|
582
881
|
stdout(`Profile "${profileName}" saved.`);
|
|
583
882
|
return 0;
|
|
584
883
|
}
|
|
@@ -598,17 +897,37 @@ async function runConfigCommand(args, flags, stdout, stderr) {
|
|
|
598
897
|
return 0;
|
|
599
898
|
}
|
|
600
899
|
case "list": {
|
|
601
|
-
const
|
|
900
|
+
const cfg = await load();
|
|
901
|
+
const names = Object.keys(cfg.profiles);
|
|
602
902
|
if (names.length === 0) {
|
|
603
903
|
stdout("No profiles configured.");
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
904
|
+
return 0;
|
|
905
|
+
}
|
|
906
|
+
const width = Math.max(...names.map((n) => n.length));
|
|
907
|
+
stdout("Profiles:");
|
|
908
|
+
for (const name of names) {
|
|
909
|
+
const marker = name === cfg.defaultProfile ? "*" : " ";
|
|
910
|
+
stdout(`${marker} ${name.padEnd(width)} ${cfg.profiles[name].environment}`);
|
|
609
911
|
}
|
|
912
|
+
if (cfg.defaultProfile)
|
|
913
|
+
stdout(`
|
|
914
|
+
(* = default)`);
|
|
610
915
|
return 0;
|
|
611
916
|
}
|
|
917
|
+
case "remove": {
|
|
918
|
+
const profileName = args[1];
|
|
919
|
+
if (!profileName) {
|
|
920
|
+
stderr("Usage: square config remove <profile>");
|
|
921
|
+
return 1;
|
|
922
|
+
}
|
|
923
|
+
try {
|
|
924
|
+
const wasDefault = await removeProfile(profileName);
|
|
925
|
+
stdout(`Profile "${profileName}" removed.${wasDefault ? " It was the default; no default is set now." : ""}`);
|
|
926
|
+
return 0;
|
|
927
|
+
} catch (e) {
|
|
928
|
+
return renderError(e, { writeFn: stderr });
|
|
929
|
+
}
|
|
930
|
+
}
|
|
612
931
|
case "use": {
|
|
613
932
|
const profileName = args[1];
|
|
614
933
|
if (!profileName) {
|
|
@@ -624,11 +943,20 @@ async function runConfigCommand(args, flags, stdout, stderr) {
|
|
|
624
943
|
}
|
|
625
944
|
}
|
|
626
945
|
default: {
|
|
627
|
-
stderr(`Unknown config subcommand: "${subcommand}". Use set, get, list, or
|
|
946
|
+
stderr(`Unknown config subcommand: "${subcommand}". Use set, get, list, use, or remove.`);
|
|
628
947
|
return 1;
|
|
629
948
|
}
|
|
630
949
|
}
|
|
631
950
|
}
|
|
951
|
+
function parseLimit(value, flag) {
|
|
952
|
+
if (value === undefined)
|
|
953
|
+
return;
|
|
954
|
+
const n = Number(value);
|
|
955
|
+
if (typeof value !== "string" || !Number.isInteger(n) || n < 1) {
|
|
956
|
+
throw new Error(`${flag} must be a positive integer`);
|
|
957
|
+
}
|
|
958
|
+
return n;
|
|
959
|
+
}
|
|
632
960
|
function maskToken(token) {
|
|
633
961
|
if (token.length <= 4)
|
|
634
962
|
return "****";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "square-sdk-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Command-line interface for the Square API, exposing every SDK namespace and method via runtime introspection.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"square",
|
|
@@ -27,7 +27,8 @@
|
|
|
27
27
|
},
|
|
28
28
|
"files": [
|
|
29
29
|
"dist",
|
|
30
|
-
"README.md"
|
|
30
|
+
"README.md",
|
|
31
|
+
"CHANGELOG.md"
|
|
31
32
|
],
|
|
32
33
|
"engines": {
|
|
33
34
|
"node": ">=18"
|
|
@@ -35,15 +36,14 @@
|
|
|
35
36
|
"scripts": {
|
|
36
37
|
"build": "bun scripts/build.ts",
|
|
37
38
|
"test": "bun test",
|
|
38
|
-
"
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"prepublishOnly": "bun run typecheck && bun run build && bun test"
|
|
39
41
|
},
|
|
40
42
|
"devDependencies": {
|
|
41
|
-
"@types/bun": "
|
|
42
|
-
|
|
43
|
-
"peerDependencies": {
|
|
44
|
-
"typescript": "^5"
|
|
43
|
+
"@types/bun": "^1.4.3",
|
|
44
|
+
"typescript": "^5.9.3"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"square": "^44.1
|
|
47
|
+
"square": "^44.2.1"
|
|
48
48
|
}
|
|
49
49
|
}
|