@substrio/cli 0.0.0-stage → 0.1.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.
Files changed (56) hide show
  1. package/LICENSE +177 -0
  2. package/README.md +66 -2
  3. package/bin/substrio.mjs +91 -0
  4. package/package.json +44 -4
  5. package/src/api.mjs +107 -0
  6. package/src/apply.mjs +204 -0
  7. package/src/blobs.mjs +102 -0
  8. package/src/cli.mjs +405 -0
  9. package/src/collections.mjs +701 -0
  10. package/src/command-table.mjs +436 -0
  11. package/src/commands/bundle.mjs +369 -0
  12. package/src/commands/count.mjs +39 -0
  13. package/src/commands/deploy.mjs +488 -0
  14. package/src/commands/dev.mjs +246 -0
  15. package/src/commands/env.mjs +115 -0
  16. package/src/commands/files.mjs +172 -0
  17. package/src/commands/git.mjs +195 -0
  18. package/src/commands/groups-runtime.mjs +227 -0
  19. package/src/commands/groups.mjs +417 -0
  20. package/src/commands/history.mjs +374 -0
  21. package/src/commands/import.mjs +506 -0
  22. package/src/commands/init.mjs +175 -0
  23. package/src/commands/key.mjs +172 -0
  24. package/src/commands/login.mjs +167 -0
  25. package/src/commands/logs.mjs +285 -0
  26. package/src/commands/mcp-config.mjs +102 -0
  27. package/src/commands/op.mjs +265 -0
  28. package/src/commands/open.mjs +35 -0
  29. package/src/commands/push.mjs +199 -0
  30. package/src/commands/signup.mjs +164 -0
  31. package/src/commands/site.mjs +129 -0
  32. package/src/commands/skills.mjs +177 -0
  33. package/src/commands/status.mjs +78 -0
  34. package/src/commands/tenants.mjs +172 -0
  35. package/src/commands/test.mjs +167 -0
  36. package/src/commands/tools.mjs +63 -0
  37. package/src/commands/versions.mjs +293 -0
  38. package/src/config.mjs +569 -0
  39. package/src/documents.mjs +139 -0
  40. package/src/function-build.mjs +273 -0
  41. package/src/identity.mjs +248 -0
  42. package/src/jsonfile.mjs +22 -0
  43. package/src/live-move.mjs +267 -0
  44. package/src/local/args.mjs +58 -0
  45. package/src/local/reload.mjs +408 -0
  46. package/src/local/server.mjs +291 -0
  47. package/src/local/watch.mjs +175 -0
  48. package/src/manifest.mjs +591 -0
  49. package/src/ops.mjs +265 -0
  50. package/src/readers.mjs +416 -0
  51. package/src/sdk.mjs +26 -0
  52. package/src/settings.mjs +117 -0
  53. package/src/testing/app.mjs +507 -0
  54. package/src/testing/env.mjs +35 -0
  55. package/src/testing/index.mjs +11 -0
  56. package/src/testing/types.mjs +55 -0
