@jinshuju/cli 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +58 -1
  2. package/dist/args.d.ts +47 -0
  3. package/dist/args.js +185 -0
  4. package/dist/auth.js +43 -11
  5. package/dist/cli-bin.js +1 -1
  6. package/dist/cli.d.ts +2 -20
  7. package/dist/cli.js +71 -659
  8. package/dist/commands/account.d.ts +2 -0
  9. package/dist/commands/account.js +15 -0
  10. package/dist/commands/comment.d.ts +2 -0
  11. package/dist/commands/comment.js +66 -0
  12. package/dist/commands/entry.d.ts +31 -0
  13. package/dist/commands/entry.js +715 -0
  14. package/dist/commands/field.d.ts +3 -0
  15. package/dist/commands/field.js +259 -0
  16. package/dist/commands/folder.d.ts +2 -0
  17. package/dist/commands/folder.js +31 -0
  18. package/dist/commands/form.d.ts +2 -0
  19. package/dist/commands/form.js +394 -0
  20. package/dist/commands/index.d.ts +16 -0
  21. package/dist/commands/index.js +68 -0
  22. package/dist/commands/local.d.ts +10 -0
  23. package/dist/commands/local.js +76 -0
  24. package/dist/commands/opensearch.d.ts +2 -0
  25. package/dist/commands/opensearch.js +73 -0
  26. package/dist/commands/shared.d.ts +57 -0
  27. package/dist/commands/shared.js +122 -0
  28. package/dist/commands/table.d.ts +2 -0
  29. package/dist/commands/table.js +101 -0
  30. package/dist/{commands.d.ts → commands/types.d.ts} +24 -30
  31. package/dist/commands/types.js +1 -0
  32. package/dist/commands/upload.d.ts +7 -0
  33. package/dist/commands/upload.js +40 -0
  34. package/dist/commands/view.d.ts +2 -0
  35. package/dist/commands/view.js +81 -0
  36. package/dist/config.d.ts +2 -0
  37. package/dist/config.js +45 -5
  38. package/dist/errors.d.ts +48 -0
  39. package/dist/errors.js +99 -0
  40. package/dist/help.d.ts +1 -1
  41. package/dist/help.js +11 -1
  42. package/dist/http.d.ts +37 -4
  43. package/dist/http.js +119 -14
  44. package/dist/local.d.ts +24 -0
  45. package/dist/local.js +208 -0
  46. package/dist/options.d.ts +8 -4
  47. package/dist/options.js +63 -18
  48. package/dist/payload.d.ts +14 -8
  49. package/dist/payload.js +22 -54
  50. package/dist/render.d.ts +21 -0
  51. package/dist/render.js +315 -0
  52. package/dist/result.d.ts +31 -0
  53. package/dist/result.js +32 -0
  54. package/dist/values.d.ts +4 -0
  55. package/dist/values.js +8 -0
  56. package/dist/version.d.ts +6 -0
  57. package/dist/version.js +16 -0
  58. package/package.json +23 -18
  59. package/dist/commands.js +0 -1672
package/dist/options.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { readFileSync } from 'node:fs';
2
- export const OUTPUT_FORMATS = ['text', 'json'];
2
+ import { UsageError } from './errors.js';
3
+ export const OUTPUT_FORMATS = ['text', 'json', 'jsonl'];
3
4
  /** Accepted by every command. */
