@jinshuju/cli 0.10.0 → 0.12.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/dist/options.d.ts CHANGED
@@ -102,5 +102,10 @@ export interface Containers {
102
102
  * container lets the server choose. Still one kind per call.
103
103
  */
104
104
  export declare function namedContainers(options: Record<string, unknown>): Containers;
105
- /** The repeatable form of resolveContainer, for a read that answers about several. */
106
- export declare function resolveContainers(options: Record<string, unknown>, max: number): Containers;
105
+ /**
106
+ * The repeatable form of resolveContainer, for a read that answers about
107
+ * several. How many it may name is the API's to say: the number is in its
108
+ * prose rather than its schema, and a copy enforced here would go on refusing
109
+ * after the API took more.
110
+ */
111
+ export declare function resolveContainers(options: Record<string, unknown>): Containers;
package/dist/options.js CHANGED
@@ -263,13 +263,15 @@ export function namedContainers(options) {
263
263
  throw new UsageError('--form and --table are mutually exclusive');
264
264
  return { tokens: forms.length > 0 ? forms : tables, kind: forms.length > 0 ? 'form' : 'table' };
265
265
  }
266
- /** The repeatable form of resolveContainer, for a read that answers about several. */
267
- export function resolveContainers(options, max) {
266
+ /**
267
+ * The repeatable form of resolveContainer, for a read that answers about
268
+ * several. How many it may name is the API's to say: the number is in its
269
+ * prose rather than its schema, and a copy enforced here would go on refusing
270
+ * after the API took more.
271
+ */
272
+ export function resolveContainers(options) {
268
273
  const containers = namedContainers(options);
269
274
  if (containers.tokens.length === 0)
270
275
  throw new UsageError('one of --form <token> or --table <token> is required');
271
- if (containers.tokens.length > max) {
272
- throw new UsageError(`at most ${max} containers can be asked about in one call, got ${containers.tokens.length}`);
273
- }
274
276
  return containers;
275
277
  }
package/dist/spec.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ import { type OperationId } from './generated/operations.js';
2
+ import type { HttpMethod, HttpRequest } from './http.js';
3
+ /**
4
+ * What API v1 takes, as openapi.yaml says it, and the one way a command turns
5
+ * an operation into a request.
6
+ *
7
+ * The commands decide what the CLI offers. Which operation lives at which
8
+ * path, which parameters it has and of what type, how a list goes on the wire,
9
+ * and which values a flag offers are the spec's, read from the generated table
10
+ * rather than written down a second time here. When the spec changes,
11
+ * `npm run spec:update` regenerates the table and the CLI follows.
12
+ */
13
+ export type { OperationId } from './generated/operations.js';
14
+ export { BASE_PATH } from './generated/operations.js';
15
+ /** A JSON Schema cut down to the constraints scripts/generate.mjs keeps. */
16
+ export interface Schema {
17
+ /** The name of a schema in SCHEMAS. */
18
+ readonly $ref?: string;
19
+ readonly type?: string | readonly string[];
20
+ readonly enum?: readonly unknown[];
21
+ readonly const?: unknown;
22
+ readonly properties?: {
23
+ readonly [name: string]: Schema | boolean;
24
+ };
25
+ readonly required?: readonly string[];
26
+ readonly dependentRequired?: {
27
+ readonly [name: string]: readonly string[];
28
+ };
29
+ readonly additionalProperties?: Schema | boolean;
30
+ readonly items?: Schema | boolean;
31
+ readonly contains?: Schema | boolean;
32
+ readonly allOf?: readonly (Schema | boolean)[];
33
+ readonly oneOf?: readonly (Schema | boolean)[];
34
+ readonly anyOf?: readonly (Schema | boolean)[];
35
+ readonly not?: Schema | boolean;
36
+ readonly if?: Schema | boolean;
37
+ readonly then?: Schema | boolean;
38
+ readonly else?: Schema | boolean;
39
+ readonly minimum?: number;
40
+ readonly maximum?: number;
41
+ readonly minLength?: number;
42
+ readonly maxLength?: number;
43
+ readonly minItems?: number;
44
+ readonly maxItems?: number;
45
+ readonly pattern?: string;
46
+ }
47
+ export interface Parameter {
48
+ readonly name: string;
49
+ readonly in: string;
50
+ readonly required?: boolean;
51
+ readonly style?: string;
52
+ readonly explode?: boolean;
53
+ readonly schema: Schema;
54
+ }
55
+ export interface Operation {
56
+ readonly method: HttpMethod;
57
+ /** Relative to BASE_PATH, with `{name}` for each path parameter. */
58
+ readonly path: string;
59
+ readonly parameters: readonly Parameter[];
60
+ readonly body?: {
61
+ readonly required?: boolean;
62
+ readonly content: {
63
+ readonly [mediaType: string]: Schema;
64
+ };
65
+ };
66
+ }
67
+ export declare function operation(id: OperationId): Operation;
68
+ /** A query value as a command has it; `call` spells it for the wire. */
69
+ export type QueryValue = string | number | boolean | readonly string[] | undefined;
70
+ export interface CallParts {
71
+ readonly path?: Readonly<Record<string, string | number | undefined>>;
72
+ readonly query?: Readonly<Record<string, QueryValue>>;
73
+ readonly body?: unknown;
74
+ /** A multipart body, for the operations that take a file. */
75
+ readonly form?: FormData;
76
+ }
77
+ /**
78
+ * The request an operation is.
79
+ *
80
+ * Path and query come from the CLI's own flags and arguments, so they are held
81
+ * to the operation's parameters here: one it does not have, a required one
82
+ * left out, or a value that is not of its type is a usage error naming it. A
83
+ * new parameter needs a new flag and so a new release anyway, which is why
84
+ * this never makes an installed CLI stricter than a newer API.
85
+ *
86
+ * A body goes as given. It is the caller's payload as often as not, the API
87
+ * validates it against the openapi.yaml it runs — the only copy never out of
88
+ * date — and answers a 400 that says exactly what is wrong. A check here
89
+ * would save that round trip at the price of refusing, in every CLI already
90
+ * installed, each field type, key and value the API learns after it ships.
91
+ */
92
+ export declare function call(id: OperationId, parts?: CallParts): HttpRequest;
93
+ export declare function unansweredLookups(): readonly string[];
94
+ /**
95
+ * The values a query parameter takes, for the flag that feeds it. A flag
96
+ * listing them itself is a second copy, and the second copy was already behind
97
+ * once: a view type and two scenes the API had learned were refused by the CLI
98
+ * before they reached it.
99
+ */
100
+ export declare function choices(id: OperationId, name: string): readonly string[] | undefined;
101
+ /**
102
+ * The values a property of a JSON body takes. `path` walks properties with
103
+ * dots and steps into a list's items with `[]`: `fields[].type`.
104
+ */
105
+ export declare function bodyChoices(id: OperationId, path: string): readonly string[] | undefined;
package/dist/spec.js ADDED
@@ -0,0 +1,201 @@
1
+ import { UsageError } from './errors.js';
2
+ import { BASE_PATH, OPERATIONS, SCHEMAS } from './generated/operations.js';
3
+ export { BASE_PATH } from './generated/operations.js';
4
+ export function operation(id) {
5
+ return OPERATIONS[id];
6
+ }
7
+ /**
8
+ * The request an operation is.
9
+ *
10
+ * Path and query come from the CLI's own flags and arguments, so they are held
11
+ * to the operation's parameters here: one it does not have, a required one
12
+ * left out, or a value that is not of its type is a usage error naming it. A
13
+ * new parameter needs a new flag and so a new release anyway, which is why
14
+ * this never makes an installed CLI stricter than a newer API.
15
+ *
16
+ * A body goes as given. It is the caller's payload as often as not, the API
17
+ * validates it against the openapi.yaml it runs — the only copy never out of
18
+ * date — and answers a 400 that says exactly what is wrong. A check here
19
+ * would save that round trip at the price of refusing, in every CLI already
20
+ * installed, each field type, key and value the API learns after it ships.
21
+ */
22
+ export function call(id, parts = {}) {
23
+ const op = OPERATIONS[id];
24
+ const request = {
25
+ method: op.method,
26
+ path: BASE_PATH + fillPath(id, op, parts.path ?? {})
27
+ };
28
+ const query = queryOf(id, op, parts.query ?? {});
29
+ if (Object.keys(query).length > 0)
30
+ request.query = query;
31
+ if (parts.body !== undefined) {
32
+ if (!op.body?.content['application/json'])
33
+ throw new Error(`${id} takes no JSON body`);
34
+ request.body = parts.body;
35
+ }
36
+ if (parts.form !== undefined) {
37
+ if (!op.body?.content['multipart/form-data'])
38
+ throw new Error(`${id} takes no multipart body`);
39
+ request.form = parts.form;
40
+ }
41
+ if (op.body?.required && request.body === undefined && request.form === undefined) {
42
+ throw new Error(`${id} needs a request body`);
43
+ }
44
+ return request;
45
+ }
46
+ function fillPath(id, op, values) {
47
+ for (const name of Object.keys(values)) {
48
+ if (!op.parameters.some((param) => param.in === 'path' && param.name === name)) {
49
+ throw new Error(`${id} has no path parameter ${name}`);
50
+ }
51
+ }
52
+ return op.path.replace(/\{([^}]+)\}/g, (_, name) => {
53
+ const value = values[name];
54
+ if (value === undefined || value === '')
55
+ throw new Error(`${id} needs its path parameter ${name}`);
56
+ const param = op.parameters.find((candidate) => candidate.in === 'path' && candidate.name === name);
57
+ check(param, [String(value)]);
58
+ return encodeURIComponent(String(value));
59
+ });
60
+ }
61
+ function queryOf(id, op, values) {
62
+ const query = {};
63
+ for (const [name, value] of Object.entries(values)) {
64
+ if (value === undefined)
65
+ continue;
66
+ const param = op.parameters.find((candidate) => candidate.in === 'query' && candidate.name === name);
67
+ if (!param) {
68
+ throw new UsageError(`${op.method} ${BASE_PATH}${op.path} takes no ${name} parameter (${id} in openapi.yaml)`);
69
+ }
70
+ const texts = typeof value === 'object' ? [...value] : [String(value)];
71
+ check(param, texts);
72
+ if (isArray(param.schema)) {
73
+ // A list on one parameter is `name=a,b` when the spec says it does not
74
+ // explode, and `name[]=a&name[]=b` otherwise, which is how Rails reads one.
75
+ query[name] = param.explode === false ? texts.join(',') : texts;
76
+ }
77
+ else {
78
+ // The spec's own prose lets a scalar repeat — `q[]=A&q[]=B` — so a list
79
+ // is each of its values sent as the scalar.
80
+ query[name] = typeof value === 'object' ? texts : texts[0];
81
+ }
82
+ }
83
+ for (const param of op.parameters) {
84
+ if (param.in === 'query' && param.required && query[param.name] === undefined) {
85
+ throw new UsageError(`${param.name} is required (${id} in openapi.yaml)`);
86
+ }
87
+ }
88
+ return query;
89
+ }
90
+ /**
91
+ * Each value of a path or query parameter, held to the type it declares: the
92
+ * one thing about it no later version of the API changes its mind on. A
93
+ * range, a length or a list of values may grow, so those are the server's.
94
+ */
95
+ function check(param, texts) {
96
+ const types = typesOf(isArray(param.schema) ? itemsOf(param.schema) : param.schema);
97
+ if (types.length === 0)
98
+ return;
99
+ for (const text of texts) {
100
+ if (types.some((type) => reads(text, type)))
101
+ continue;
102
+ throw new UsageError(`${param.name} must be ${types.map(article).join(' or ')}, got ${JSON.stringify(text)}`);
103
+ }
104
+ }
105
+ /** Whether a string off the command line reads as a value of the type. */
106
+ function reads(text, type) {
107
+ switch (type) {
108
+ case 'integer':
109
+ return /^-?\d+$/.test(text);
110
+ case 'number':
111
+ return /^-?\d+(\.\d+)?$/.test(text);
112
+ case 'boolean':
113
+ return text === 'true' || text === 'false';
114
+ case 'null':
115
+ return false;
116
+ default:
117
+ return true;
118
+ }
119
+ }
120
+ function article(type) {
121
+ return type === 'integer' || type === 'object' || type === 'array' ? `an ${type}` : `a ${type}`;
122
+ }
123
+ function isArray(schema) {
124
+ return typesOf(schema).includes('array');
125
+ }
126
+ function itemsOf(schema) {
127
+ const items = resolved(schema).items;
128
+ return typeof items === 'object' ? items : {};
129
+ }
130
+ function typesOf(schema) {
131
+ const type = resolved(schema).type;
132
+ return type === undefined ? [] : typeof type === 'string' ? [type] : type;
133
+ }
134
+ function resolved(schema) {
135
+ let current = schema;
136
+ while (current.$ref !== undefined) {
137
+ const target = SCHEMAS[current.$ref];
138
+ if (!target)
139
+ throw new Error(`openapi.yaml has no schema ${current.$ref}`);
140
+ current = target;
141
+ }
142
+ return current;
143
+ }
144
+ // --- the vocabulary flags are checked by --------------------------------------
145
+ /**
146
+ * Every lookup that found no list of values. These run as the commands load,
147
+ * so a spec that dropped one must not take every command down with it, --help
148
+ * included: the flag goes without a list and the server judges the value, and
149
+ * a test fails on this list instead, in the sync pull request that dropped it.
150
+ */
151
+ const unanswered = [];
152
+ export function unansweredLookups() {
153
+ return unanswered;
154
+ }
155
+ /**
156
+ * The values a query parameter takes, for the flag that feeds it. A flag
157
+ * listing them itself is a second copy, and the second copy was already behind
158
+ * once: a view type and two scenes the API had learned were refused by the CLI
159
+ * before they reached it.
160
+ */
161
+ export function choices(id, name) {
162
+ const param = OPERATIONS[id].parameters.find((candidate) => candidate.name === name);
163
+ return enumOf(param && (isArray(param.schema) ? itemsOf(param.schema) : param.schema), `${id} ${name}`);
164
+ }
165
+ /**
166
+ * The values a property of a JSON body takes. `path` walks properties with
167
+ * dots and steps into a list's items with `[]`: `fields[].type`.
168
+ */
169
+ export function bodyChoices(id, path) {
170
+ let schema = OPERATIONS[id].body?.content['application/json'];
171
+ for (const step of path.split('.')) {
172
+ if (!schema)
173
+ break;
174
+ const many = step.endsWith('[]');
175
+ const property = propertyOf(schema, many ? step.slice(0, -2) : step);
176
+ schema = property && (many ? itemsOf(property) : property);
177
+ }
178
+ return enumOf(schema, `${id} ${path}`);
179
+ }
180
+ /** A property as an object schema or any of its allOf parts declares it. */
181
+ function propertyOf(schema, name) {
182
+ const here = resolved(schema);
183
+ const own = here.properties?.[name];
184
+ if (typeof own === 'object')
185
+ return own;
186
+ for (const part of here.allOf ?? []) {
187
+ if (typeof part !== 'object')
188
+ continue;
189
+ const found = propertyOf(part, name);
190
+ if (found)
191
+ return found;
192
+ }
193
+ return undefined;
194
+ }
195
+ function enumOf(schema, what) {
196
+ const values = (schema ? (resolved(schema).enum ?? []) : []).filter((value) => typeof value === 'string');
197
+ if (values.length > 0)
198
+ return values;
199
+ unanswered.push(what);
200
+ return undefined;
201
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jinshuju/cli",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Command line interface for Jinshuju Open API v1",
5
5
  "homepage": "https://github.com/jinshuju/cli#readme",
6
6
  "bugs": {
@@ -18,7 +18,8 @@
18
18
  "files": [
19
19
  "dist",
20
20
  "!dist/**/*.test.js",
21
- "!dist/**/*.test.d.ts"
21
+ "!dist/**/*.test.d.ts",
22
+ "!dist/testing"
22
23
  ],
23
24
  "type": "module",
24
25
  "publishConfig": {
@@ -34,13 +35,16 @@
34
35
  "lint": "oxlint",
35
36
  "fmt": "oxfmt",
36
37
  "fmt:check": "oxfmt --check",
37
- "check": "npm run typecheck && npm run lint && npm run fmt:check"
38
+ "check": "npm run typecheck && npm run lint && npm run fmt:check",
39
+ "generate": "node scripts/generate.mjs && oxfmt src/generated",
40
+ "spec:update": "node scripts/fetch-spec.mjs && npm run generate"
38
41
  },
39
42
  "devDependencies": {
40
43
  "@types/node": "^22.10.0",
41
44
  "oxfmt": "^0.70.0",
42
45
  "oxlint": "^1.85.0",
43
- "typescript": "^5.9.3"
46
+ "typescript": "^5.9.3",
47
+ "yaml": "^2.9.1"
44
48
  },
45
49
  "engines": {
46
50
  "node": ">=20"