package/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @substrio/cli
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
+ The Substrio CLI: deploy functions, manage secrets, stream logs, run a local dev server.
4
+ Bin name is `substrio`. Every command is non-interactive when given its flags or stdin, so an agent never needs a TTY.
5
+
6
+ ## Install
7
+
8
+ ```
9
+ npm install -g @substrio/cli
10
+ ```
11
+
12
+ (or run it once with `npx @substrio/cli <command>`).
13
+
14
+ ## Five commands from a fresh machine to a working result
15
+
16
+ ```
17
+ substrio init --url http://localhost:9000 --tenant myapp --yes
18
+ substrio login --url http://localhost:9000 --key - --tenant myapp < keyfile
19
+ substrio status
20
+ substrio dev
21
+ substrio deploy
22
+ ```
23
+
24
+ - `substrio init --url URL --tenant SLUG --yes` scaffolds a project (`substrio.toml`, no key stored in it).
25
+ - `substrio login [--url URL] --key - [--tenant SLUG]` reads the key from stdin (never from argv, never in shell history) and saves a profile. Without `--url` the profile is the hosted platform, `https://mcp.substrio.com`. Set `--profile NAME` to save under a name other than the default.
26
+ - `substrio status` reports server health and the config in use.
27
+ - `substrio dev [--attach URL] [--server PATH] [--port N] [--data DIR] [--no-build] [--no-logs]` runs the app on a local server with hot reload. Data and keys stay under `.substrio/dev` (or `--data DIR`).
28
+ - `substrio deploy [--dry-run]` deploys the declared collections, functions and rules.
29
+
30
+ ## Non-interactive forms
31
+
32
+ - Any flag that would otherwise prompt takes `-` to read from stdin (for example `substrio login --key -`), or can be set from an environment variable (`SUBSTRIO_SERVER_BIN`, `SUBSTRIO_KEY`; see below).
33
+ - `substrio key export --env FILE [--var NAME] [--force]` writes `NAME=KEY` (default variable name `SUBSTRIO_KEY`) to `FILE`, created owner-only (mode 0600), and never prints the key. Use this to feed a key to an MCP client config or a CI secret store.
34
+ - `substrio mcp config [--client claude|cursor|generic] [--name NAME] [--env VAR]` prints an MCP client config as JSON to stdout (`substrio mcp config > .mcp.json`); the key itself is never read or printed, only a reference to the environment variable.
35
+
36
+ ## Where the key is stored
37
+
38
+ A saved profile's key lives in the CLI's local config directory, never in `substrio.toml` and never printed by `substrio login` or `substrio init`. To get the key into a file for another tool, use `substrio key export --env FILE` (0600, owner-only).
39
+
40
+ ## The local substrio_server binary
41
+
42
+ `substrio dev` and `substrio test` need a `substrio_server` binary; the CLI does not download one. `resolveServerBinary` (`src/local/server.mjs`) looks, in order:
43
+
44
+ 1. `--server PATH` given on the command line.
45
+ 2. `SUBSTRIO_SERVER_BIN` environment variable.
46
+ 3. `substrio_server` on `PATH`.
47
+ 4. `build/bin/substrio_server` relative to the checkout the CLI file sits in (only exists when run from a source checkout, never under `node_modules`).
48
+
49
+ If none of these resolve, the command fails with a `FILE_NOT_FOUND` error and a hint to build the binary (`cmake --build build --target substrio_server`) or pass `--server PATH` / set `SUBSTRIO_SERVER_BIN`.
50
+
51
+ ## Exit codes
52
+
53
+ | Code | Meaning |
54
+ |---|---|
55
+ | 0 | success |
56
+ | 1 | failure (anything not listed below) |
57
+ | 2 | usage: bad arguments or input |
58
+ | 3 | auth: no credentials, or refused |
59
+ | 4 | not found |
60
+ | 5 | conflict: exists already or changed meanwhile |
61
+ | 6 | server error (5xx) |
62
+ | 7 | network: the server could not be reached |
63
+ | 8 | partial: a bulk operation stored some documents and refused others |
64
+
65
+ ## Docs
66
+
67
+ See `docs/install.md` in this repository for npm/pnpm/yarn/bun install notes and the server binary's current state.
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Substrio CLI: main entry point. Global flags are parsed once (src/cli.mjs);
5
+ * every command, its usage and what it needs come from one table
6
+ * (src/command-table.mjs). `--help` on any command prints its usage and
7
+ * exits 0 before anything runs. `substrio help` lists every command.
8
+ */
9
+
10
+ import { readFileSync } from 'node:fs';
11
+ import { ErrorCode, applyGlobals, emit, fail, parseGlobal } from '../src/cli.mjs';
12
+ import { COMMANDS, Needs, commandHelp, findCommand, needsOf, topHelp } from '../src/command-table.mjs';
13
+
14
+ const DIM = '\x1b[2m';
15
+ const RESET = '\x1b[0m';
16
+ // The version is the package's own (package.json, which npm pack ships).
17
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
18
+
19
+ // The config and API client a command needs, validated to that level.
20
+ async function contextFor(needs) {
21
+ if (needs === Needs.NOTHING) return {};
22
+ const { loadConfig, validateConfig } = await import('../src/config.mjs');
23
+ const config = loadConfig();
24
+ if (needs === Needs.CONFIG) return { config };
25
+ const err = validateConfig(config, needs === Needs.KEY);
26
+ if (err) fail(err, "Run 'substrio login' or 'substrio init' to configure.", ErrorCode.CREDENTIAL_REQUIRED);
27
+ const { SubstrioAPI } = await import('../src/api.mjs');
28
+ return { config, api: new SubstrioAPI(config) };
29
+ }
30
+
31
+ // --dev: the dev profile of this project (saved by `substrio dev`) decides the server, tenant and key.
32
+ async function selectDevServer(flags) {
33
+ if (flags.profile) fail('--dev and --profile each select a profile; give one', null, ErrorCode.INVALID_ARGUMENT);
34
+ const { devConnection } = await import('../src/config.mjs');
35
+ try {
36
+ Object.assign(process.env, devConnection(process.cwd()));
37
+ } catch (err) {
38
+ fail(err.message, 'Start it with "substrio dev" in this directory.', ErrorCode.CREDENTIAL_REQUIRED);
39
+ }
40
+ }
41
+
42
+ async function main() {
43
+ let parsed;
44
+ try {
45
+ parsed = parseGlobal(process.argv.slice(2));
46
+ } catch (err) {
47
+ // The flags did not parse; --json still asks for the typed error.
48
+ applyGlobals({ json: process.argv.includes('--json') });
49
+ fail(err.message, "Run 'substrio help' for usage.");
50
+ }
51
+ const { command, args, flags } = parsed;
52
+ applyGlobals(flags);
53
+ if (flags.dev) await selectDevServer(flags);
54
+
55
+ if (flags.version) {
56
+ emit({ version: VERSION }, ({ version }) => console.log(version));
57
+ return;
58
+ }
59
+ if (!command) {
60
+ console.log(topHelp(VERSION));
61
+ return;
62
+ }
63
+ const entry = findCommand(command);
64
+ if (!entry) fail(`Unknown command: ${command}`, `Commands: ${COMMANDS.map((c) => c.names[0]).join(', ')}. Run 'substrio help'.`);
65
+
66
+ if (flags.help) {
67
+ // An operation's own help reads the server's catalog (a GET, nothing
68
+ // changes); without a configured server, or for the command itself,
69
+ // the usage from the table.
70
+ if (entry.help && args.length) {
71
+ const { loadConfig, validateConfig } = await import('../src/config.mjs');
72
+ const config = loadConfig();
73
+ if (!validateConfig(config, false)) {
74
+ const { SubstrioAPI } = await import('../src/api.mjs');
75
+ try {
76
+ if (await entry.help({ api: new SubstrioAPI(config), config, args, command })) return;
77
+ } catch (err) {
78
+ // No catalog or no such operation: the usage below.
79
+ console.error(`${DIM} (${err.message})${RESET}`);
80
+ }
81
+ }
82
+ }
83
+ console.log(commandHelp(entry));
84
+ return;
85
+ }
86
+
87
+ const ctx = await contextFor(needsOf(entry, args));
88
+ await entry.run({ ...ctx, args, command });
89
+ }
90
+
91
+ main().catch((err) => fail(err, null, ErrorCode.UNKNOWN));
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
- "name": "@substrio/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
2
+ "name": "@substrio/cli",
3
+ "version": "0.1.1",
4
+ "description": "Substrio CLI: deploy functions, manage secrets, stream logs",
5
+ "homepage": "https://github.com/illtronicevents-a11y/substrio#readme",
6
+ "bugs": "https://github.com/illtronicevents-a11y/substrio/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/illtronicevents-a11y/substrio.git",
10
+ "directory": "packages/substrio-cli"
11
+ },
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "bin": {
15
+ "substrio": "bin/substrio.mjs"
16
+ },
17
+ "exports": {
18
+ "./test": "./src/testing/index.mjs",
19
+ "./package.json": "./package.json"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test --test-timeout=60000 \"test/*.test.mjs\""
23
+ },
24
+ "files": [
25
+ "bin/",
26
+ "src/"
27
+ ],
28
+ "dependencies": {
29
+ "@substrio/sdk": "^0.1.0",
30
+ "esbuild": "^0.25.10"
31
+ },
32
+ "engines": {
33
+ "node": ">=18.0.0"
34
+ },
35
+ "keywords": [
36
+ "substrio",
37
+ "baas",
38
+ "cli",
39
+ "deploy",
40
+ "serverless"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "license": "Apache-2.0"
6
46
  }
