@jinshuju/cli 0.1.3 → 0.3.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 +80 -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 +20 -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 +723 -0
  14. package/dist/commands/field.d.ts +3 -0
  15. package/dist/commands/field.js +261 -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 +412 -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 -1690
@@ -0,0 +1,57 @@
1
+ import { type OptionSpec } from '../options.js';
2
+ import type { CommandInput, Pagination } from './types.js';
3
+ /** What more than one resource's commands build their requests from. */
4
+ export declare const API = "/api/v1";
5
+ /** The path segment a container lives under. */
6
+ export declare function containerPath(input: CommandInput): string;
7
+ /** The conditions themselves. A read sends them as a query string, a write as a body. */
8
+ export declare function filterConditions(input: CommandInput): unknown;
9
+ export declare function filters(input: CommandInput): string | undefined;
10
+ export declare function sort(input: CommandInput, key: 'api_code' | 'field'): string | undefined;
11
+ export declare function paging(input: CommandInput): Record<string, string | undefined>;
12
+ /** The sort rules as the API's own objects, for a body. */
13
+ export declare function sortRules(input: CommandInput): {
14
+ api_code: string;
15
+ order: string;
16
+ }[] | undefined;
17
+ /**
18
+ * A delete says so out loud. Nothing here prompts — stdin belongs to `--json -`
19
+ * — so the confirmation is a flag, and leaving it out is the safe outcome
20
+ * rather than a question nobody is there to answer.
21
+ */
22
+ export declare function confirmed(input: CommandInput, what: string): void;
23
+ /**
24
+ * Drops the keys an optional flag left undefined. JSON.stringify would drop
25
+ * them on the wire anyway, but a body that carries them reads as though the
26
+ * caller asked for the field to be unset, and shows up that way in --output
27
+ * json and in anything asserting on the request.
28
+ */
29
+ export declare function given<T extends Record<string, unknown>>(body: T): Partial<T>;
30
+ /**
31
+ * A payload with the flags that were actually given laid over it.
32
+ *
33
+ * The obvious spelling — spread the payload, then assign each flag — writes
34
+ * `undefined` for every flag the caller left out, and that erases whatever the
35
+ * payload said. Someone asking for an exam form through --json got a plain one
36
+ * and no error. Only the flags that were given may override.
37
+ */
38
+ export declare function overriding(payload: Record<string, unknown>, flags: Record<string, unknown>): Record<string, unknown>;
39
+ /** A write that names one thing still sends the API a list of one. */
40
+ export declare function one(value: unknown): unknown[];
41
+ export declare const YES_OPTION: OptionSpec;
42
+ export declare const FOLDER_OPTION: OptionSpec;
43
+ /**
44
+ * `--mine` is a different range, not a narrower one: it reads what the caller
45
+ * submitted to forms they need not own. The flags that describe the owner-side
46
+ * question have no counterpart there, so naming one alongside --mine is
47
+ * refused rather than quietly dropped.
48
+ */
49
+ export declare function refuseWithMine(input: CommandInput, flags: readonly string[]): void;
50
+ /**
51
+ * Keywords stay separate: the API matches a name containing any of them, and
52
+ * joining them would ask for one keyword with a comma in it.
53
+ */
54
+ export declare function keywords(value: unknown): readonly string[] | undefined;
55
+ export declare const LISTING: Pagination;
56
+ export declare function payload(input: CommandInput): unknown;
57
+ export declare function requiredOption(input: CommandInput, key: string): string;
@@ -0,0 +1,122 @@
1
+ import { UsageError, parseFilter, parseSort, resolveContainer } from '../options.js';
2
+ /** What more than one resource's commands build their requests from. */
3
+ export const API = '/api/v1';
4
+ /** The path segment a container lives under. */
5
+ export function containerPath(input) {
6
+ const { token, kind } = resolveContainer(input.options);
7
+ return `${API}/${kind === 'table' ? 'tables' : 'forms'}/${token}`;
8
+ }
9
+ /** The conditions themselves. A read sends them as a query string, a write as a body. */
10
+ export function filterConditions(input) {
11
+ const compact = input.options.filter ?? [];
12
+ const raw = input.options.filters;
13
+ if (raw !== undefined && compact.length > 0) {
14
+ throw new UsageError('--filter and --filters are alternatives, not both');
15
+ }
16
+ if (raw !== undefined)
17
+ return raw;
18
+ if (compact.length === 0)
19
+ return undefined;
20
+ const conditions = compact.map(parseFilter);
21
+ return conditions;
22
+ }
23
+ export function filters(input) {
24
+ const conditions = filterConditions(input);
25
+ return conditions === undefined ? undefined : JSON.stringify(conditions);
26
+ }
27
+ export function sort(input, key) {
28
+ const rules = input.options.sort ?? [];
29
+ if (rules.length === 0)
30
+ return undefined;
31
+ // The API names a sort key `api_code` for data and `field` for listings; the
32
+ // CLI shows one `--sort <field>:<order>` and translates here.
33
+ return JSON.stringify(rules.map(parseSort).map((rule) => ({ [key]: rule.field, order: rule.order })));
34
+ }
35
+ export function paging(input) {
36
+ return {
37
+ limit: input.options.limit === undefined ? undefined : String(input.options.limit),
38
+ next: input.options.next
39
+ };
40
+ }
41
+ /** The sort rules as the API's own objects, for a body. */
42
+ export function sortRules(input) {
43
+ const rules = input.options.sort ?? [];
44
+ if (rules.length === 0)
45
+ return undefined;
46
+ return rules.map(parseSort).map((rule) => ({ api_code: rule.field, order: rule.order }));
47
+ }
48
+ /**
49
+ * A delete says so out loud. Nothing here prompts — stdin belongs to `--json -`
50
+ * — so the confirmation is a flag, and leaving it out is the safe outcome
51
+ * rather than a question nobody is there to answer.
52
+ */
53
+ export function confirmed(input, what) {
54
+ if (!input.options.yes)
55
+ throw new UsageError(`${what} is permanent; pass --yes to go ahead`);
56
+ }
57
+ /**
58
+ * Drops the keys an optional flag left undefined. JSON.stringify would drop
59
+ * them on the wire anyway, but a body that carries them reads as though the
60
+ * caller asked for the field to be unset, and shows up that way in --output
61
+ * json and in anything asserting on the request.
62
+ */
63
+ export function given(body) {
64
+ return Object.fromEntries(Object.entries(body).filter(([, value]) => value !== undefined));
65
+ }
66
+ /**
67
+ * A payload with the flags that were actually given laid over it.
68
+ *
69
+ * The obvious spelling — spread the payload, then assign each flag — writes
70
+ * `undefined` for every flag the caller left out, and that erases whatever the
71
+ * payload said. Someone asking for an exam form through --json got a plain one
72
+ * and no error. Only the flags that were given may override.
73
+ */
74
+ export function overriding(payload, flags) {
75
+ return { ...payload, ...given(flags) };
76
+ }
77
+ /** A write that names one thing still sends the API a list of one. */
78
+ export function one(value) {
79
+ return Array.isArray(value) ? value : [value];
80
+ }
81
+ export const YES_OPTION = { name: '--yes', type: 'boolean', description: 'Confirm the deletion' };
82
+ export const FOLDER_OPTION = {
83
+ name: '--folder',
84
+ type: 'string',
85
+ placeholder: '<token>',
86
+ description: 'Folder token; empty moves it out of any folder'
87
+ };
88
+ /**
89
+ * `--mine` is a different range, not a narrower one: it reads what the caller
90
+ * submitted to forms they need not own. The flags that describe the owner-side
91
+ * question have no counterpart there, so naming one alongside --mine is
92
+ * refused rather than quietly dropped.
93
+ */
94
+ export function refuseWithMine(input, flags) {
95
+ for (const flag of flags) {
96
+ const value = input.options[flag];
97
+ const given = Array.isArray(value) ? value.length > 0 : value !== undefined;
98
+ if (given)
99
+ throw new UsageError(`--${flag.replace(/_/g, '-')} cannot be combined with --mine`);
100
+ }
101
+ }
102
+ /**
103
+ * Keywords stay separate: the API matches a name containing any of them, and
104
+ * joining them would ask for one keyword with a comma in it.
105
+ */
106
+ export function keywords(value) {
107
+ const values = value;
108
+ return values && values.length > 0 ? values : undefined;
109
+ }
110
+ export const LISTING = { items: 'data', cursor: 'next' };
111
+ export function payload(input) {
112
+ const value = input.options.json;
113
+ if (value === undefined)
114
+ throw new UsageError('--json <json|@file|-> is required');
115
+ return value;
116
+ }
117
+ export function requiredOption(input, key) {
118
+ const value = input.options[key];
119
+ if (!value)
120
+ throw new UsageError(`--${key.replace(/_/g, '-')} is required`);
121
+ return value;
122
+ }
@@ -0,0 +1,2 @@
1
+ import type { Command } from './types.js';
2
+ export declare const TABLE: readonly Command[];
@@ -0,0 +1,101 @@
1
+ import { FILTER_OPTION, FILTERS_OPTION, JSON_OPTION, PAGINATION_OPTIONS, SORT_OPTION } from '../options.js';
2
+ import { API, FOLDER_OPTION, LISTING, filters, keywords, overriding, paging, payload, sort } from './shared.js';
3
+ import { validateContainerPayload } from '../payload.js';
4
+ /**
5
+ * The field types a table column may be, which is a third of what a form takes.
6
+ * Worth naming in the help rather than leaving to a rejected create: the absence
7
+ * of TextField is the one nobody guesses.
8
+ */
9
+ const TABLE_FIELD_TYPES = [
10
+ 'TextArea',
11
+ 'RadioButton',
12
+ 'CheckBox',
13
+ 'BooleanField',
14
+ 'MobileField',
15
+ 'NumberField',
16
+ 'DateTimeField',
17
+ 'EmailField',
18
+ 'LinkField',
19
+ 'AttachmentField',
20
+ 'FormulaField'
21
+ ];
22
+ export const TABLE = [
23
+ {
24
+ path: ['table', 'list'],
25
+ summary: 'List tables',
26
+ options: [
27
+ {
28
+ name: '--name',
29
+ type: 'string',
30
+ repeatable: true,
31
+ placeholder: '<kw>',
32
+ description: 'Match tables whose name contains the keyword'
33
+ },
34
+ FILTER_OPTION,
35
+ FILTERS_OPTION,
36
+ SORT_OPTION,
37
+ ...PAGINATION_OPTIONS
38
+ ],
39
+ request: (input) => ({
40
+ method: 'GET',
41
+ path: `${API}/tables`,
42
+ query: { q: keywords(input.options.name), filters: filters(input), sort: sort(input, 'field'), ...paging(input) }
43
+ }),
44
+ paginate: LISTING,
45
+ examples: ['jinshuju table list --name 台账', 'jinshuju entry list --table Vn4xR8']
46
+ },
47
+ {
48
+ path: ['table', 'get'],
49
+ summary: 'Show a table: columns, types, choices',
50
+ args: [{ name: 'table', required: true, description: 'Table token, six letters and digits, e.g. Vn4xR8' }],
51
+ request: (input) => ({ method: 'GET', path: `${API}/tables/${input.args.table}` }),
52
+ examples: ['jinshuju table get Vn4xR8']
53
+ },
54
+ {
55
+ path: ['table', 'create'],
56
+ summary: 'Create a table',
57
+ description: 'Column types use the API v1 names, but a table takes fewer of them than a form: ' +
58
+ `${TABLE_FIELD_TYPES.join(', ')}. There is no TextField — a single line of text is a ` +
59
+ 'TextArea here. Do not pass api_code: the backend generates it.',
60
+ options: [
61
+ JSON_OPTION,
62
+ FOLDER_OPTION,
63
+ {
64
+ name: '--with-default-entries',
65
+ type: 'boolean',
66
+ description: 'Seed a few blank rows, as the UI does. Leave it off when rows follow'
67
+ }
68
+ ],
69
+ request: (input) => ({
70
+ method: 'POST',
71
+ path: `${API}/tables`,
72
+ body: overriding(validateContainerPayload(payload(input), 'table'), {
73
+ folder_token: input.options.folder,
74
+ with_default_entries: input.options.with_default_entries ? true : undefined
75
+ })
76
+ }),
77
+ examples: ['jinshuju table create --json @table.json']
78
+ },
79
+ {
80
+ path: ['table', 'move'],
81
+ summary: 'Move a table into a folder, or out of one',
82
+ description: 'The folder must be a table folder; a form folder cannot hold a table.',
83
+ args: [{ name: 'table', required: true, description: 'Table token' }],
84
+ options: [FOLDER_OPTION],
85
+ request: (input) => ({
86
+ method: 'PATCH',
87
+ path: `${API}/tables/${input.args.table}/folder`,
88
+ body: { folder_token: input.options.folder ?? '' }
89
+ }),
90
+ examples: ['jinshuju table move Vn4xR8 --folder Nf7mDC', 'jinshuju table move Vn4xR8']
91
+ },
92
+ {
93
+ path: ['table', 'edit'],
94
+ summary: 'Edit a table',
95
+ description: 'The payload carries the operations to apply: name, description, setting, and columns as ' +
96
+ 'fields: {add, update, update_choices, remove}.',
97
+ args: [{ name: 'table', required: true, description: 'Table token' }],
98
+ options: [JSON_OPTION],
99
+ request: (input) => ({ method: 'PATCH', path: `${API}/tables/${input.args.table}`, body: payload(input) })
100
+ }
101
+ ];
@@ -1,14 +1,6 @@
1
- import { JSON_OPTION, type OptionSpec } from './options.js';
2
- import type { HttpClient } from './http.js';
3
- /**
4
- * Every command the CLI has, as data.
5
- *
6
- * The shape is `jinshuju <resource> <verb> [args] [flags]`: resources kept at
7
- * one level, the parent given by a flag —
8
- * `entry list --form <token>`, not `form entry list <token>`. Help, argument
9
- * checking and dispatch all read this table, so a command cannot be reachable
10
- * without its help, nor accept a flag it never described.
11
- */
1
+ import type { HttpClient, HttpRequest } from '../http.js';
2
+ import type { OptionSpec } from '../options.js';
3
+ import type { TextHints } from '../render.js';
12
4
  export interface ArgSpec {
13
5
  readonly name: string;
14
6
  readonly required: boolean;
@@ -16,16 +8,6 @@ export interface ArgSpec {
16
8
  readonly variadic?: boolean;
17
9
  readonly description: string;
18
10
  }
19
- /** A repeated parameter arrives as a list; everything else is one value. */
20
- export type QueryValues = Record<string, string | readonly string[] | undefined>;
21
- export interface HttpRequest {
22
- readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
23
- readonly path: string;
24
- readonly query?: QueryValues;
25
- readonly body?: unknown;
26
- /** A multipart body, for the endpoints that take a file. */
27
- readonly form?: FormData;
28
- }
29
11
  /** How a listing returns its next page, which is what `--all` follows. */
30
12
  export interface Pagination {
31
13
  readonly items: string;
@@ -52,18 +34,24 @@ export interface Command {
52
34
  */
53
35
  readonly payload?: readonly string[];
54
36
  readonly examples?: readonly string[];
37
+ /** The one request the command is. Most commands are this and nothing else. */
55
38
  readonly request?: (input: CommandInput) => HttpRequest;
56
39
  /**
57
- * For the commands a single request cannot express: uploading a file and then
58
- * acting on it. It gets the client and returns whatever should be printed.
40
+ * For the commands a single request cannot express, or that have to decide
41
+ * how many they are: uploading a file and then acting on it. It gets the
42
+ * client and returns whatever should be printed. A command has one of
43
+ * `request` and `run`, never both.
59
44
  */
60
45
  readonly run?: (input: CommandInput, client: HttpClient) => Promise<unknown>;
61
46
  readonly paginate?: Pagination;
62
47
  /**
63
48
  * Narrows the response to what the command is about. `field list` asks for a
64
49
  * form because that is where fields live, but a caller asked for the fields.
50
+ * It gets the input too, because what a write touched is known from what was
51
+ * sent: a field patch answers with the whole form, and only the caller's
52
+ * api_code says which row of it the caller meant.
65
53
  */
66
- readonly select?: (body: unknown) => unknown;
54
+ readonly select?: (body: unknown, input: CommandInput) => unknown;
67
55
  /**
68
56
  * Reshapes the response for reading, and only for reading: `--output json`
69
57
  * answers what the API answered. A command needs this when its payload is
@@ -71,14 +59,20 @@ export interface Command {
71
59
  * could know how to put it back together.
72
60
  */
73
61
  readonly render?: (body: unknown) => unknown;
62
+ /**
63
+ * What the text renderer cannot read off the payload: the key holding the
64
+ * listing when it is not `data` or the paginated one, and the lists inside
65
+ * a row that are the answer rather than detail.
66
+ */
67
+ readonly text?: TextHints;
74
68
  }
75
69
  export interface Resource {
76
70
  readonly name: string;
77
71
  readonly summary: string;
72
+ /**
73
+ * Shown under the resource's verbs. For what a caller will look for here and
74
+ * not find: a missing verb is indistinguishable from a verb named something
75
+ * else unless the help says which it is.
76
+ */
77
+ readonly note?: string;
78
78
  }
79
- /** Resource order in the root help, and the one-liner each gets. */
80
- export declare const RESOURCES: readonly Resource[];
81
- export declare const COMMANDS: readonly Command[];
82
- /** The command whose path the words begin with, longest match first. */
83
- export declare function findCommand(words: readonly string[], commands?: readonly Command[]): Command | undefined;
84
- export { JSON_OPTION };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { HttpRequest } from '../http.js';
2
+ /**
3
+ * A file on disk, as multipart. The three endpoints that take one authenticate
4
+ * like every other request, so there is no ticket to fetch first: the file goes
5
+ * up in one call and comes back with an id to refer to it by.
6
+ */
7
+ export declare function upload(path: string, file: string, extra?: Record<string, string>): HttpRequest;
@@ -0,0 +1,40 @@
1
+ import { UsageError } from '../options.js';
2
+ import { readFileSync } from 'node:fs';
3
+ import { basename, extname } from 'node:path';
4
+ /**
5
+ * The media type of an upload, by extension. The server stores the type the
6
+ * multipart part declares and decides from it what the file may be used for, so
7
+ * an untyped part is an .xlsx it refuses as not a spreadsheet.
8
+ */
9
+ const UPLOAD_TYPES = {
10
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
11
+ '.xlsm': 'application/vnd.ms-excel.sheet.macroEnabled.12',
12
+ '.xls': 'application/vnd.ms-excel',
13
+ '.csv': 'text/csv',
14
+ '.png': 'image/png',
15
+ '.jpg': 'image/jpeg',
16
+ '.jpeg': 'image/jpeg',
17
+ '.gif': 'image/gif',
18
+ '.webp': 'image/webp',
19
+ '.pdf': 'application/pdf'
20
+ };
21
+ /**
22
+ * A file on disk, as multipart. The three endpoints that take one authenticate
23
+ * like every other request, so there is no ticket to fetch first: the file goes
24
+ * up in one call and comes back with an id to refer to it by.
25
+ */
26
+ export function upload(path, file, extra = {}) {
27
+ const form = new FormData();
28
+ let bytes;
29
+ try {
30
+ bytes = readFileSync(file);
31
+ }
32
+ catch (error) {
33
+ throw new UsageError(`could not read ${file}: ${error.message}`);
34
+ }
35
+ const type = UPLOAD_TYPES[extname(file).toLowerCase()];
36
+ form.append('file', new Blob([new Uint8Array(bytes)], type ? { type } : undefined), basename(file));
37
+ for (const [name, value] of Object.entries(extra))
38
+ form.append(name, value);
39
+ return { method: 'POST', path, form };
40
+ }
@@ -0,0 +1,2 @@
1
+ import type { Command } from './types.js';
2
+ export declare const VIEW: readonly Command[];
@@ -0,0 +1,81 @@
1
+ import { CONTAINER_OPTIONS, FILTER_OPTION, FILTERS_OPTION, JSON_OPTION, SORT_OPTION } from '../options.js';
2
+ import { YES_OPTION, confirmed, containerPath, filterConditions, overriding, sortRules } from './shared.js';
3
+ /** What `view create` and `view edit` both take, beyond the name. */
4
+ const VIEW_OPTIONS = [
5
+ {
6
+ name: '--type',
7
+ type: 'string',
8
+ choices: ['grid', 'kanban', 'stats'],
9
+ placeholder: '<type>',
10
+ description: 'View type'
11
+ },
12
+ { name: '--columns', type: 'list', placeholder: '<api-code,...>', description: 'Columns to show, in this order' },
13
+ FILTER_OPTION,
14
+ FILTERS_OPTION,
15
+ SORT_OPTION,
16
+ JSON_OPTION
17
+ ];
18
+ function viewBody(input) {
19
+ const rest = input.options.json ?? {};
20
+ return overriding(rest, {
21
+ view_type: input.options.type,
22
+ prefer_columns: input.options.columns,
23
+ sort: sortRules(input),
24
+ filter: filterConditions(input)
25
+ });
26
+ }
27
+ export const VIEW = [
28
+ {
29
+ path: ['view', 'list'],
30
+ summary: 'List the views of a form or table',
31
+ options: [...CONTAINER_OPTIONS],
32
+ request: (input) => ({ method: 'GET', path: `${containerPath(input)}/views` })
33
+ },
34
+ {
35
+ path: ['view', 'get'],
36
+ summary: 'Show a view',
37
+ args: [{ name: 'view', required: true, description: 'View token, six letters and digits, e.g. aB3dE9' }],
38
+ options: [...CONTAINER_OPTIONS],
39
+ request: (input) => ({ method: 'GET', path: `${containerPath(input)}/views/${input.args.view}` })
40
+ },
41
+ {
42
+ path: ['view', 'create'],
43
+ summary: 'Create a view',
44
+ description: 'A view carries its own filter, sort and columns, so `entry list --view` needs none of them. ' +
45
+ 'Anything without a flag of its own — kanban grouping, visibility — goes through --json.',
46
+ args: [{ name: 'name', required: true, description: 'View name' }],
47
+ options: [...CONTAINER_OPTIONS, ...VIEW_OPTIONS],
48
+ request: (input) => ({
49
+ method: 'POST',
50
+ path: `${containerPath(input)}/views`,
51
+ body: { ...viewBody(input), name: input.args.name }
52
+ }),
53
+ examples: ["jinshuju view create --form Kp7mQ2 高分 --filter 'field_3 gte 80' --sort created_at:desc"]
54
+ },
55
+ {
56
+ path: ['view', 'edit'],
57
+ summary: 'Edit a view',
58
+ description: 'Only what is named changes; --name renames it.',
59
+ args: [{ name: 'view', required: true, description: 'View token' }],
60
+ options: [
61
+ ...CONTAINER_OPTIONS,
62
+ { name: '--name', type: 'string', placeholder: '<name>', description: 'Rename the view' },
63
+ ...VIEW_OPTIONS
64
+ ],
65
+ request: (input) => ({
66
+ method: 'PATCH',
67
+ path: `${containerPath(input)}/views/${input.args.view}`,
68
+ body: overriding(viewBody(input), { name: input.options.name })
69
+ })
70
+ },
71
+ {
72
+ path: ['view', 'delete'],
73
+ summary: 'Delete a view',
74
+ args: [{ name: 'view', required: true, description: 'View token' }],
75
+ options: [...CONTAINER_OPTIONS, YES_OPTION],
76
+ request: (input) => {
77
+ confirmed(input, `Deleting view ${input.args.view}`);
78
+ return { method: 'DELETE', path: `${containerPath(input)}/views/${input.args.view}` };
79
+ }
80
+ }
81
+ ];
package/dist/config.d.ts CHANGED
@@ -21,6 +21,8 @@ export type LoadedConfig = {
21
21
  authHost: string;
22
22
  clientId?: string;
23
23
  auth?: OAuthConfig;
24
+ /** How long one request may take, from JINSHUJU_TIMEOUT_MS; unset means the client's default. */
25
+ timeoutMs?: number;
24
26
  configPath: string;
25
27
  sources: {
26
28
  accessToken: ConfigSource;
package/dist/config.js CHANGED
@@ -1,6 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
+ import { UsageError } from './errors.js';
4
5
  export const defaultConfigPath = join(homedir(), '.jinshuju', 'config.json');
5
6
  export const defaultHost = 'https://jinshuju.net';
6
7
  export const defaultAuthHost = 'https://account.jinshuju.net';
@@ -9,11 +10,33 @@ export const defaultScopes = 'public forms read_entries write_entries form_setti
9
10
  function readConfigFile(configPath) {
10
11
  if (!existsSync(configPath))
11
12
  return {};
12
- return JSON.parse(readFileSync(configPath, 'utf8'));
13
+ const text = readFileSync(configPath, 'utf8');
14
+ let parsed;
15
+ try {
16
+ parsed = JSON.parse(text);
17
+ }
18
+ catch (error) {
19
+ throw new UsageError(`${configPath} is not valid JSON: ${error.message}. Fix it, or remove it and log in again.`, {
20
+ cause: error
21
+ });
22
+ }
23
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
24
+ throw new UsageError(`${configPath} should hold a JSON object, not ${Array.isArray(parsed) ? 'a list' : String(parsed)}`);
25
+ }
26
+ return parsed;
13
27
  }
28
+ /**
29
+ * Written whole or not at all: the file goes down beside its target and is
30
+ * renamed over it, so a crash mid-write, or two commands refreshing a token at
31
+ * once, cannot leave half a file behind. The mode is set every time, because
32
+ * the mode on writeFileSync only applies to a file that did not exist yet.
33
+ */
14
34
  function writeConfigFile(configPath, config) {
15
35
  mkdirSync(dirname(configPath), { recursive: true });
16
- writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
36
+ const draft = `${configPath}.${process.pid}.tmp`;
37
+ writeFileSync(draft, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
38
+ chmodSync(draft, 0o600);
39
+ renameSync(draft, configPath);
17
40
  }
18
41
  function pickValue(cliValue, envValue, fileValue, fallback) {
19
42
  if (cliValue)
@@ -38,6 +61,7 @@ export function loadConfig(options = {}) {
38
61
  const defaultClientId = authHost.value === defaultAuthHost ? defaultOAuthClientId : undefined;
39
62
  const clientId = pickValue(options.cli?.clientId, env.JINSHUJU_OAUTH_CLIENT_ID, file.client_id ?? file.auth?.client_id, defaultClientId);
40
63
  const auth = file.auth?.type === 'oauth' ? file.auth : undefined;
64
+ const timeoutMs = parseTimeout(env.JINSHUJU_TIMEOUT_MS);
41
65
  return {
42
66
  accessToken: accessToken.value,
43
67
  apiKey: apiKey.value,
@@ -46,6 +70,7 @@ export function loadConfig(options = {}) {
46
70
  authHost: authHost.value,
47
71
  clientId: clientId.value,
48
72
  auth,
73
+ timeoutMs,
49
74
  configPath,
50
75
  sources: {
51
76
  accessToken: accessToken.source,
@@ -58,6 +83,14 @@ export function loadConfig(options = {}) {
58
83
  }
59
84
  };
60
85
  }
86
+ /** A whole number of milliseconds, or nothing: a timeout nobody can parse is not a timeout of zero. */
87
+ function parseTimeout(value) {
88
+ if (!value)
89
+ return undefined;
90
+ if (!/^\d+$/.test(value))
91
+ throw new UsageError(`JINSHUJU_TIMEOUT_MS must be a whole number of milliseconds, got ${JSON.stringify(value)}`);
92
+ return Number.parseInt(value, 10);
93
+ }
61
94
  export function setConfigValue(configPath, key, value) {
62
95
  const config = readConfigFile(configPath);
63
96
  config[key] = value;
@@ -91,9 +124,16 @@ export function maskSecret(value) {
91
124
  return `${value.slice(0, 4)}…${value.slice(-4)}`;
92
125
  }
93
126
  /** Every key the config file holds, in the order help should list them. */
94
- export const CONFIG_KEYS = ['access_token', 'api_key', 'api_secret', 'host', 'auth_host', 'client_id'];
127
+ export const CONFIG_KEYS = [
128
+ 'access_token',
129
+ 'api_key',
130
+ 'api_secret',
131
+ 'host',
132
+ 'auth_host',
133
+ 'client_id'
134
+ ];
95
135
  export function assertConfigKey(value) {
96
136
  if (!CONFIG_KEYS.includes(value)) {
97
- throw new Error(`Config key must be one of ${CONFIG_KEYS.join(', ')}`);
137
+ throw new UsageError(`Config key must be one of ${CONFIG_KEYS.join(', ')}`);
98
138
  }
99
139
  }
@@ -0,0 +1,48 @@
1
+ /** The command line itself was wrong: a flag, an argument, an input file. */
2
+ export declare class UsageError extends Error {
3
+ name: string;
4
+ }
5
+ /** No credential, or one the server would not take. */
6
+ export declare class AuthError extends Error {
7
+ name: string;
8
+ }
9
+ /** A response the server sent and refused with. `status` and `body` are what it said. */
10
+ export declare class HttpError extends Error {
11
+ readonly status: number;
12
+ readonly body: unknown;
13
+ constructor(message: string, status: number, body: unknown);
14
+ }
15
+ /** No response at all: the connection failed, or the request ran out of time. */
16
+ export declare class TransportError extends Error {
17
+ readonly timedOut: boolean;
18
+ constructor(message: string, timedOut: boolean, cause?: unknown);
19
+ }
20
+ /**
21
+ * The server took the request and turned down what it carried: an import
22
+ * whose rows it would not write, say. Exits as a refused 4xx would.
23
+ */
24
+ export declare class RefusedError extends Error {
25
+ name: string;
26
+ }
27
+ /**
28
+ * What kind of failure it was, which is what a script branches on. The exit
29
+ * code says it without parsing anything; `--output json` also says it in
30
+ * words, alongside the status and body the server answered with.
31
+ */
32
+ export type ErrorKind = 'unexpected' | 'usage' | 'auth' | 'not_found' | 'refused' | 'server' | 'transport' | 'rate_limited';
33
+ export declare const EXIT_CODES: Readonly<Record<ErrorKind, number>>;
34
+ export type ClassifiedError = {
35
+ kind: ErrorKind;
36
+ exitCode: number;
37
+ message: string;
38
+ status?: number;
39
+ body?: unknown;
40
+ /** Seconds the server asked for before trying again, when it said. */
41
+ retry_after?: number;
42
+ };
43
+ /**
44
+ * Sorts a failure into its kind. An error that wraps another — "the form was
45
+ * created, but its settings were refused" — is sorted by what it wraps, so a
46
+ * partial failure exits the way its refused half would have.
47
+ */
48
+ export declare function classify(error: unknown): ClassifiedError;