4
5
  export const GLOBAL_OPTIONS = [
5
- { name: '--output', type: 'string', choices: OUTPUT_FORMATS, placeholder: '<format>', description: 'Output format: text, json' },
6
+ {
7
+ name: '--output',
8
+ type: 'string',
9
+ choices: OUTPUT_FORMATS,
10
+ placeholder: '<format>',
11
+ description: 'Output format: text, json, or jsonl (one JSON object per line; a listing streams its rows)'
12
+ },
6
13
  { name: '--config', type: 'string', placeholder: '<path>', description: 'Config file path' },
7
14
  { name: '--help', short: '-h', type: 'boolean', description: 'Show help' },
8
15
  // -V rather than -v: nearly every CLI reads -v as verbose, and a flag that
@@ -29,23 +36,47 @@ export const LOCAL_OPTIONS = [
29
36
  ];
30
37
  /** The data container a command acts on. Mutually exclusive; both map to form_token. */
31
38
  export const CONTAINER_OPTIONS = [
32
- { name: '--form', type: 'string', placeholder: '<token>', description: 'Form token, six letters and digits, e.g. Kp7mQ2' },
33
- { name: '--table', type: 'string', placeholder: '<token>', description: 'Table token, six letters and digits, e.g. Vn4xR8' }
39
+ {
40
+ name: '--form',
41
+ type: 'string',
42
+ placeholder: '<token>',
43
+ description: 'Form token, six letters and digits, e.g. Kp7mQ2'
44
+ },
45
+ {
46
+ name: '--table',
47
+ type: 'string',
48
+ placeholder: '<token>',
49
+ description: 'Table token, six letters and digits, e.g. Vn4xR8'
50
+ }
34
51
  ];
35
52
  /**
36
53
  * The same container, repeatable, for the reads that answer about several at
37
54
  * once. Still one kind per call: `--form` and `--table` stay mutually exclusive.
38
55
  */
39
56
  export const CONTAINER_LIST_OPTIONS = [
40
- { name: '--form', type: 'string', repeatable: true, placeholder: '<token>', description: 'Form token, repeatable, e.g. Kp7mQ2' },
41
- { name: '--table', type: 'string', repeatable: true, placeholder: '<token>', description: 'Table token, repeatable, e.g. Vn4xR8' }
57
+ {
58
+ name: '--form',
59
+ type: 'string',
60
+ repeatable: true,
61
+ placeholder: '<token>',
62
+ description: 'Form token, repeatable, e.g. Kp7mQ2'
63
+ },
64
+ {
65
+ name: '--table',
66
+ type: 'string',
67
+ repeatable: true,
68
+ placeholder: '<token>',
69
+ description: 'Table token, repeatable, e.g. Vn4xR8'
70
+ }
42
71
  ];
43
72
  export const FILTER_OPTION = {
44
73
  name: '--filter',
45
74
  type: 'string',
46
75
  repeatable: true,
47
76
  placeholder: "'<field> <op> [value]'",
48
- description: "Filter condition, repeatable, AND-combined. e.g. 'field_3 gte 80', 'created_at within_last 30d', 'field_4 between 1,10'"
77
+ description: 'Filter condition, repeatable, AND-combined. Operators: eq ne gte gt lte lt like not_like ' +
78
+ 'any_in none_in between not_between null not_null match within_last. ' +
79
+ "e.g. 'field_3 gte 80', 'created_at within_last 30d', 'field_4 between 1,10'"
49
80
  };
50
81
  export const FILTERS_OPTION = {
51
82
  name: '--filters',
@@ -62,11 +93,19 @@ export const SORT_OPTION = {
62
93
  };
63
94
  /** Asks for a smaller page; a listing's default is also its cap. */
64
95
  export const LIMIT_OPTION = {
65
- name: '--limit', type: 'integer', placeholder: '<n>', description: 'Rows per page, up to the listing default'
96
+ name: '--limit',
97
+ type: 'integer',
98
+ placeholder: '<n>',
99
+ description: 'Rows per page, up to the listing default'
66
100
  };
67
101
  export const PAGINATION_OPTIONS = [
68
102
  LIMIT_OPTION,
69
- { name: '--next', type: 'string', placeholder: '<cursor>', description: 'Cursor from the previous response, passed back verbatim' },
103
+ {
104
+ name: '--next',
105
+ type: 'string',
106
+ placeholder: '<cursor>',
107
+ description: 'Cursor from the previous response, passed back verbatim'
108
+ },
70
109
  { name: '--all', type: 'boolean', description: 'Follow the cursor and return every page' }
71
110
  ];
72
111
  export const JSON_OPTION = {
@@ -80,8 +119,7 @@ export const MINE_OPTION = {
80
119
  type: 'boolean',
81
120
  description: 'Switch to what the current user submitted'
82
121
  };
83
- export class UsageError extends Error {
84
- }
122
+ export { UsageError } from './errors.js';
85
123
  /** `--api-key` reads back as `api_key`. */
86
124
  export function optionKey(spec) {
87
125
  return spec.name.replace(/^--/, '').replace(/-/g, '_');
@@ -216,17 +254,24 @@ export function resolveContainer(options) {
216
254
  return { token: table, kind: 'table' };
217
255
  throw new UsageError('one of --form <token> or --table <token> is required');
218
256
  }
219
- /** The repeatable form of the above, for a read that answers about several. */
220
- export function resolveContainers(options, max) {
257
+ /**
258
+ * Every container named, of one kind, possibly none: a search that names no
259
+ * container lets the server choose. Still one kind per call.
260
+ */
261
+ export function namedContainers(options) {
221
262
  const forms = options.form ?? [];
222
263
  const tables = options.table ?? [];
223
264
  if (forms.length > 0 && tables.length > 0)
224
265
  throw new UsageError('--form and --table are mutually exclusive');
225
- const tokens = forms.length > 0 ? forms : tables;
226
- if (tokens.length === 0)
266
+ return { tokens: forms.length > 0 ? forms : tables, kind: forms.length > 0 ? 'form' : 'table' };
267
+ }
268
+ /** The repeatable form of resolveContainer, for a read that answers about several. */
269
+ export function resolveContainers(options, max) {
270
+ const containers = namedContainers(options);
271
+ if (containers.tokens.length === 0)
227
272
  throw new UsageError('one of --form <token> or --table <token> is required');
228
- if (tokens.length > max) {
229
- throw new UsageError(`at most ${max} containers can be asked about in one call, got ${tokens.length}`);
273
+ if (containers.tokens.length > max) {
274
+ throw new UsageError(`at most ${max} containers can be asked about in one call, got ${containers.tokens.length}`);
230
275
  }
231
- return { tokens, kind: forms.length > 0 ? 'form' : 'table' };
276
+ return containers;
232
277
  }
package/dist/payload.d.ts CHANGED
@@ -1,12 +1,18 @@
1
- export type FormCreatePayload = {
1
+ /**
2
+ * What a form or table payload has to look like before it is worth sending.
3
+ *
4
+ * Only the shape is checked here: an object, a name, fields that are objects
5
+ * with a type and without an api_code. Which types exist, which a table takes,
6
+ * which a scene allows and what each one needs is the server's vocabulary, and
7
+ * `jinshuju field types` reads it from there. A copy kept here was already
8
+ * wrong once — it refused every question type an exam scene has — and would be
9
+ * wrong again the next time the server learned a type.
10
+ */
11
+ export type ContainerPayload = {
2
12
  name: string;
3
- description?: string;
4
- fields: Array<Record<string, unknown> & {
13
+ fields?: Array<Record<string, unknown> & {
5
14
  type: string;
6
- label?: string;
7
15
  }>;
8
- setting?: Record<string, unknown>;
9
- folder_token?: string;
16
+ [key: string]: unknown;
10
17
  };
11
- export declare function parseJsonPayload(value: string): unknown;
12
- export declare function validateCreateFormPayload(payload: unknown): FormCreatePayload;
18
+ export declare function validateContainerPayload(payload: unknown, what: 'form' | 'table'): ContainerPayload;
package/dist/payload.js CHANGED
@@ -1,59 +1,27 @@
1
- const API_V1_FIELD_TYPES = new Set([
2
- 'TextField', 'TextArea', 'NumberField', 'EmailField', 'MobileField', 'TelephoneField', 'IdCardField',
3
- 'NameField', 'AddressField', 'LinkField', 'GeoField', 'AttachmentField', 'DateTimeField', 'TimeField',
4
- 'RatingField', 'NpsField', 'RadioButton', 'CheckBox', 'DropDown', 'TableField', 'CascadeDropDown',
5
- 'SortField', 'LikertField', 'MatrixField', 'MatrixScaleField', 'ImageRadioButton', 'ImageCheckBox',
6
- 'GoodsField', 'FormulaField', 'ReservationField', 'FormAssociation', 'ESignatureField', 'AudioField',
7
- 'PageBreak', 'SectionBreak', 'WidgetButton', 'WidgetContact', 'WidgetMap', 'WidgetMarquee'
8
- ]);
9
- /**
10
- * The question types only a scorable scene has. They are not Fields::* classes
11
- * of their own — each persists as a base field plus a customized_type and the
12
- * correct answers — which is why they are absent from the list above and were
13
- * being refused here: `--type exam` could create an exam-scene form and then
14
- * not one question that scores, the only thing the scene is for.
15
- *
16
- * Which scene accepts which is the server's answer, and it names them in the
17
- * refusal; there is nothing to duplicate here beyond letting them through.
18
- */
19
- const SCENE_FIELD_TYPES = new Set([
20
- 'SingleSelect', 'MultiSelect', 'ImageSingleSelect', 'ImageMultiSelect', 'TrueOrFalse', 'DropDownSelect',
21
- 'FillInBlank', 'ShortAnswer', 'FillInNumber', 'Rating', 'Nps',
22
- 'Department', 'Grade'
23
- ]);
24
- export function parseJsonPayload(value) {
25
- try {
26
- return JSON.parse(value);
27
- }
28
- catch (error) {
29
- throw new Error(`Invalid JSON payload: ${error.message}`);
30
- }
31
- }
32
- export function validateCreateFormPayload(payload) {
1
+ import { UsageError } from './errors.js';
2
+ export function validateContainerPayload(payload, what) {
33
3
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
34
- throw new Error('Form payload must be a JSON object');
35
- }
36
- const form = payload;
37
- if (typeof form.name !== 'string' || form.name.trim() === '') {
38
- throw new Error('Form payload requires non-empty name');
4
+ throw new UsageError(`the ${what} payload must be a JSON object`);
39
5
  }
40
- if (!Array.isArray(form.fields) || form.fields.length === 0) {
41
- throw new Error('Form payload requires at least one field');
6
+ const container = payload;
7
+ if (typeof container.name !== 'string' || container.name.trim() === '') {
8
+ throw new UsageError(`the ${what} payload needs a non-empty "name"`);
42
9
  }
43
- for (const field of form.fields) {
44
- if (!field || typeof field !== 'object' || Array.isArray(field)) {
45
- throw new Error('Each field must be an object');
46
- }
47
- const fieldObject = field;
48
- if ('api_code' in fieldObject) {
49
- throw new Error('Do not pass api_code when creating fields; backend generates it');
50
- }
51
- if (typeof fieldObject.type !== 'string' || !(API_V1_FIELD_TYPES.has(fieldObject.type) || SCENE_FIELD_TYPES.has(fieldObject.type))) {
52
- throw new Error(`Field type must be an API v1 field type, got ${String(fieldObject.type)}`);
53
- }
54
- if (typeof fieldObject.label !== 'string' && fieldObject.type !== 'PageBreak') {
55
- throw new Error('Each field requires label');
56
- }
10
+ if (container.fields !== undefined) {
11
+ if (!Array.isArray(container.fields))
12
+ throw new UsageError('"fields" must be a list of field objects');
13
+ container.fields.forEach((field, index) => {
14
+ if (!field || typeof field !== 'object' || Array.isArray(field)) {
15
+ throw new UsageError(`fields[${index}] must be an object`);
16
+ }
17
+ const shape = field;
18
+ if ('api_code' in shape) {
19
+ throw new UsageError(`fields[${index}] carries an api_code; leave it out, the backend assigns one`);
20
+ }
21
+ if (typeof shape.type !== 'string' || shape.type === '') {
22
+ throw new UsageError(`fields[${index}] needs a "type"; run \`jinshuju field types\` for the list`);
23
+ }
24
+ });
57
25
  }
58
- return form;
26
+ return container;
59
27
  }
@@ -0,0 +1,21 @@
1
+ import type { OutputFormat } from './options.js';
2
+ export declare function terminalWidth(stream?: NodeJS.WriteStream): number;
3
+ export declare function json(value: unknown): string;
4
+ /**
5
+ * One JSON object per line, which is what `jq -c`, a shell loop and a log
6
+ * shipper all read without holding the whole answer first. A listing becomes
7
+ * its rows, one each; anything else is one line.
8
+ */
9
+ export declare function jsonl(value: unknown, listKey?: string): string;
10
+ /**
11
+ * What a command knows about the shape of its answer that no renderer could
12
+ * read off the payload: which key holds the listing when it is not `data`, and
13
+ * which lists inside a row are the answer rather than detail.
14
+ */
15
+ export type TextHints = {
16
+ readonly list?: string;
17
+ readonly essentialLists?: readonly string[];
18
+ };
19
+ /** The payload in the format asked for. */
20
+ export declare function format(value: unknown, output: OutputFormat, width: number, hints?: TextHints): string;
21
+ export declare function text(value: unknown, width: number, hints?: TextHints): string;
package/dist/render.js ADDED
@@ -0,0 +1,315 @@
1
+ import { isRecord, isScalar } from './values.js';
2
+ /**
3
+ * How a response is put on the page. `--output json` is the payload as the
4
+ * API answered it; text is the same payload laid out for a person: a table
5
+ * where the rows are alike, `key: value` where they are not, and nothing a
6
+ * reader has to parse braces to find.
7
+ */
8
+ const MAX_CELL = 120;
9
+ /** What a table is allowed to be wide when nobody is watching it on a screen. */
10
+ const PIPED_WIDTH = 120;
11
+ /** Columns that say which row this is; they earn their place before any value. */
12
+ const LEADING_COLUMNS = [
13
+ 'token',
14
+ 'api_code',
15
+ 'serial_number',
16
+ 'id',
17
+ 'name',
18
+ 'title',
19
+ 'label',
20
+ 'type',
21
+ 'state',
22
+ 'status'
23
+ ];
24
+ /**
25
+ * Timestamps go last, however early they appear in the payload. On a listing of
26
+ * rows they are the least of what the reader came for, and taking them in
27
+ * payload order is what left `entry list` showing two of a form's ten fields.
28
+ */
29
+ const TRAILING_COLUMNS = ['created_at', 'updated_at'];
30
+ /**
31
+ * A column that names the row rather than saying anything about it. The listed
32
+ * ones plus whatever ends in `_token` or `_id`, because a search answers with
33
+ * `form_token` and a row showing only that has told the reader nothing.
34
+ */
35
+ function identifies(column) {
36
+ return LEADING_COLUMNS.includes(column) || /(^|_)(token|id)$/.test(column);
37
+ }
38
+ export function terminalWidth(stream = process.stdout) {
39
+ return stream.isTTY && stream.columns > 0 ? stream.columns : PIPED_WIDTH;
40
+ }
41
+ export function json(value) {
42
+ return JSON.stringify(value, null, 2);
43
+ }
44
+ /**
45
+ * One JSON object per line, which is what `jq -c`, a shell loop and a log
46
+ * shipper all read without holding the whole answer first. A listing becomes
47
+ * its rows, one each; anything else is one line.
48
+ */
49
+ export function jsonl(value, listKey) {
50
+ const rows = listOf(value, listKey);
51
+ return (rows ?? [value]).map((row) => JSON.stringify(row)).join('\n');
52
+ }
53
+ /** The rows a payload carries, when it is a listing. */
54
+ function listOf(value, listKey) {
55
+ if (Array.isArray(value))
56
+ return value;
57
+ if (!isRecord(value))
58
+ return undefined;
59
+ const key = listKey ?? 'data';
60
+ return Array.isArray(value[key]) ? value[key] : undefined;
61
+ }
62
+ /** The payload in the format asked for. */
63
+ export function format(value, output, width, hints = {}) {
64
+ if (output === 'json')
65
+ return json(value);
66
+ if (output === 'jsonl')
67
+ return jsonl(value, hints.list);
68
+ return text(value, width, hints);
69
+ }
70
+ export function text(value, width, hints = {}) {
71
+ return render(value, { width, list: hints.list ?? 'data', essentialLists: hints.essentialLists ?? [] });
72
+ }
73
+ function render(value, layout) {
74
+ if (typeof value === 'string')
75
+ return value;
76
+ if (value === undefined || value === null)
77
+ return '';
78
+ if (Array.isArray(value))
79
+ return renderList(value, layout);
80
+ if (typeof value === 'object')
81
+ return renderObject(value, layout);
82
+ return String(value);
83
+ }
84
+ function renderObject(value, layout) {
85
+ const listKey = Array.isArray(value[layout.list]) ? layout.list : undefined;
86
+ if (listKey) {
87
+ // Everything beside the listing is rendered, not just its scalars. Filtering
88
+ // to scalars here was another way for a payload to lose a key on the way to
89
+ // the page — the warnings an import answers with, say.
90
+ const heading = Object.entries(value)
91
+ .filter(([key]) => key !== listKey)
92
+ .map(([key, fieldValue]) => renderEntry(key, fieldValue, layout));
93
+ const listText = renderList(value[listKey], layout);
94
+ // A response that is nothing but the listing has nothing to separate it
95
+ // from, and `data:` on its own line is the JSON envelope showing through.
96
+ if (heading.length === 0)
97
+ return listText;
98
+ return [...heading, `${listKey}:`, listText].filter(Boolean).join('\n');
99
+ }
100
+ const entries = Object.entries(value);
101
+ if (entries.length === 0)
102
+ return '{}';
103
+ return entries.map(([key, fieldValue]) => renderEntry(key, fieldValue, layout)).join('\n');
104
+ }
105
+ /**
106
+ * A setting is an object of objects, and printing it as JSON asks the reader to
107
+ * parse braces to find one flag. Nesting goes one indent deeper instead, so the
108
+ * shape stays visible and every leaf reads as `key: value`.
109
+ */
110
+ function renderEntry(key, value, layout) {
111
+ if (Array.isArray(value)) {
112
+ return value.length === 0 ? `${key}: (empty)` : `${key}:\n${indent(renderList(value, layout))}`;
113
+ }
114
+ if (value !== null && typeof value === 'object') {
115
+ const block = renderObject(value, layout);
116
+ return block === '{}' ? `${key}: {}` : `${key}:\n${indent(block)}`;
117
+ }
118
+ return `${key}: ${formatCell(value)}`;
119
+ }
120
+ function indent(block) {
121
+ return block
122
+ .split('\n')
123
+ .map((line) => (line ? ` ${line}` : line))
124
+ .join('\n');
125
+ }
126
+ function renderList(values, layout) {
127
+ if (values.length === 0)
128
+ return '(empty)';
129
+ if (!values.every(isRecord))
130
+ return values.map((item) => formatField(item)).join('\n');
131
+ const { rows, headings } = splitLabels(values.map(unwrapKeyed));
132
+ if (rows.some((row) => hasEssentialList(row, layout.essentialLists))) {
133
+ return rows.map((row) => renderObject(row, layout)).join('\n\n');
134
+ }
135
+ const heading = (column) => headings.get(column) ?? column;
136
+ const candidates = candidateColumns(rows);
137
+ if (candidates.length === 0)
138
+ return rows.map((row) => json(row)).join('\n');
139
+ const columns = [];
140
+ const widths = [];
141
+ let used = 0;
142
+ for (const column of candidates) {
143
+ const columnWidth = Math.max(displayWidth(heading(column)), ...rows.map((row) => displayWidth(formatCell(row[column]))));
144
+ const next = used + (columns.length === 0 ? 0 : 2) + columnWidth;
145
+ // The first column goes in whatever it costs: a table of nothing is worse
146
+ // than a table too wide.
147
+ if (columns.length > 0 && next > layout.width)
148
+ break;
149
+ columns.push(column);
150
+ widths.push(columnWidth);
151
+ used = next;
152
+ }
153
+ // A row that says nothing but its own name says nothing at all — and the
154
+ // column that would have explained it is exactly the one a narrow terminal
155
+ // drops. `entry search` keeps a form it could not read *with the reason*, and
156
+ // the budget must not be what throws that reason away. A row left with only
157
+ // its identity buys back one column, whatever the width says.
158
+ const told = (row, column) => !identifies(column) && formatCell(row[column]) !== '';
159
+ for (const row of rows) {
160
+ if (columns.some((column) => told(row, column)))
161
+ continue;
162
+ const rescued = candidates.find((column) => !columns.includes(column) && told(row, column));
163
+ if (!rescued)
164
+ continue;
165
+ columns.push(rescued);
166
+ widths.push(Math.max(displayWidth(heading(rescued)), ...rows.map((other) => displayWidth(formatCell(other[rescued])))));
167
+ }
168
+ const header = columns.map((column, index) => pad(heading(column), widths[index])).join(' ');
169
+ const separator = widths.map((columnWidth) => '-'.repeat(columnWidth)).join(' ');
170
+ const body = rows.map((row) => columns.map((column, index) => pad(formatCell(row[column]), widths[index])).join(' '));
171
+ return [header, separator, ...body].join('\n');
172
+ }
173
+ /**
174
+ * Every column the rows could show, best first. How many of them fit is the
175
+ * caller's question, and it needs their widths to answer it.
176
+ */
177
+ function candidateColumns(rows) {
178
+ const present = (key) => rows.some((row) => Object.prototype.hasOwnProperty.call(row, key) && isCell(row[key]));
179
+ const seen = new Set(LEADING_COLUMNS.filter(present));
180
+ for (const row of rows) {
181
+ for (const [key, value] of Object.entries(row)) {
182
+ if (isCell(value) && !TRAILING_COLUMNS.includes(key))
183
+ seen.add(key);
184
+ }
185
+ }
186
+ for (const key of TRAILING_COLUMNS.filter(present))
187
+ seen.add(key);
188
+ return [...seen];
189
+ }
190
+ /**
191
+ * A form's fields arrive as `{ "field_1": { label, type, ... } }`, one key per
192
+ * row. A table of those reads as a column per field and nothing in it, so the
193
+ * key becomes a cell of its own row instead.
194
+ */
195
+ function unwrapKeyed(row) {
196
+ const entries = Object.entries(row);
197
+ if (entries.length !== 1)
198
+ return row;
199
+ const [key, value] = entries[0];
200
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
201
+ return row;
202
+ return { api_code: key, ...value };
203
+ }
204
+ /**
205
+ * `--labels` answers each field as `{ label, value }`. A cell cannot hold a
206
+ * pair, and a column of pairs is no column at all — which is why the values
207
+ * used to vanish from the table entirely. The pair is split instead: the value
208
+ * becomes the cell, the label becomes the column's heading. Columns stay keyed
209
+ * by api_code, because two fields may carry the same label.
210
+ */
211
+ function splitLabels(rows) {
212
+ const headings = new Map();
213
+ const split = rows.map((row) => {
214
+ const out = {};
215
+ for (const [key, value] of Object.entries(row)) {
216
+ if (!isLabelled(value)) {
217
+ out[key] = value;
218
+ continue;
219
+ }
220
+ const { label, value: cell } = value;
221
+ if (typeof label === 'string' && label !== '')
222
+ headings.set(key, label);
223
+ out[key] = cell;
224
+ }
225
+ return out;
226
+ });
227
+ return { rows: split, headings };
228
+ }
229
+ function isLabelled(value) {
230
+ if (!isRecord(value))
231
+ return false;
232
+ const keys = Object.keys(value);
233
+ return keys.length === 2 && keys.includes('label') && keys.includes('value');
234
+ }
235
+ /**
236
+ * A row carrying a list of its own has no cell a table could put it in, and the
237
+ * table drops it. Usually that is the right trade — a field's `choices` are
238
+ * detail, and the row still says what the field is. An analysis' buckets are
239
+ * not detail: they are the answer, and a table of `entry summary` without them
240
+ * prints how many people answered and never what they answered.
241
+ *
242
+ * Which is which is not readable off the shape — both are a list of objects
243
+ * beside a handful of scalars — so the command names the lists worth breaking
244
+ * the table for, in its `text` hints.
245
+ */
246
+ function hasEssentialList(row, essential) {
247
+ return essential.some((key) => {
248
+ const value = row[key];
249
+ return Array.isArray(value) && value.length > 0 && value.every(isRecord);
250
+ });
251
+ }
252
+ /**
253
+ * Whether a value earns its key a column. A list of values does: a
254
+ * multiple-choice answer is a list, and so is the `serial_numbers` a search
255
+ * answers with. Treating those as unprintable dropped the column — which meant
256
+ * `--fields field_6` left out field_6, and `entry search` said how many rows
257
+ * matched without ever saying which.
258
+ *
259
+ * An empty list earns nothing, though. A column that is `[]` in every row is a
260
+ * heading with a blank under it for as far as the table goes.
261
+ */
262
+ function isCell(value) {
263
+ if (Array.isArray(value))
264
+ return value.length > 0 && value.every(isScalar);
265
+ return isScalar(value);
266
+ }
267
+ function formatField(value) {
268
+ if (isScalar(value))
269
+ return formatCell(value);
270
+ return json(value);
271
+ }
272
+ function formatCell(value) {
273
+ if (value === undefined || value === null)
274
+ return '';
275
+ if (typeof value === 'string')
276
+ return clip(value);
277
+ if (typeof value === 'number' || typeof value === 'boolean')
278
+ return String(value);
279
+ if (Array.isArray(value) && value.every(isScalar))
280
+ return clip(value.map(formatCell).join(', '));
281
+ return clip(JSON.stringify(value));
282
+ }
283
+ /**
284
+ * One rich text field is longer than the rest of a form put together, and it
285
+ * wraps over a screen of terminal. Text is the readable format; whoever wants
286
+ * the whole value asks for --output json.
287
+ */
288
+ function clip(value) {
289
+ return value.length <= MAX_CELL ? value : `${value.slice(0, MAX_CELL)}… (${value.length} chars)`;
290
+ }
291
+ /**
292
+ * A column is padded to what the terminal shows, not to how many code points
293
+ * the value holds: a Chinese label takes two cells per character, so counting
294
+ * length leaves every table with a Chinese column ragged.
295
+ */
296
+ function pad(value, width) {
297
+ return value + ' '.repeat(Math.max(0, width - displayWidth(value)));
298
+ }
299
+ function displayWidth(value) {
300
+ let width = 0;
301
+ for (const char of value)
302
+ width += isWide(char.codePointAt(0)) ? 2 : 1;
303
+ return width;
304
+ }
305
+ function isWide(code) {
306
+ return ((code >= 0x1100 && code <= 0x115f) ||
307
+ (code >= 0x2e80 && code <= 0xa4cf) ||
308
+ (code >= 0xac00 && code <= 0xd7a3) ||
309
+ (code >= 0xf900 && code <= 0xfaff) ||
310
+ (code >= 0xfe30 && code <= 0xfe6f) ||
311
+ (code >= 0xff00 && code <= 0xff60) ||
312
+ (code >= 0xffe0 && code <= 0xffe6) ||
313
+ (code >= 0x1f300 && code <= 0x1faff) ||
314
+ (code >= 0x20000 && code <= 0x3fffd));
315
+ }
@@ -0,0 +1,31 @@
1
+ import type { HttpClient } from './http.js';
2
+ import type { OutputFormat } from './options.js';
3
+ export type CliResult = {
4
+ exitCode: number;
5
+ stdout: string;
6
+ stderr: string;
7
+ };
8
+ export type CliRuntime = {
9
+ env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
10
+ client?: HttpClient;
11
+ stdin?: () => string;
12
+ /**
13
+ * Where a streaming command writes as it goes. Without it, what would have
14
+ * streamed is gathered into the result instead, which is what a test wants.
15
+ */
16
+ stdout?: (chunk: string) => void;
17
+ /** How wide a table may be. Defaults to the terminal, or 120 through a pipe. */
18
+ width?: number;
19
+ };
20
+ export declare function ok(stdout: string): CliResult;
21
+ /**
22
+ * A failure, sorted into its kind. The exit code says which kind without
23
+ * anything being parsed; with `--output json` stderr carries the same in
24
+ * words, plus whatever status and body the server answered with, so a script
25
+ * that reads JSON on the way in reads JSON on the way out as well.
26
+ */
27
+ export declare function fail(error: unknown, output: OutputFormat): CliResult;
28
+ /** An unknown command is a usage error, and in text mode the help is the message. */
29
+ export declare function unknown(words: readonly string[], output: OutputFormat): CliResult;
30
+ /** What `--output` asked for, read before the flags are checked so a failure can honour it. */
31
+ export declare function outputOf(flags: Record<string, unknown>): OutputFormat;
package/dist/result.js ADDED
@@ -0,0 +1,32 @@
1
+ import { EXIT_CODES, UsageError, classify } from './errors.js';
2
+ import { unknownCommandHelp } from './help.js';
3
+ import { json } from './render.js';
4
+ export function ok(stdout) {
5
+ return { exitCode: 0, stdout: stdout.endsWith('\n') ? stdout : `${stdout}\n`, stderr: '' };
6
+ }
7
+ /**
8
+ * A failure, sorted into its kind. The exit code says which kind without
9
+ * anything being parsed; with `--output json` stderr carries the same in
10
+ * words, plus whatever status and body the server answered with, so a script
11
+ * that reads JSON on the way in reads JSON on the way out as well.
12
+ */
13
+ export function fail(error, output) {
14
+ const sorted = classify(error);
15
+ if (output !== 'text') {
16
+ const { exitCode, ...envelope } = sorted;
17
+ return { exitCode, stdout: '', stderr: `${json({ error: envelope })}\n` };
18
+ }
19
+ const wait = sorted.retry_after === undefined ? '' : ` Retry after ${sorted.retry_after}s.`;
20
+ return { exitCode: sorted.exitCode, stdout: '', stderr: `Error: ${sorted.message}${wait}\n` };
21
+ }
22
+ /** An unknown command is a usage error, and in text mode the help is the message. */
23
+ export function unknown(words, output) {
24
+ if (output !== 'text')
25
+ return fail(new UsageError(`Unknown command: jinshuju ${words.join(' ')}`), output);
26
+ return { exitCode: EXIT_CODES.usage, stdout: '', stderr: unknownCommandHelp(words) };
27
+ }
28
+ /** What `--output` asked for, read before the flags are checked so a failure can honour it. */
29
+ export function outputOf(flags) {
30
+ const asked = flags['--output'];
31
+ return asked === 'json' || asked === 'jsonl' ? asked : 'text';
32
+ }
@@ -0,0 +1,4 @@
1
+ /** A plain object: something with keys, that is not a list. */
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
3
+ /** A value with nothing inside it: text, a number, a boolean, or null. */
4
+ export declare function isScalar(value: unknown): boolean;
package/dist/values.js ADDED
@@ -0,0 +1,8 @@
1
+ /** A plain object: something with keys, that is not a list. */
2
+ export function isRecord(value) {
3
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ }
5
+ /** A value with nothing inside it: text, a number, a boolean, or null. */
6
+ export function isScalar(value) {
7
+ return value === null || ['string', 'number', 'boolean'].includes(typeof value);
8
+ }