package/src/api.mjs ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Substrio CLI: HTTP API Client
3
+ *
4
+ * Wraps built-in fetch with auth headers.
5
+ * All methods return the raw fetch Response so callers can handle parsing.
6
+ */
7
+
8
+ import { CliError, ErrorCode } from './cli.mjs';
9
+
10
+ /**
11
+ * The reason a failed API call gives, for people and agents to act on. A substrio
12
+ * error body carries a generic `error` label for its code and, when the
13
+ * handler said more, a `detail` (a sentence such as "Tenant already exists",
14
+ * or the name of the field at fault); both are shown.
15
+ * @param {any} data - the parsed error body (may be empty)
16
+ * @param {number} status - the HTTP status, when the body says nothing
17
+ * @returns {string}
18
+ */
19
+ export function errorText(data, status) {
20
+ const error = data?.error;
21
+ const label = (typeof error === 'string' ? error : error?.message) || data?.message || '';
22
+ const detail = typeof data?.detail === 'string' ? data.detail : '';
23
+ if (detail) return label ? `${label}: ${detail}` : detail;
24
+ return label || `HTTP ${status}`;
25
+ }
26
+
27
+ export class SubstrioAPI {
28
+ /**
29
+ * @param {object} config - { url, tenant, master_key }
30
+ */
31
+ constructor(config) {
32
+ this.url = config.url;
33
+ // null: no tenant header (a call that names none, such as a login's
34
+ // whoami); else the tenant, 'default' when none is configured.
35
+ this.tenant = config.tenant === null ? null : (config.tenant || 'default');
36
+ this.masterKey = config.master_key;
37
+ }
38
+
39
+ /**
40
+ * Make a raw authenticated request. Returns the fetch Response directly.
41
+ * @param {string} method - HTTP method
42
+ * @param {string} path - API path (e.g., '/v1/_secrets')
43
+ * @param {any} [body] - Request body (string, Buffer, a web ReadableStream sent as it is read, or object → JSON)
44
+ * @param {object} [extraHeaders] - Additional headers to merge
45
+ * @returns {Promise<Response>}
46
+ */
47
+ async raw(method, path, body = undefined, extraHeaders = {}) {
48
+ const url = `${this.url}${path}`;
49
+
50
+ const headers = {
51
+ ...(this.tenant === null ? {} : { 'X-Substrio-Tenant': this.tenant }),
52
+ ...extraHeaders,
53
+ };
54
+
55
+ if (this.masterKey) {
56
+ headers['X-Substrio-Master-Key'] = this.masterKey;
57
+ }
58
+
59
+ // Default content-type to JSON unless overridden
60
+ if (!headers['Content-Type']) {
61
+ headers['Content-Type'] = 'application/json';
62
+ }
63
+
64
+ const opts = { method, headers };
65
+
66
+ if (body !== undefined) {
67
+ if (body instanceof ReadableStream) {
68
+ opts.body = body;
69
+ opts.duplex = 'half';
70
+ } else if (typeof body === 'object' && !(body instanceof Buffer) && !(body instanceof Uint8Array)) {
71
+ opts.body = JSON.stringify(body);
72
+ } else {
73
+ opts.body = body;
74
+ }
75
+ }
76
+
77
+ try {
78
+ return await fetch(url, opts);
79
+ } catch (err) {
80
+ // No HTTP answer at all: a typed network error (exit code NETWORK).
81
+ const why = err.cause?.code === 'ECONNREFUSED' ? 'is the Substrio server running?' : (err.cause?.message || err.message);
82
+ throw new CliError(`Cannot connect to ${this.url}: ${why}`, { code: ErrorCode.NETWORK_ERROR });
83
+ }
84
+ }
85
+
86
+ // Convenience methods: all return raw Response
87
+ async get(path) { return this.raw('GET', path); }
88
+ async post(path, body) { return this.raw('POST', path, body); }
89
+ async put(path, body) { return this.raw('PUT', path, body); }
90
+ async patch(path, body) { return this.raw('PATCH', path, body); }
91
+ async delete(path) { return this.raw('DELETE', path); }
92
+
93
+ /**
94
+ * Legacy request() for backward compat: parses response automatically.
95
+ */
96
+ async request(method, path, body = undefined) {
97
+ const res = await this.raw(method, path, body);
98
+ let data;
99
+ const contentType = res.headers.get('content-type') || '';
100
+ if (contentType.includes('application/json')) {
101
+ data = await res.json();
102
+ } else {
103
+ data = await res.text();
104
+ }
105
+ return { status: res.status, data, ok: res.ok };
106
+ }
107
+ }