@nasebanal/cli 0.12.0 → 0.13.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/README.md +268 -79
- package/dist/apis.js +2 -1
- package/dist/index.js +12 -3
- package/dist/reports/monitors.js +57 -0
- package/dist/reports/upload.js +117 -249
- package/dist/spec/build.js +61 -7
- package/dist/specs/apiVersion.js +38 -0
- package/dist/specs/command.js +210 -13
- package/dist/specs/docs.js +73 -0
- package/dist/specs/pull.js +18 -13
- package/dist/specs/push.js +170 -16
- package/dist/specs/resolve.js +182 -0
- package/dist/specs/servers.js +88 -0
- package/dist/specs/settings.js +48 -0
- package/package.json +1 -1
- package/specs/account.yaml +90 -1
- package/specs/assurance.yaml +229 -1215
- package/specs/specs.yaml +1574 -0
- package/specs/target.yaml +1 -1
package/dist/spec/build.js
CHANGED
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
import { Command } from "commander";
|
|
31
31
|
import { readFileSync } from "node:fs";
|
|
32
|
-
import { loadSpec } from "./loader.js";
|
|
32
|
+
import { loadSpec, } from "./loader.js";
|
|
33
33
|
import { resolveBaseUrl, request } from "../http.js";
|
|
34
34
|
import { resolveAccessToken, resolveEnv } from "../config.js";
|
|
35
35
|
import { printJson } from "../output.js";
|
|
@@ -81,6 +81,38 @@ function group(parent, name) {
|
|
|
81
81
|
parent.addCommand(cmd);
|
|
82
82
|
return cmd;
|
|
83
83
|
}
|
|
84
|
+
/** The parameters of an operation as the spec means them: the path's shared ones and its own, `$ref`s resolved, own wins. */
|
|
85
|
+
function resolveParameters(spec, shared, own) {
|
|
86
|
+
const out = new Map();
|
|
87
|
+
for (const raw of [...(shared ?? []), ...(own ?? [])]) {
|
|
88
|
+
let p;
|
|
89
|
+
if ("$ref" in raw) {
|
|
90
|
+
const name = raw.$ref.replace(/^#\/components\/parameters\//, "");
|
|
91
|
+
p = spec.components?.parameters?.[name];
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
p = raw;
|
|
95
|
+
}
|
|
96
|
+
if (p)
|
|
97
|
+
out.set(`${p.in}:${p.name.toLowerCase()}`, p);
|
|
98
|
+
}
|
|
99
|
+
return [...out.values()];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The `--flag` a header parameter becomes. The active organization (`X-Active-Organization-Id`) is `--org`, the same flag
|
|
103
|
+
* the hand-written `nb specs` verbs take; any other header is its name without the `X-` prefix, in kebab case.
|
|
104
|
+
*/
|
|
105
|
+
export function headerFlag(header) {
|
|
106
|
+
if (header.toLowerCase() === "x-active-organization-id")
|
|
107
|
+
return "org";
|
|
108
|
+
return header.toLowerCase().replace(/^x-/, "");
|
|
109
|
+
}
|
|
110
|
+
/** `personal`, or an organization's id: the only two values the active-organization header takes. */
|
|
111
|
+
function checkOrgValue(raw) {
|
|
112
|
+
if (raw === "personal" || /^[1-9]\d{0,17}$/.test(raw))
|
|
113
|
+
return raw;
|
|
114
|
+
throw new Error(`--org '${raw}' must be 'personal' or an organization id (a number)`);
|
|
115
|
+
}
|
|
84
116
|
function readData(value) {
|
|
85
117
|
const raw = value.startsWith("@") ? readFileSync(value.slice(1), "utf8") : value;
|
|
86
118
|
try {
|
|
@@ -90,16 +122,24 @@ function readData(value) {
|
|
|
90
122
|
throw new Error(`--data must be valid JSON (or @file containing JSON); got: ${value}`);
|
|
91
123
|
}
|
|
92
124
|
}
|
|
93
|
-
function attachLeaf(parent, name, pathTemplate, method, op, servers) {
|
|
125
|
+
function attachLeaf(parent, name, pathTemplate, method, op, servers, parameters, apiName) {
|
|
94
126
|
const leaf = new Command(name);
|
|
95
127
|
leaf.description(op.summary || `${method.toUpperCase()} ${pathTemplate}`);
|
|
96
128
|
const params = pathParams(pathTemplate);
|
|
97
129
|
for (const p of params)
|
|
98
130
|
leaf.argument(`<${p}>`, `path parameter: ${p}`);
|
|
99
|
-
const queryParams =
|
|
131
|
+
const queryParams = parameters.filter((p) => p.in === "query");
|
|
100
132
|
for (const q of queryParams) {
|
|
101
133
|
leaf.option(`--${q.name} <value>`, q.description || `query parameter: ${q.name}`);
|
|
102
134
|
}
|
|
135
|
+
// A header the API wants on the call (the catalog's active organization). A required one has a default, so the
|
|
136
|
+
// command works without the flag; the active organization also reads $NB_<API>_ORG (NB_SPECS_ORG for `nb specs`).
|
|
137
|
+
const headerParams = parameters.filter((p) => p.in === "header" && p.name.toLowerCase() !== "authorization");
|
|
138
|
+
for (const h of headerParams) {
|
|
139
|
+
const flag = headerFlag(h.name);
|
|
140
|
+
const envName = flag === "org" ? `NB_${apiName.toUpperCase()}_ORG` : undefined;
|
|
141
|
+
leaf.option(`--${flag} <value>`, `${h.name} header${flag === "org" ? ": an organization id, or 'personal'" : ""}${h.required ? " (default: personal)" : ""}${envName ? ` (or $${envName})` : ""}`);
|
|
142
|
+
}
|
|
103
143
|
const acceptsBody = method !== "get" && method !== "delete";
|
|
104
144
|
if (acceptsBody || op.requestBody) {
|
|
105
145
|
leaf.option("--data <json>", "request body as JSON (or @file to read from a file)");
|
|
@@ -124,7 +164,15 @@ function attachLeaf(parent, name, pathTemplate, method, op, servers) {
|
|
|
124
164
|
for (const q of queryParams)
|
|
125
165
|
query[q.name] = opts[q.name];
|
|
126
166
|
const body = opts.data !== undefined ? readData(opts.data) : undefined;
|
|
127
|
-
const
|
|
167
|
+
const headers = {};
|
|
168
|
+
for (const h of headerParams) {
|
|
169
|
+
const flag = headerFlag(h.name);
|
|
170
|
+
const fromEnv = flag === "org" ? process.env[`NB_${apiName.toUpperCase()}_ORG`]?.trim() || undefined : undefined;
|
|
171
|
+
const value = opts[flag] ?? fromEnv ?? (h.required && flag === "org" ? "personal" : undefined);
|
|
172
|
+
if (value !== undefined)
|
|
173
|
+
headers[h.name] = flag === "org" ? checkOrgValue(value) : value;
|
|
174
|
+
}
|
|
175
|
+
const res = await request({ baseUrl, path: realPath, method, query, body, token, headers });
|
|
128
176
|
printJson(res.data);
|
|
129
177
|
});
|
|
130
178
|
parent.addCommand(leaf);
|
|
@@ -141,7 +189,13 @@ export function buildApiCommand(api) {
|
|
|
141
189
|
const op = item[method];
|
|
142
190
|
if (!op)
|
|
143
191
|
continue;
|
|
144
|
-
const entry = {
|
|
192
|
+
const entry = {
|
|
193
|
+
chain: commandChain(method, path),
|
|
194
|
+
path,
|
|
195
|
+
method,
|
|
196
|
+
op,
|
|
197
|
+
parameters: resolveParameters(spec, item.parameters, op.parameters),
|
|
198
|
+
};
|
|
145
199
|
const key = entry.chain.join(" ");
|
|
146
200
|
const existing = byChain.get(key);
|
|
147
201
|
if (!existing || pathParams(path).length > pathParams(existing.path).length) {
|
|
@@ -174,12 +228,12 @@ export function buildApiCommand(api) {
|
|
|
174
228
|
byChain.delete(entry.chain.join(" "));
|
|
175
229
|
byChain.set(key, { ...entry, chain: renamed });
|
|
176
230
|
}
|
|
177
|
-
for (const { chain, path, method, op } of byChain.values()) {
|
|
231
|
+
for (const { chain, path, method, op, parameters } of byChain.values()) {
|
|
178
232
|
const leafName = chain[chain.length - 1];
|
|
179
233
|
let parent = root;
|
|
180
234
|
for (const segment of chain.slice(0, -1))
|
|
181
235
|
parent = group(parent, segment);
|
|
182
|
-
attachLeaf(parent, leafName, path, method, op, spec.servers);
|
|
236
|
+
attachLeaf(parent, leafName, path, method, op, spec.servers, parameters, api.name);
|
|
183
237
|
}
|
|
184
238
|
return root;
|
|
185
239
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The API version of a spec (`v1`, `v2`): a property of the SPEC, not of a revision. A new major API version is a new spec; inside
|
|
3
|
+
* a spec the numbered history is the REVISION (what the catalog calls `version`, and this CLI calls a revision).
|
|
4
|
+
*
|
|
5
|
+
* The same derivation as nb-specs-api's `apiVersionOf`, so `nb specs specs push` knows before sending which spec a document
|
|
6
|
+
* belongs to: the document's `info.version`, trimmed, must match `^[vV]?(\d{1,3})(\.\d+){0,2}([-+][0-9A-Za-z.+-]*)?$`, and the
|
|
7
|
+
* API version is `v<major>` with leading zeros dropped. `1.8.0` -> `v1`, `v2.0` -> `v2`, `1.0.0-rc.1` -> `v1`, `007.1` -> `v7`;
|
|
8
|
+
* `2023-01`, `2023.1`, `latest` and `1.x` have no major (they need `--api-version`).
|
|
9
|
+
*/
|
|
10
|
+
import { parse } from "yaml";
|
|
11
|
+
const MAJOR = /^[vV]?(\d{1,3})(\.\d+){0,2}([-+][0-9A-Za-z.+-]*)?$/;
|
|
12
|
+
/** The API version an `info.version` gives, or null when it has no major. */
|
|
13
|
+
export function apiVersionFromInfoVersion(infoVersion) {
|
|
14
|
+
const m = MAJOR.exec(infoVersion.trim());
|
|
15
|
+
return m ? `v${Number(m[1])}` : null;
|
|
16
|
+
}
|
|
17
|
+
/** The API version a document's `info.version` gives, or null (not parseable, no `info.version`, or no major in it). */
|
|
18
|
+
export function apiVersionOf(text) {
|
|
19
|
+
try {
|
|
20
|
+
const doc = parse(text);
|
|
21
|
+
const v = doc?.info?.version;
|
|
22
|
+
// YAML reads `version: 1.0` as the number 1: the text the author wrote is what the server reads, so a number is its plain text.
|
|
23
|
+
return typeof v === "string" || typeof v === "number" ? apiVersionFromInfoVersion(String(v)) : null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const LABEL = /^[A-Za-z0-9._-]{1,32}$/;
|
|
30
|
+
/** `--api-version`: the same label rule as the catalog (letters, digits, '.', '_', '-', up to 32). Returned trimmed. */
|
|
31
|
+
export function checkApiVersion(raw) {
|
|
32
|
+
const v = raw.trim();
|
|
33
|
+
if (!LABEL.test(v))
|
|
34
|
+
throw new Error(`--api-version '${raw}' must be a version label: letters, digits, '.', '_' and '-' (up to 32), e.g. v1 or v2`);
|
|
35
|
+
return v;
|
|
36
|
+
}
|
|
37
|
+
/** Whether two API versions are the same one (the catalog compares them ignoring case). */
|
|
38
|
+
export const sameApiVersion = (a, b) => (a ?? "").toLowerCase() === (b ?? "").toLowerCase();
|
package/dist/specs/command.js
CHANGED
|
@@ -1,24 +1,37 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `nb specs` - the API catalog (your own OpenAPI documents)
|
|
3
|
-
*
|
|
2
|
+
* `nb specs` - repositories and the API catalog (your own OpenAPI documents). The tree is generated from the contract like
|
|
3
|
+
* every other group (`nb specs specs list`, `nb specs repositories get <id>`, `nb specs groups ...`); the verbs a pipeline
|
|
4
|
+
* wants and the contract cannot express are hand-written and attached to it by `attachSpecsCommands`: `specs push`,
|
|
5
|
+
* `specs pull`, `specs settings` and `repositories upsert`. Each sub-menu of the Evolution screen API management has one resource:
|
|
6
|
+
* Repository Management = `nb specs repositories` (provider, name, component and the one repository setting, `--attachments`),
|
|
7
|
+
* Spec Management = `nb specs specs` (the spec, its description document `docs push|pull|delete`, and, since 2026-11-10, its public badge and report with their links). The key of a spec is its group, its repository row, its API version (v1, v2: a new major version is a new spec) and its name (an environment is a group); the numbered history inside a spec is its revisions. The old direct form (`nb specs push|pull|versions`) stays as hidden aliases.
|
|
4
8
|
*/
|
|
5
|
-
import { writeFileSync } from "node:fs";
|
|
9
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
6
10
|
import { Command } from "commander";
|
|
7
11
|
import { resolveAccessToken, resolveEnv } from "../config.js";
|
|
8
12
|
import { exportGithubOutput, printJson } from "../output.js";
|
|
9
13
|
import { detectCi } from "../reports/ci.js";
|
|
14
|
+
import { docsDelete, docsPull, docsPush } from "./docs.js";
|
|
10
15
|
import { parseHash, parseVersion, pullSpec, specVersions } from "./pull.js";
|
|
11
|
-
import {
|
|
16
|
+
import { checkServerUrl } from "./servers.js";
|
|
17
|
+
import { checkOrg, checkProvider, ciNote, pushSpec, specsBaseUrl, upsertRepository } from "./push.js";
|
|
18
|
+
import { onOff, parseSettingsFlags, updateSpecSettings } from "./settings.js";
|
|
12
19
|
export function buildPushCommand() {
|
|
13
20
|
return new Command("push")
|
|
14
|
-
.description("Register an OpenAPI file in the API catalog: a new spec, or a new
|
|
21
|
+
.description("Register an OpenAPI file in the API catalog: a new spec, or a new revision when its content changed. Safe to run on every commit: a file that is already the latest revision uploads nothing")
|
|
15
22
|
.requiredOption("--file <path>", "the OpenAPI document (YAML or JSON, up to 2 MiB)")
|
|
16
23
|
.option("--name <name>", "the spec's name in the catalog (default: the document's info.title, then the file's name)")
|
|
17
24
|
.option("--id <id>", "push to this spec by id: a rename cannot make a second one")
|
|
18
25
|
.option("--rename", "with --id: also rename the spec to --name (default: the document's info.title) when it is called something else")
|
|
19
|
-
.option("--group <name>", "
|
|
26
|
+
.option("--group <name>", "the spec's group, part of its key (the same name may exist in other groups: an environment each): the spec is looked up in this group, and a NEW one is filed there (the group is made when missing). Default: no group, which does not mean any group: a name that exists only in groups is an error that lists them. An existing spec is never moved by a push")
|
|
27
|
+
.option("--api-version <v>", "the spec's API version (v1, v2), part of its key: a new major API version is a new spec. Default: what the document's info.version gives (1.8.0 -> v1, v2.0 -> v2); needed when it gives none (2023-01, latest). A document of another major than an existing spec of that name makes the NEW spec for its API version and leaves the other alone")
|
|
28
|
+
.option("--server-url <url>", "replace the document's top-level `servers` with this one URL before sending (the environment's URL): one OpenAPI file in the repository, one spec per environment. A YAML file is edited as text (comments and order kept) when that can be proven safe, otherwise written again; the contract hash ignores `servers`, so the contract's identity does not change")
|
|
20
29
|
.option("--description <text>", "a new spec's description")
|
|
21
|
-
.option("--note <text>", "what changed, shown in the
|
|
30
|
+
.option("--note <text>", "what changed, shown in the revision list (default: the commit, branch and CI run)")
|
|
31
|
+
.option("--repository-id <id>", "tie the spec to this repository (the id `nb specs repositories upsert` printed; default: $NB_REPOSITORY_ID). A new spec is created tied to it; a spec with no repository is tied to it; one tied to another repository is left there")
|
|
32
|
+
.option("--repository <name>", "tie the spec to the repository of this name (owner/name): it is registered first, idempotently, and its id used. Instead of --repository-id")
|
|
33
|
+
.option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
|
|
34
|
+
.option("--component <name>", "with --repository: the part of the repository the spec belongs to (account-api, web...); part of the repository's key. Default: none = the repository as a whole")
|
|
22
35
|
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
|
|
23
36
|
.option("--dry-run", "read the catalog and say what would happen; write nothing")
|
|
24
37
|
.action(async (_flags, command) => {
|
|
@@ -31,18 +44,40 @@ export function buildPushCommand() {
|
|
|
31
44
|
file: opts.file,
|
|
32
45
|
name: opts.name,
|
|
33
46
|
group: opts.group,
|
|
47
|
+
apiVersion: opts.apiVersion,
|
|
48
|
+
serverUrl: opts.serverUrl !== undefined ? checkServerUrl(opts.serverUrl) : undefined,
|
|
34
49
|
description: opts.description,
|
|
35
50
|
note: opts.note ?? ciNote(ci, undefined),
|
|
36
51
|
id: opts.id,
|
|
37
52
|
rename: opts.rename,
|
|
53
|
+
// A name asked for wins over the id the pipeline's variable carries.
|
|
54
|
+
repositoryId: opts.repository ? undefined : (opts.repositoryId ?? (process.env.NB_REPOSITORY_ID?.trim() || undefined)),
|
|
55
|
+
repository: opts.repository,
|
|
56
|
+
provider: opts.repository ? checkProvider(opts.provider) : undefined,
|
|
57
|
+
component: opts.repository ? opts.component?.trim() || undefined : undefined,
|
|
38
58
|
dryRun: opts.dryRun,
|
|
39
59
|
});
|
|
40
60
|
printJson(result);
|
|
41
61
|
exportGithubOutput("spec_id", result.id);
|
|
42
|
-
|
|
62
|
+
if (result.repository_id && result.repository_id !== "(new)")
|
|
63
|
+
exportGithubOutput("repository_id", result.repository_id);
|
|
64
|
+
if (result.repository_kept) {
|
|
65
|
+
process.stderr.write(`! ${result.name} is tied to another repository (${result.repository_kept}); a push never moves a spec, so it was left there\n`);
|
|
66
|
+
}
|
|
67
|
+
if (result.servers_edit === "reserialised")
|
|
68
|
+
process.stderr.write("! --server-url: the YAML file was written again (its comments are not kept in what was pushed); the file on disk is unchanged\n");
|
|
69
|
+
const what = { created: `created (${result.api_version}, rev ${result.version})`, new_version: `new revision ${result.version} of ${result.api_version}`, unchanged: `unchanged (already rev ${result.version} of ${result.api_version}: nothing uploaded)` }[result.action];
|
|
43
70
|
process.stderr.write(`${opts.dryRun ? "(dry run) " : ""}✓ ${result.renamed_from ? `${result.renamed_from} renamed to ` : ""}${result.name} -> ${what}\n`);
|
|
44
71
|
});
|
|
45
72
|
}
|
|
73
|
+
/** The group / repository / API version part of a spec's key, from the options (all absent = the name alone, as before). */
|
|
74
|
+
function whereOf(opts) {
|
|
75
|
+
if (opts.repository === undefined && opts.group === undefined && opts.component === undefined && opts.provider === undefined && opts.apiVersion === undefined)
|
|
76
|
+
return undefined;
|
|
77
|
+
if (opts.repository === undefined && (opts.component !== undefined || opts.provider !== undefined))
|
|
78
|
+
throw new Error("--component and --provider need --repository");
|
|
79
|
+
return { group: opts.group, repository: opts.repository, component: opts.component, apiVersion: opts.apiVersion, provider: opts.repository ? checkProvider(opts.provider) : undefined };
|
|
80
|
+
}
|
|
46
81
|
async function connection(opts) {
|
|
47
82
|
const env = opts.env || resolveEnv();
|
|
48
83
|
const token = opts.token || (await resolveAccessToken());
|
|
@@ -53,7 +88,12 @@ export function buildPullCommand() {
|
|
|
53
88
|
.description("Read a version of a spec's document out of the API catalog, exactly as it was uploaded, and check its SHA-256. For a pipeline that works from the catalog's document (a contract test, a client generator)")
|
|
54
89
|
.option("--id <id>", "the spec, by id (a rename cannot change it)")
|
|
55
90
|
.option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
|
|
56
|
-
.option("--
|
|
91
|
+
.option("--group <name>", "with --name: the group the spec is in (part of its key); none = no group")
|
|
92
|
+
.option("--api-version <v>", "with --name: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
|
|
93
|
+
.option("--repository <owner/name>", "with --name: the repository the spec is tied to (part of its key); none = a spec tied to no repository")
|
|
94
|
+
.option("--component <name>", "with --repository: the component part of its key (none = the repository as a whole)")
|
|
95
|
+
.option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
|
|
96
|
+
.option("--spec-version <n|latest>", "the catalog's revision number (1, 2, 3...), not the API's v1 / v2 and not the CLI's own --version. Default: latest. Pin a number in a pipeline: 'latest' moves")
|
|
57
97
|
.option("--hash <sha256>", "the SHA-256 the document must have (as 'nb specs versions' prints it): the pull fails when it differs")
|
|
58
98
|
.option("--out <file>", "write the document here (default: to standard output, the details to standard error)")
|
|
59
99
|
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
|
|
@@ -63,6 +103,7 @@ export function buildPullCommand() {
|
|
|
63
103
|
conn: await connection(opts),
|
|
64
104
|
id: opts.id,
|
|
65
105
|
name: opts.name,
|
|
106
|
+
where: whereOf(opts),
|
|
66
107
|
version: parseVersion(opts.specVersion),
|
|
67
108
|
hash: parseHash(opts.hash),
|
|
68
109
|
});
|
|
@@ -82,23 +123,179 @@ export function buildPullCommand() {
|
|
|
82
123
|
exportGithubOutput("spec_id", result.id);
|
|
83
124
|
exportGithubOutput("spec_version", String(result.version));
|
|
84
125
|
exportGithubOutput("spec_hash", result.content_hash);
|
|
85
|
-
process.stderr.write(`✓ ${result.name}
|
|
126
|
+
process.stderr.write(`✓ ${result.name} rev ${result.version} (sha256 ${result.content_hash.slice(0, 12)}..., ${result.size_bytes} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
|
|
86
127
|
});
|
|
87
128
|
}
|
|
88
129
|
export function buildVersionsCommand() {
|
|
89
130
|
return new Command("versions")
|
|
90
|
-
.description("List the
|
|
131
|
+
.description("List the revisions of a spec in the API catalog, newest first, each with the SHA-256 of its document (what 'nb specs pull --hash' pins)")
|
|
91
132
|
.option("--id <id>", "the spec, by id")
|
|
92
133
|
.option("--name <name>", "the spec, by its name in the catalog (matched ignoring case)")
|
|
134
|
+
.option("--group <name>", "with --name: the group the spec is in (part of its key); none = no group")
|
|
135
|
+
.option("--api-version <v>", "with --name: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
|
|
136
|
+
.option("--repository <owner/name>", "with --name: the repository the spec is tied to (part of its key); none = a spec tied to no repository")
|
|
137
|
+
.option("--component <name>", "with --repository: the component part of its key (none = the repository as a whole)")
|
|
138
|
+
.option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
|
|
93
139
|
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
|
|
94
140
|
.action(async (_flags, command) => {
|
|
95
141
|
const opts = command.optsWithGlobals();
|
|
96
|
-
const result = await specVersions({ conn: await connection(opts), id: opts.id, name: opts.name });
|
|
142
|
+
const result = await specVersions({ conn: await connection(opts), id: opts.id, name: opts.name, where: whereOf(opts) });
|
|
97
143
|
printJson(result);
|
|
98
144
|
const latest = result.versions[0];
|
|
99
|
-
process.stderr.write(`✓ ${result.name}: ${result.versions.length}
|
|
145
|
+
process.stderr.write(`✓ ${result.name}: ${result.versions.length} revision${result.versions.length === 1 ? "" : "s"}${latest ? ` (latest rev ${latest.version})` : ""}\n`);
|
|
100
146
|
});
|
|
101
147
|
}
|
|
148
|
+
/** The spec a `docs` verb is about: `--spec-id` (default $NB_SPEC_ID), or `--spec` with the optional repository / component / group. */
|
|
149
|
+
function docsRefOf(opts) {
|
|
150
|
+
const byNames = [opts.spec, opts.repository, opts.component, opts.group, opts.apiVersion].some((v) => v !== undefined && v.trim() !== "");
|
|
151
|
+
if (opts.specId !== undefined && byNames)
|
|
152
|
+
throw new Error("--spec-id names the spec by itself: do not combine it with --spec, --repository, --component, --group or --api-version");
|
|
153
|
+
if (byNames)
|
|
154
|
+
return { spec: opts.spec, repository: opts.repository, component: opts.component, group: opts.group, apiVersion: opts.apiVersion, provider: opts.provider };
|
|
155
|
+
const specId = (opts.specId ?? process.env.NB_SPEC_ID)?.trim();
|
|
156
|
+
if (specId)
|
|
157
|
+
return { specId };
|
|
158
|
+
throw new Error("Say which spec: --spec-id <id> (or set NB_SPEC_ID), or --spec <name> [--repository <name> [--component <name>]] [--group <name>]");
|
|
159
|
+
}
|
|
160
|
+
function withSpecOptions(cmd) {
|
|
161
|
+
return cmd
|
|
162
|
+
.option("--spec-id <id>", "the spec, by its id in the catalog (default: $NB_SPEC_ID). Exclusive with the names below")
|
|
163
|
+
.option("--spec <name>", "by names: the spec's name")
|
|
164
|
+
.option("--repository <owner/name>", "by names: the repository the spec is tied to; none = a spec tied to no repository")
|
|
165
|
+
.option("--component <name>", "by names, with --repository: the component part of its key (none = the repository as a whole)")
|
|
166
|
+
.option("--group <name>", "by names: the group the spec is filed in; none = a spec in no group (not any group)")
|
|
167
|
+
.option("--api-version <v>", "by names: the spec's API version (v1, v2), part of its key; left out = the API version of the one spec the rest of the key matches (several: the error lists them)")
|
|
168
|
+
.option("--provider <provider>", "with --repository: github | gitlab | bitbucket | other (default: github)")
|
|
169
|
+
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)");
|
|
170
|
+
}
|
|
171
|
+
export function buildDocsCommand() {
|
|
172
|
+
const docs = new Command("docs").description("The spec's description document: ONE Markdown file per spec (up to 200 KiB), shown rendered in the catalog, like a developer portal's overview page");
|
|
173
|
+
docs.addCommand(withSpecOptions(new Command("push").description("Upload a Markdown file as the spec's description document (replaces the one it has)").requiredOption("--file <path>", "the Markdown file (up to 200 KiB, UTF-8)")).action(async (_flags, command) => {
|
|
174
|
+
const opts = command.optsWithGlobals();
|
|
175
|
+
const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
|
|
176
|
+
const result = await docsPush({ conn: await connection(opts), ref, file: opts.file });
|
|
177
|
+
printJson(result);
|
|
178
|
+
exportGithubOutput("spec_id", result.spec_id);
|
|
179
|
+
process.stderr.write(`✓ ${result.spec_name}: description document ${result.created ? "added" : "replaced"} (${result.size_bytes} bytes)\n`);
|
|
180
|
+
}));
|
|
181
|
+
docs.addCommand(withSpecOptions(new Command("pull").description("Print the spec's description document (or write it with --out)").option("--out <file>", "write the document here (default: standard output)")).action(async (_flags, command) => {
|
|
182
|
+
const opts = command.optsWithGlobals();
|
|
183
|
+
const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
|
|
184
|
+
const result = await docsPull({ conn: await connection(opts), ref });
|
|
185
|
+
if (opts.out) {
|
|
186
|
+
try {
|
|
187
|
+
writeFileSync(opts.out, result.text);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
throw new Error(`--out: cannot write ${opts.out}: ${err.message}`);
|
|
191
|
+
}
|
|
192
|
+
printJson({ spec_id: result.spec_id, spec_name: result.spec_name, out: opts.out });
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
process.stdout.write(result.text);
|
|
196
|
+
}
|
|
197
|
+
process.stderr.write(`✓ ${result.spec_name}: description document (${Buffer.byteLength(result.text, "utf8")} bytes)${opts.out ? ` -> ${opts.out}` : ""}\n`);
|
|
198
|
+
}));
|
|
199
|
+
docs.addCommand(withSpecOptions(new Command("delete").description("Remove the spec's description document (safe when there is none)")).action(async (_flags, command) => {
|
|
200
|
+
const opts = command.optsWithGlobals();
|
|
201
|
+
const ref = docsRefOf({ ...opts, provider: opts.repository ? checkProvider(opts.provider) : undefined });
|
|
202
|
+
const result = await docsDelete({ conn: await connection(opts), ref });
|
|
203
|
+
printJson(result);
|
|
204
|
+
process.stderr.write(`✓ ${result.spec_name}: description document removed\n`);
|
|
205
|
+
}));
|
|
206
|
+
return docs;
|
|
207
|
+
}
|
|
208
|
+
export function buildUpsertCommand() {
|
|
209
|
+
return new Command("upsert")
|
|
210
|
+
.description("Register a repository by provider and name and print it, with the id the catalog issued for it. Safe to repeat: the same repository always answers the same id (and nothing set on a screen is overwritten). Run it once by hand, then give the id to the pipeline as NB_REPOSITORY_ID")
|
|
211
|
+
.requiredOption("--name <name>", "the repository: owner/name for github, gitlab and bitbucket; any text for 'other' (a delivery that is not in git)")
|
|
212
|
+
.option("--provider <provider>", "github | gitlab | bitbucket | other (default: github)")
|
|
213
|
+
.option("--component <name>", "the part of the repository (account-api, web...), at most 100 characters; with the provider and the name it is the key, and one id says which repository AND which component. Default: none = the repository as a whole")
|
|
214
|
+
.option("--attachments <on|off>", "a result of this repository may carry the original test report (kept in R2); applied only when this call registers the repository, an existing one is left as it is (change it with `repositories update --attachments`)")
|
|
215
|
+
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
|
|
216
|
+
.action(async (_flags, command) => {
|
|
217
|
+
const opts = command.optsWithGlobals();
|
|
218
|
+
const attachments = opts.attachments === undefined ? undefined : onOff("--attachments", opts.attachments);
|
|
219
|
+
const repo = await upsertRepository(await connection(opts), checkProvider(opts.provider), opts.name.trim(), opts.component?.trim() ?? "", attachments);
|
|
220
|
+
const { created, ...row } = repo;
|
|
221
|
+
printJson(row);
|
|
222
|
+
exportGithubOutput("repository_id", repo.id);
|
|
223
|
+
process.stderr.write(`✓ ${repo.provider} ${repo.name}${repo.component ? ` / ${repo.component}` : ""} -> ${repo.id} (${created ? "registered" : "already registered"})\n`);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
export function buildSettingsCommand() {
|
|
227
|
+
return new Command("settings")
|
|
228
|
+
.description("Change a spec's public settings (the Spec screen's public badge and report with their links), and print the spec. Only the flags you pass change; the rest is left as it is. Attachments are the repository's: `nb specs repositories update --attachments`")
|
|
229
|
+
.argument("<id>", "the spec's id")
|
|
230
|
+
.option("--public-badge <on|off>", "the quality badge is readable without a login while it is on")
|
|
231
|
+
.option("--report-access <hidden|login|public>", "who may read the quality report: nobody, anyone signed in with the link, or anyone with the link")
|
|
232
|
+
.option("--rotate-quality-public-id", "issue a new token for the public badge and report links: every old link stops working")
|
|
233
|
+
.option("--org <id>", "the organization whose catalog it is (an id), or 'personal' (default; or $NB_SPECS_ORG)")
|
|
234
|
+
.action(async (id, _flags, command) => {
|
|
235
|
+
const opts = command.optsWithGlobals();
|
|
236
|
+
const patch = parseSettingsFlags(opts);
|
|
237
|
+
const spec = await updateSpecSettings(await connection(opts), id, patch);
|
|
238
|
+
printJson(spec);
|
|
239
|
+
process.stderr.write(`✓ ${spec.name}: ${Object.keys(patch).join(", ")} updated\n`);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The generated `repositories update` takes the whole body as `--data`; this adds `--attachments <on|off>` to it (the repository's
|
|
244
|
+
* one setting) and puts `attachments_enabled` into the body just before the generated action sends it. Without the flag the body
|
|
245
|
+
* is sent as it is.
|
|
246
|
+
*/
|
|
247
|
+
export function attachRepositoryAttachments(repositories) {
|
|
248
|
+
const leaf = repositories.commands.find((c) => c.name() === "update");
|
|
249
|
+
if (!leaf)
|
|
250
|
+
return;
|
|
251
|
+
leaf.option("--attachments <on|off>", "a result of this repository may carry the original test report (kept in R2); merged into --data as attachments_enabled");
|
|
252
|
+
leaf.hook("preAction", (thisCommand) => {
|
|
253
|
+
const opts = thisCommand.optsWithGlobals();
|
|
254
|
+
if (opts.attachments === undefined)
|
|
255
|
+
return;
|
|
256
|
+
const attachments = onOff("--attachments", opts.attachments);
|
|
257
|
+
let body = {};
|
|
258
|
+
if (opts.data !== undefined) {
|
|
259
|
+
const raw = opts.data.startsWith("@") ? readFileSync(opts.data.slice(1), "utf8") : opts.data;
|
|
260
|
+
try {
|
|
261
|
+
const parsed = JSON.parse(raw);
|
|
262
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
263
|
+
throw new Error("not an object");
|
|
264
|
+
body = parsed;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
throw new Error(`--data must be a JSON object (or @file containing one); got: ${opts.data}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
thisCommand.setOptionValue("data", JSON.stringify({ ...body, attachments_enabled: attachments }));
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
/** The hand-written verbs on the generated `specs` group, in the same `<resource> <verb>` shape as the rest of the tree. */
|
|
274
|
+
export function attachSpecsCommands(group) {
|
|
275
|
+
const child = (name) => {
|
|
276
|
+
const existing = group.commands.find((c) => c.name() === name);
|
|
277
|
+
if (existing)
|
|
278
|
+
return existing;
|
|
279
|
+
const made = new Command(name).description(`${name} commands`);
|
|
280
|
+
group.addCommand(made);
|
|
281
|
+
return made;
|
|
282
|
+
};
|
|
283
|
+
const specsResource = child("specs");
|
|
284
|
+
// The contract's docs routes generate a `docs` leaf (a JSON body for PUT): the description document is Markdown, so the hand-written
|
|
285
|
+
// `docs push|pull|delete` group takes its place.
|
|
286
|
+
const generated = specsResource.commands.findIndex((c) => c.name() === "docs");
|
|
287
|
+
if (generated >= 0)
|
|
288
|
+
specsResource.commands.splice(generated, 1);
|
|
289
|
+
specsResource.addCommand(buildPushCommand()).addCommand(buildPullCommand()).addCommand(buildSettingsCommand()).addCommand(buildDocsCommand());
|
|
290
|
+
child("repositories").addCommand(buildUpsertCommand());
|
|
291
|
+
attachRepositoryAttachments(child("repositories"));
|
|
292
|
+
// The old direct form (`nb specs push`) keeps working for pipelines already written that way; it is not advertised.
|
|
293
|
+
group.addCommand(buildPushCommand(), { hidden: true });
|
|
294
|
+
group.addCommand(buildPullCommand(), { hidden: true });
|
|
295
|
+
group.addCommand(buildVersionsCommand(), { hidden: true });
|
|
296
|
+
return group;
|
|
297
|
+
}
|
|
298
|
+
/** The old standalone `nb specs push|pull|versions` group, as it was before the tree was generated (the tests drive it). */
|
|
102
299
|
export function buildSpecsCommand() {
|
|
103
300
|
return new Command("specs")
|
|
104
301
|
.description("The API catalog: your own OpenAPI documents (NASEBANAL Evolution)")
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nb specs specs docs push|pull|delete`: the description document of a spec (Kong Dev Portal style): ONE Markdown file per spec,
|
|
3
|
+
* shown rendered in the catalog beside the API reference. The catalog keeps it as text (`PUT|GET|DELETE /specs/{id}/docs`, at most
|
|
4
|
+
* 200 KiB of UTF-8). The spec is named like everywhere else: `--spec-id`, or `--spec <name>` with the optional `--repository`
|
|
5
|
+
* [`--component`] and `--group` (what is left out means none: a spec in no group, tied to no repository).
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, statSync, existsSync } from "node:fs";
|
|
8
|
+
import { ApiError, request } from "../http.js";
|
|
9
|
+
import { envTokenHint } from "../output.js";
|
|
10
|
+
import { headersOf, reasonOf } from "./push.js";
|
|
11
|
+
import { locateSpec } from "./resolve.js";
|
|
12
|
+
/** The catalog takes a description document up to this size (200 KiB); the CLI refuses a larger one before sending anything. */
|
|
13
|
+
export const MAX_DOCS_BYTES = 200 * 1024;
|
|
14
|
+
/** The Markdown file: it must exist, be a file, be non-empty, at most 200 KiB, valid text (no NUL byte). */
|
|
15
|
+
export function readDocsFile(file) {
|
|
16
|
+
if (!existsSync(file))
|
|
17
|
+
throw new Error(`--file: not found: ${file}`);
|
|
18
|
+
const stat = statSync(file);
|
|
19
|
+
if (!stat.isFile())
|
|
20
|
+
throw new Error(`--file: ${file} is not a file`);
|
|
21
|
+
if (stat.size === 0)
|
|
22
|
+
throw new Error(`--file: ${file} is empty`);
|
|
23
|
+
if (stat.size > MAX_DOCS_BYTES)
|
|
24
|
+
throw new Error(`--file: ${file} is ${(stat.size / 1024).toFixed(0)} KiB, more than the ${MAX_DOCS_BYTES / 1024} KiB the catalog takes for a description document`);
|
|
25
|
+
const bytes = readFileSync(file);
|
|
26
|
+
if (bytes.includes(0))
|
|
27
|
+
throw new Error(`--file: ${file} is not a text file (it contains a NUL byte): a description document is Markdown`);
|
|
28
|
+
return { text: bytes.toString("utf8"), bytes };
|
|
29
|
+
}
|
|
30
|
+
async function catalog(what, run) {
|
|
31
|
+
try {
|
|
32
|
+
return await run();
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (err instanceof ApiError) {
|
|
36
|
+
const hint = err.status === 401 ? envTokenHint() : null;
|
|
37
|
+
const reason = err.status === 413 ? `the document is larger than ${MAX_DOCS_BYTES / 1024} KiB` : err.status === 415 ? "the catalog takes Markdown only (text/markdown)" : reasonOf(err);
|
|
38
|
+
throw new Error(`The catalog refused ${what}: ${reason}${hint ? `\n${hint}` : ""}`);
|
|
39
|
+
}
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const pathOf = (id) => `/api/v1/specs/${encodeURIComponent(id)}/docs`;
|
|
44
|
+
export async function docsPush(p) {
|
|
45
|
+
const { bytes } = readDocsFile(p.file);
|
|
46
|
+
return catalog("the description document", async () => {
|
|
47
|
+
const { spec } = await locateSpec(p.conn, p.ref);
|
|
48
|
+
const res = await request({ ...headersOf(p.conn), method: "PUT", path: pathOf(spec.id), rawBody: new Uint8Array(bytes), contentType: "text/markdown; charset=utf-8" });
|
|
49
|
+
const data = res.data.data;
|
|
50
|
+
return { spec_id: spec.id, spec_name: spec.name, size_bytes: data?.size_bytes ?? bytes.length, updated_at: data?.updated_at, created: res.status === 201 };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export async function docsPull(p) {
|
|
54
|
+
return catalog("the request", async () => {
|
|
55
|
+
const { spec } = await locateSpec(p.conn, p.ref);
|
|
56
|
+
try {
|
|
57
|
+
const res = await request({ ...headersOf(p.conn), method: "GET", path: pathOf(spec.id), headers: { ...headersOf(p.conn).headers, Accept: "text/markdown" }, raw: true });
|
|
58
|
+
return { spec_id: spec.id, spec_name: spec.name, text: res.data };
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
if (err instanceof ApiError && err.status === 404)
|
|
62
|
+
throw new Error(`The spec '${spec.name}' has no description document (push one with 'nb specs specs docs push --file README.md').`);
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
export async function docsDelete(p) {
|
|
68
|
+
return catalog("the request", async () => {
|
|
69
|
+
const { spec } = await locateSpec(p.conn, p.ref);
|
|
70
|
+
await request({ ...headersOf(p.conn), method: "DELETE", path: pathOf(spec.id) });
|
|
71
|
+
return { spec_id: spec.id, spec_name: spec.name };
|
|
72
|
+
});
|
|
73
|
+
}
|
package/dist/specs/pull.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `nb specs pull` / `nb specs versions` - read a document back out of the API catalog (nb-specs-api), the other half of
|
|
3
|
-
* `nb specs push`: a pipeline asks the catalog for a given
|
|
3
|
+
* `nb specs push`: a pipeline asks the catalog for a given revision of an API's document and works from that (a contract
|
|
4
4
|
* test with Specmatic, a client generator) instead of from a copy that lives in some repository.
|
|
5
5
|
*
|
|
6
6
|
* - a spec is named by `--id` (what a rename cannot change) or by `--name` (matched ignoring case, like push)
|
|
7
|
-
* - `--spec-version` is the catalog's
|
|
8
|
-
* not the API's
|
|
7
|
+
* - `--spec-version` is the catalog's REVISION number (1, 2, 3...: one per `nb specs push` that changed the document),
|
|
8
|
+
* not the API's version (`v1`, `v2`: a property of the spec) and not the document's own `info.version`; absent or `latest` = the newest
|
|
9
9
|
* - the document comes back exactly as it was uploaded (the bytes, not a re-serialised copy), and its SHA-256 is
|
|
10
10
|
* checked against the `content_hash` the catalog keeps for that version; `--hash` pins what a pipeline expects, so
|
|
11
11
|
* a version that was swapped, or a name that now points somewhere else, fails instead of testing the wrong thing
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import { ApiError, request } from "../http.js";
|
|
14
14
|
import { envTokenHint } from "../output.js";
|
|
15
15
|
import { findSpec, hashText, headersOf, reasonOf } from "./push.js";
|
|
16
|
+
import { locateSpec } from "./resolve.js";
|
|
16
17
|
/** `--spec-version`: a positive whole number, or `latest` (or nothing) for the newest. Returns undefined for the newest. */
|
|
17
18
|
export function parseVersion(raw) {
|
|
18
19
|
const v = raw?.trim();
|
|
@@ -20,7 +21,7 @@ export function parseVersion(raw) {
|
|
|
20
21
|
return undefined;
|
|
21
22
|
if (/^[1-9]\d{0,8}$/.test(v))
|
|
22
23
|
return Number(v);
|
|
23
|
-
throw new Error(`--spec-version '${raw}' must be a
|
|
24
|
+
throw new Error(`--spec-version '${raw}' must be a revision number (1, 2, 3...) or 'latest'. It is the catalog's revision, not the API's v1 / v2`);
|
|
24
25
|
}
|
|
25
26
|
/** `--hash`: 64 hex characters (case does not matter). Returns it lower-cased, or undefined when none was asked. */
|
|
26
27
|
export function parseHash(raw) {
|
|
@@ -44,9 +45,13 @@ async function refusal(what, run) {
|
|
|
44
45
|
throw err;
|
|
45
46
|
}
|
|
46
47
|
}
|
|
47
|
-
async function resolveSpec(conn, id, name) {
|
|
48
|
+
async function resolveSpec(conn, id, name, where) {
|
|
48
49
|
if (!id && !name?.trim())
|
|
49
50
|
throw new Error("Say which spec: --id <id> or --name <name> (the name is the spec's title in the catalog)");
|
|
51
|
+
if (!id && where && (where.group || where.repository || where.apiVersion)) {
|
|
52
|
+
const hit = await locateSpec(conn, { spec: name.trim(), ...where });
|
|
53
|
+
return { id: hit.spec.id, name: hit.spec.name, group_id: hit.spec.group_id ?? null, repository_id: hit.spec.repository_id ?? null, latest_version: 0 };
|
|
54
|
+
}
|
|
50
55
|
const spec = await findSpec(conn, name?.trim() ?? "", id);
|
|
51
56
|
if (!spec) {
|
|
52
57
|
throw new Error(`No spec named '${name}' in the catalog (names match ignoring case; check --org: the catalog is per owner, and 'nb specs versions' needs the exact name or the id).`);
|
|
@@ -57,23 +62,23 @@ async function listVersions(conn, spec) {
|
|
|
57
62
|
const res = await request({ ...headersOf(conn), method: "GET", path: `/api/v1/specs/${encodeURIComponent(spec.id)}/versions` });
|
|
58
63
|
return res.data.data.data;
|
|
59
64
|
}
|
|
60
|
-
/** The
|
|
65
|
+
/** The revisions of a spec, newest first, each with the SHA-256 of its document (what `--hash` pins). */
|
|
61
66
|
export async function specVersions(p) {
|
|
62
67
|
return refusal("the request", async () => {
|
|
63
|
-
const spec = await resolveSpec(p.conn, p.id, p.name);
|
|
68
|
+
const spec = await resolveSpec(p.conn, p.id, p.name, p.where);
|
|
64
69
|
return { id: spec.id, name: spec.name, versions: await listVersions(p.conn, spec) };
|
|
65
70
|
});
|
|
66
71
|
}
|
|
67
|
-
/** A
|
|
72
|
+
/** A revision's document exactly as uploaded, verified against the catalog's hash (and `--hash`). */
|
|
68
73
|
export async function pullSpec(p) {
|
|
69
74
|
return refusal("the request", async () => {
|
|
70
|
-
const spec = await resolveSpec(p.conn, p.id, p.name);
|
|
75
|
+
const spec = await resolveSpec(p.conn, p.id, p.name, p.where);
|
|
71
76
|
const versions = await listVersions(p.conn, spec);
|
|
72
77
|
if (versions.length === 0)
|
|
73
|
-
throw new Error(`Spec '${spec.name}' has no
|
|
78
|
+
throw new Error(`Spec '${spec.name}' has no revisions.`);
|
|
74
79
|
const picked = p.version === undefined ? versions[0] : versions.find((v) => v.version === p.version);
|
|
75
80
|
if (!picked) {
|
|
76
|
-
throw new Error(`Spec '${spec.name}' has no
|
|
81
|
+
throw new Error(`Spec '${spec.name}' has no revision ${p.version} (it has ${versions.map((v) => v.version).join(", ")}). The revision is the catalog's number: 'nb specs versions' lists them.`);
|
|
77
82
|
}
|
|
78
83
|
const res = await request({
|
|
79
84
|
...headersOf(p.conn),
|
|
@@ -85,11 +90,11 @@ export async function pullSpec(p) {
|
|
|
85
90
|
const hash = hashText(text);
|
|
86
91
|
// The catalog keeps the hash of what it stored: a document that does not match it was damaged on the way.
|
|
87
92
|
if (picked.content_hash && hash !== picked.content_hash) {
|
|
88
|
-
throw new Error(`The document of '${spec.name}'
|
|
93
|
+
throw new Error(`The document of '${spec.name}' rev ${picked.version} has SHA-256 ${hash}, not the ${picked.content_hash} the catalog lists for it: it did not arrive intact.`);
|
|
89
94
|
}
|
|
90
95
|
// And the one a pipeline pinned: the version, or what the name points at, is no longer what it expected.
|
|
91
96
|
if (p.hash && hash !== p.hash) {
|
|
92
|
-
throw new Error(`The document of '${spec.name}'
|
|
97
|
+
throw new Error(`The document of '${spec.name}' rev ${picked.version} has SHA-256 ${hash}, not the ${p.hash} you pinned with --hash: the revision was replaced, or the name now points at another spec.`);
|
|
93
98
|
}
|
|
94
99
|
return { id: spec.id, name: spec.name, version: picked.version, content_hash: hash, size_bytes: Buffer.byteLength(text, "utf8"), text };
|
|
95
100
|
});
|