@jinshuju/cli 0.20.0 → 0.22.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/schema.js ADDED
@@ -0,0 +1,239 @@
1
+ import { SCHEMAS } from './generated/operations.js';
2
+ import { isRecord } from './values.js';
3
+ /** The ways a value breaks a schema, first found first. */
4
+ export function validate(schema, value, pointer = '', certain = true) {
5
+ if (schema === true)
6
+ return [];
7
+ if (schema === false)
8
+ return [{ pointer, kind: 'shape', message: 'is not allowed here', value, certain }];
9
+ const s = resolved(schema);
10
+ const issues = [];
11
+ const issue = (kind, message) => issues.push({ pointer, kind, message, value, certain });
12
+ if (s.type !== undefined) {
13
+ const types = typeof s.type === 'string' ? [s.type] : s.type;
14
+ if (!types.some((type) => isType(value, type))) {
15
+ issue('type', `must be ${types.join(' or ')}`);
16
+ return issues;
17
+ }
18
+ }
19
+ if (s.enum !== undefined && !s.enum.some((option) => same(option, value))) {
20
+ issue('enum', `must be one of ${s.enum.map((option) => String(option)).join(', ')}`);
21
+ }
22
+ if (s.const !== undefined && !same(s.const, value))
23
+ issue('enum', `must be ${JSON.stringify(s.const)}`);
24
+ if (typeof value === 'number') {
25
+ if (s.minimum !== undefined && value < s.minimum)
26
+ issue('range', `must be at least ${s.minimum}`);
27
+ if (s.maximum !== undefined && value > s.maximum)
28
+ issue('range', `must be at most ${s.maximum}`);
29
+ }
30
+ if (typeof value === 'string') {
31
+ const length = [...value].length;
32
+ if (s.minLength !== undefined && length < s.minLength)
33
+ issue('range', `must be at least ${s.minLength} long`);
34
+ if (s.maxLength !== undefined && length > s.maxLength)
35
+ issue('range', `must be at most ${s.maxLength} long`);
36
+ if (s.pattern !== undefined && !new RegExp(s.pattern, 'u').test(value))
37
+ issue('range', `must match ${s.pattern}`);
38
+ }
39
+ if (Array.isArray(value)) {
40
+ if (s.minItems !== undefined && value.length < s.minItems)
41
+ issue('range', `must have at least ${s.minItems} items`);
42
+ if (s.maxItems !== undefined && value.length > s.maxItems)
43
+ issue('range', `must have at most ${s.maxItems} items`);
44
+ if (s.uniqueItems === true) {
45
+ const again = value.findIndex((item, index) => value.slice(0, index).some((earlier) => same(earlier, item)));
46
+ if (again >= 0) {
47
+ const first = value.findIndex((item) => same(item, value[again]));
48
+ issue('range', `must have each item once; item ${again} repeats item ${first}`);
49
+ }
50
+ }
51
+ const items = s.items;
52
+ if (items !== undefined) {
53
+ value.forEach((item, index) => issues.push(...validate(items, item, `${pointer}/${index}`, certain)));
54
+ }
55
+ const contains = s.contains;
56
+ if (contains !== undefined && !value.some((item) => validate(contains, item).length === 0)) {
57
+ issue('shape', 'must contain a matching item');
58
+ }
59
+ }
60
+ if (isRecord(value))
61
+ issues.push(...objectIssues(s, value, pointer, certain));
62
+ for (const part of s.allOf ?? [])
63
+ issues.push(...validate(part, value, pointer, certain));
64
+ if (s.discriminator !== undefined && isRecord(value)) {
65
+ issues.push(...discriminated(s, value, pointer, certain));
66
+ }
67
+ else {
68
+ if (s.anyOf !== undefined)
69
+ issues.push(...alternatives(s.anyOf, value, pointer, certain, 'anyOf'));
70
+ if (s.oneOf !== undefined)
71
+ issues.push(...alternatives(s.oneOf, value, pointer, certain, 'oneOf'));
72
+ }
73
+ if (s.not !== undefined && validate(s.not, value, pointer).length === 0)
74
+ issue('shape', 'is not allowed in this shape');
75
+ if (s.if !== undefined) {
76
+ const branch = validate(s.if, value, pointer).length === 0 ? s.then : s.else;
77
+ if (branch !== undefined)
78
+ issues.push(...validate(branch, value, pointer, certain));
79
+ }
80
+ return issues;
81
+ }
82
+ function objectIssues(s, value, pointer, certain) {
83
+ const issues = [];
84
+ const missing = (name, message) => issues.push({ pointer: `${pointer}/${escape(name)}`, kind: 'required', message, value: undefined, certain });
85
+ for (const name of s.required ?? [])
86
+ if (!(name in value))
87
+ missing(name, 'is required');
88
+ for (const [name, needs] of Object.entries(s.dependentRequired ?? {})) {
89
+ if (!(name in value))
90
+ continue;
91
+ for (const needed of needs)
92
+ if (!(needed in value))
93
+ missing(needed, `is required with ${name}`);
94
+ }
95
+ for (const [name, item] of Object.entries(value)) {
96
+ const where = `${pointer}/${escape(name)}`;
97
+ const declared = s.properties?.[name];
98
+ if (declared !== undefined)
99
+ issues.push(...validate(declared, item, where, certain));
100
+ else if (s.additionalProperties === false) {
101
+ issues.push({
102
+ pointer: where,
103
+ kind: 'unknown_key',
104
+ message: 'is not a key it takes',
105
+ value: item,
106
+ certain,
107
+ takes: Object.keys(s.properties ?? {})
108
+ });
109
+ }
110
+ else if (s.additionalProperties !== undefined) {
111
+ issues.push(...validate(s.additionalProperties, item, where, certain));
112
+ }
113
+ }
114
+ return issues;
115
+ }
116
+ /**
117
+ * The one of several shapes a value is, named by its own discriminator
118
+ * property. A value naming a shape this copy of the spec does not list is held
119
+ * to none of them: the API may have learned the shape since, and the closest
120
+ * of the others would be told about keys it never had.
121
+ */
122
+ function discriminated(s, value, pointer, certain) {
123
+ const { propertyName, mapping } = s.discriminator;
124
+ const tag = value[propertyName];
125
+ const where = `${pointer}/${escape(propertyName)}`;
126
+ if (tag === undefined) {
127
+ // Unless the object's own required list has said so already.
128
+ if (s.required?.includes(propertyName))
129
+ return [];
130
+ return [{ pointer: where, kind: 'required', message: 'is required', value: undefined, certain }];
131
+ }
132
+ const branch = typeof tag === 'string' ? mapping[tag] : undefined;
133
+ if (branch === undefined) {
134
+ // Unless the property's own list of values has said so already.
135
+ if (s.properties?.[propertyName] !== undefined)
136
+ return [];
137
+ const known = Object.keys(mapping).join(', ');
138
+ return [{ pointer: where, kind: 'enum', message: `must be one of ${known}`, value: tag, certain }];
139
+ }
140
+ return validate({ $ref: branch }, value, pointer, certain);
141
+ }
142
+ /** A value held to one of several shapes: the one its tag names when they are told apart by one, else the closest. */
143
+ function alternatives(parts, value, pointer, certain, how) {
144
+ const named = discriminatedAmong(parts, value, pointer, certain);
145
+ if (named !== undefined)
146
+ return named;
147
+ const fitting = parts.filter((part) => validate(part, value, pointer).length === 0).length;
148
+ if (fitting === 0)
149
+ return closest(parts, value, pointer);
150
+ if (how === 'oneOf' && fitting > 1) {
151
+ return [{ pointer, kind: 'shape', message: 'matches more than one of the shapes it may take', value, certain }];
152
+ }
153
+ return [];
154
+ }
155
+ /**
156
+ * Among shapes each told apart by the same discriminator — a form's field
157
+ * types beside a table's — the one the value's own tag names, held to with
158
+ * certainty. Nothing to say when the shapes are not all of that kind, or the
159
+ * tag names a different shape in each. A tag none of them lists names no
160
+ * shape, and that is an answer rather than a guess: the API may have learned
161
+ * the type since, and the closest of the others would be told about keys it
162
+ * never had, which is what the API's own validation does and what sent a
163
+ * caller off to change a type that was right.
164
+ */
165
+ function discriminatedAmong(parts, value, pointer, certain) {
166
+ if (!isRecord(value))
167
+ return undefined;
168
+ const unions = parts.flatMap((part) => {
169
+ const here = typeof part === 'object' ? resolved(part) : undefined;
170
+ return here?.discriminator === undefined ? [] : [here.discriminator];
171
+ });
172
+ if (unions.length === 0 || unions.length !== parts.length)
173
+ return undefined;
174
+ const names = new Set(unions.map((union) => union.propertyName));
175
+ if (names.size !== 1)
176
+ return undefined;
177
+ const propertyName = unions[0]?.propertyName;
178
+ const tag = value[propertyName];
179
+ if (tag === undefined) {
180
+ const where = `${pointer}/${escape(propertyName)}`;
181
+ return [{ pointer: where, kind: 'required', message: 'is required', value: undefined, certain }];
182
+ }
183
+ const branches = new Set(unions.flatMap((union) => {
184
+ const branch = typeof tag === 'string' ? union.mapping[tag] : undefined;
185
+ return branch === undefined ? [] : [branch];
186
+ }));
187
+ if (branches.size > 1)
188
+ return undefined;
189
+ const [branch] = branches;
190
+ return branch === undefined ? [] : validate({ $ref: branch }, value, pointer, certain);
191
+ }
192
+ /**
193
+ * Why a value fits none of the shapes it may take, told by the one it came
194
+ * closest to. A shape it fails at its own level — a string where an object was
195
+ * wanted — is further off than one it fails only further in. Which shape was
196
+ * meant is a guess, so nothing found this way is certain.
197
+ */
198
+ function closest(parts, value, pointer) {
199
+ const distance = (issues) => issues.filter((issue) => issue.pointer === pointer).length * 1000 + issues.length;
200
+ const tries = parts.map((part) => validate(part, value, pointer, false)).sort((a, b) => distance(a) - distance(b));
201
+ return tries[0] ?? [];
202
+ }
203
+ function resolved(schema) {
204
+ let current = schema;
205
+ while (current.$ref !== undefined) {
206
+ const target = SCHEMAS[current.$ref];
207
+ if (!target)
208
+ throw new Error(`openapi.yaml has no schema ${current.$ref}`);
209
+ current = target;
210
+ }
211
+ return current;
212
+ }
213
+ function isType(value, type) {
214
+ switch (type) {
215
+ case 'null':
216
+ return value === null;
217
+ case 'boolean':
218
+ return typeof value === 'boolean';
219
+ case 'integer':
220
+ return typeof value === 'number' && Number.isInteger(value);
221
+ case 'number':
222
+ return typeof value === 'number' && Number.isFinite(value);
223
+ case 'string':
224
+ return typeof value === 'string';
225
+ case 'array':
226
+ return Array.isArray(value);
227
+ case 'object':
228
+ return isRecord(value);
229
+ default:
230
+ return true;
231
+ }
232
+ }
233
+ function same(a, b) {
234
+ return a === b || JSON.stringify(a) === JSON.stringify(b);
235
+ }
236
+ /** A key as a JSON Pointer segment spells it. */
237
+ function escape(name) {
238
+ return name.replace(/~/g, '~0').replace(/\//g, '~1');
239
+ }
package/dist/spec.d.ts CHANGED
@@ -42,7 +42,19 @@ export interface Schema {
42
42
  readonly maxLength?: number;
43
43
  readonly minItems?: number;
44
44
  readonly maxItems?: number;
45
+ readonly uniqueItems?: boolean;
45
46
  readonly pattern?: string;
47
+ /**
48
+ * Which of the shapes beside it (oneOf, anyOf) a value is, named by one of
49
+ * its own properties: `type: TextField` is a TextFieldInput. The mapping
50
+ * names schemas in SCHEMAS.
51
+ */
52
+ readonly discriminator?: {
53
+ readonly propertyName: string;
54
+ readonly mapping: {
55
+ readonly [tag: string]: string;
56
+ };
57
+ };
46
58
  }
47
59
  export interface Parameter {
48
60
  readonly name: string;
@@ -71,6 +83,11 @@ export interface Operation {
71
83
  };
72
84
  }
73
85
  export declare function operation(id: OperationId): Operation;
86
+ /**
87
+ * The operation a request was sent to, read off its method and path, so a
88
+ * request can be held to the spec without trusting how it was built.
89
+ */
90
+ export declare function operationOf(request: Pick<HttpRequest, 'method' | 'path'>): OperationId | undefined;
74
91
  /** A query value as a command has it; `call` spells it for the wire. */
75
92
  export type QueryValue = string | number | boolean | readonly string[] | undefined;
76
93
  export interface CallParts {
@@ -94,6 +111,8 @@ export interface CallParts {
94
111
  * date — and answers a 400 that says exactly what is wrong. A check here
95
112
  * would save that round trip at the price of refusing, in every CLI already
96
113
  * installed, each field type, key and value the API learns after it ships.
114
+ * The one look the CLI takes at a body is src/preflight.ts, on the way to the
115
+ * wire, and it refuses only what no newer spec could have made right.
97
116
  */
98
117
  export declare function call(id: OperationId, parts?: CallParts): HttpRequest;
99
118
  export declare function unansweredLookups(): readonly string[];
package/dist/spec.js CHANGED
@@ -4,6 +4,27 @@ export { BASE_PATH } from './generated/operations.js';
4
4
  export function operation(id) {
5
5
  return OPERATIONS[id];
6
6
  }
7
+ /**
8
+ * The operation a request was sent to, read off its method and path, so a
9
+ * request can be held to the spec without trusting how it was built.
10
+ */
11
+ export function operationOf(request) {
12
+ if (!request.path.startsWith(BASE_PATH))
13
+ return undefined;
14
+ const path = request.path.slice(BASE_PATH.length);
15
+ const matches = Object.keys(OPERATIONS).filter((id) => {
16
+ const op = OPERATIONS[id];
17
+ if (op.method !== request.method)
18
+ return false;
19
+ const pattern = op.path.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\{[^}]+\}/g, '[^/]+');
20
+ return new RegExp(`^${pattern}$`).test(path);
21
+ });
22
+ // A literal segment beats a parameter: /entries/count is not /entries/{serial_number}.
23
+ return matches.sort((a, b) => literalLength(OPERATIONS[b].path) - literalLength(OPERATIONS[a].path))[0];
24
+ }
25
+ function literalLength(path) {
26
+ return path.replace(/\{[^}]+\}/g, '').length;
27
+ }
7
28
  /**
8
29
  * The request an operation is.
9
30
  *
@@ -18,6 +39,8 @@ export function operation(id) {
18
39
  * date — and answers a 400 that says exactly what is wrong. A check here
19
40
  * would save that round trip at the price of refusing, in every CLI already
20
41
  * installed, each field type, key and value the API learns after it ships.
42
+ * The one look the CLI takes at a body is src/preflight.ts, on the way to the
43
+ * wire, and it refuses only what no newer spec could have made right.
21
44
  */
22
45
  export function call(id, parts = {}) {
23
46
  const op = OPERATIONS[id];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jinshuju/cli",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Command line interface for Jinshuju Open API v1",
5
5
  "homepage": "https://github.com/jinshuju/cli#readme",
6
6
  "bugs": {
@@ -30,7 +30,7 @@
30
30
  "clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
31
31
  "build": "npm run clean && tsc -p tsconfig.json && chmod +x dist/cli-bin.js",
32
32
  "prepare": "npm run build",
33
- "test": "npm run build && node --test dist/*.test.js",
33
+ "test": "npm run build && node --test --test-reporter=spec dist/*.test.js",
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit",
35
35
  "lint": "oxlint",
36
36
  "fmt": "oxfmt",