@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10
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/CHANGELOG.md +251 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-2JV3A7OP.js +1894 -0
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BLS2OBIQ.js +263 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-GHPJJV5L.js +613 -0
- package/dist/chunk-IXVQ62NZ.js +334 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/chunk-K7VCKJ27.js +814 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-NLMS7HGP.js +178 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-C5B5tnpA.d.ts +400 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +70 -945
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-DCe1boBz.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +184 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +137 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +17 -381
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +192 -24
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +195 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +767 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +71 -0
- package/src/index.ts +46 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +222 -0
- package/src/mcp/bridge.ts +291 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +64 -3
- package/src/published-types.test.ts +133 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +410 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/src/tui/parity.json +0 -74
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module output/error
|
|
3
|
+
*
|
|
4
|
+
* Structured-error envelope. Mirrors Go's `go/console/output` error
|
|
5
|
+
* envelope: when a command fails under `--format json|yaml`, the error is
|
|
6
|
+
* materialized as a {@link CliError} and rendered to stderr by
|
|
7
|
+
* {@link renderError}. Plaintext mode (`--format table` or unset) prints
|
|
8
|
+
* `"Code: Message\nFix: ...\n"`.
|
|
9
|
+
*
|
|
10
|
+
* Fields use the on-wire snake_case keys directly (like the telemetry
|
|
11
|
+
* `Envelope`) so `JSON.stringify` is wire-exact; empty optional fields
|
|
12
|
+
* stay off the wire, mirroring Go's `omitempty`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import * as yaml from 'js-yaml';
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Transience classes
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
/** Marks a failure a retry may clear (rate limit, timeout, upstream blip). */
|
|
22
|
+
export const TRANSIENCE_TRANSIENT = 'transient';
|
|
23
|
+
/**
|
|
24
|
+
* Marks a failure retrying cannot clear without changing the input or the
|
|
25
|
+
* environment.
|
|
26
|
+
*/
|
|
27
|
+
export const TRANSIENCE_PERMANENT = 'permanent';
|
|
28
|
+
/**
|
|
29
|
+
* Marks a failure kit cannot classify. Agents should treat retries as
|
|
30
|
+
* best-effort and bounded.
|
|
31
|
+
*/
|
|
32
|
+
export const TRANSIENCE_UNKNOWN = 'unknown';
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// Standard codes mapping the cross-tool exit codes
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
export const CODE_OK = 'OK'; // exit 0
|
|
39
|
+
export const CODE_GENERIC = 'GENERIC'; // exit 1
|
|
40
|
+
export const CODE_USAGE = 'USAGE'; // exit 2
|
|
41
|
+
export const CODE_NOT_FOUND = 'NOT_FOUND'; // exit 3
|
|
42
|
+
export const CODE_CONFLICT = 'CONFLICT'; // exit 4
|
|
43
|
+
export const CODE_UNAUTHORIZED = 'UNAUTHORIZED'; // exit 5
|
|
44
|
+
export const CODE_TRANSIENT = 'TRANSIENT'; // exit 6 — Factor-11 transient/retryable failure
|
|
45
|
+
export const CODE_CONSENT_REFUSED = 'CONSENT_REFUSED'; // exit 7 — confirmation gate declined
|
|
46
|
+
export const CODE_PROVENANCE_MISSING = 'PROVENANCE_MISSING'; // exit 65 — Factor-12 strict-mode refusal
|
|
47
|
+
export const CODE_RATE_LIMITED = 'RATE_LIMITED'; // exit 64 — Factor-10 max-ops budget exceeded
|
|
48
|
+
export const CODE_PREREQUISITE = 'PREREQUISITE'; // exit 70 — declared dependency unreachable
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Success. Present for completeness so a table of the full taxonomy can
|
|
52
|
+
* be written without a bare 0.
|
|
53
|
+
*/
|
|
54
|
+
export const EXIT_OK = 0;
|
|
55
|
+
/**
|
|
56
|
+
* Spec-assigned exit code for the generic failure class: the command
|
|
57
|
+
* failed and no narrower code applies. Pair it with {@link genericError}
|
|
58
|
+
* rather than hand-rolling exit 1, so the envelope carries a transience
|
|
59
|
+
* class.
|
|
60
|
+
*/
|
|
61
|
+
export const EXIT_GENERIC = 1;
|
|
62
|
+
/**
|
|
63
|
+
* The caller's invocation being wrong: an unknown flag, a missing
|
|
64
|
+
* argument, a value the command cannot parse. Permanent by
|
|
65
|
+
* construction — the same argv fails identically.
|
|
66
|
+
*/
|
|
67
|
+
export const EXIT_USAGE = 2;
|
|
68
|
+
/** A named resource the command could not locate. */
|
|
69
|
+
export const EXIT_NOT_FOUND = 3;
|
|
70
|
+
/**
|
|
71
|
+
* A request that cannot be satisfied against the current state: a
|
|
72
|
+
* precondition failed, a write raced, an identifier is already taken.
|
|
73
|
+
*/
|
|
74
|
+
export const EXIT_CONFLICT = 4;
|
|
75
|
+
/**
|
|
76
|
+
* An authentication or authorization refusal. Permanent: the caller
|
|
77
|
+
* needs new credentials or a different policy, not a retry. Distinct
|
|
78
|
+
* from {@link EXIT_CONSENT_REFUSED}, which a re-invocation with
|
|
79
|
+
* `--confirm=yes` clears.
|
|
80
|
+
*/
|
|
81
|
+
export const EXIT_UNAUTHORIZED = 5;
|
|
82
|
+
/**
|
|
83
|
+
* Spec-assigned exit code for transient/retryable failures (Factor 11).
|
|
84
|
+
* Agents branch on it before parsing stderr: exit 6 means a retry may
|
|
85
|
+
* clear the failure.
|
|
86
|
+
*/
|
|
87
|
+
export const EXIT_TRANSIENT = 6;
|
|
88
|
+
/**
|
|
89
|
+
* Exit code for a confirmation gate that declined to run a destructive
|
|
90
|
+
* operation (`--confirm=no`, the non-TTY default, a missing or
|
|
91
|
+
* mismatched `--confirm-token`, or `N` at the prompt). Classified
|
|
92
|
+
* transient: re-invoking with `--confirm=yes` clears it. Distinct from
|
|
93
|
+
* {@link CODE_UNAUTHORIZED} at exit 5, which is permanent because no
|
|
94
|
+
* confirmation can clear a policy denial.
|
|
95
|
+
*/
|
|
96
|
+
export const EXIT_CONSENT_REFUSED = 7;
|
|
97
|
+
/** Conventional exit code for Factor-10 rate-limit refusals. */
|
|
98
|
+
export const EXIT_RATE_LIMITED = 64;
|
|
99
|
+
/**
|
|
100
|
+
* Conventional exit code for Factor-12 strict-mode provenance refusals.
|
|
101
|
+
* Lives at 65 in kit's extension band (alongside RATE_LIMITED at 64):
|
|
102
|
+
* the spec reserves 0-6 for its core taxonomy and leaves >6 to per-tool
|
|
103
|
+
* codes, and kit as a library stays out of the low per-tool range.
|
|
104
|
+
*/
|
|
105
|
+
export const EXIT_PROVENANCE_MISSING = 65;
|
|
106
|
+
/**
|
|
107
|
+
* Exit code for a declared external dependency kit could not contact:
|
|
108
|
+
* nothing listening on the configured endpoint, connection refused,
|
|
109
|
+
* dial timeout. Separates a correct invocation whose logic never ran
|
|
110
|
+
* from the uncharacterized failures on exit 1. Classified transient,
|
|
111
|
+
* but deliberately not {@link CODE_TRANSIENT}: a dependency that is not
|
|
112
|
+
* running never comes up on its own, so the caller repairs the
|
|
113
|
+
* environment instead of backing off.
|
|
114
|
+
*/
|
|
115
|
+
export const EXIT_PREREQUISITE = 70;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Structured-error envelope rendered to stderr when `--format json|yaml`
|
|
119
|
+
* is set. Keys are the on-wire snake_case names.
|
|
120
|
+
*
|
|
121
|
+
* `transience` classifies the failure for retry decisions (Factor 4):
|
|
122
|
+
* transient (retry-worthy), permanent (do not retry), or unknown.
|
|
123
|
+
* Constructors and {@link wrapError} populate it; {@link renderError}
|
|
124
|
+
* normalizes an unset value to unknown so every structured error carries
|
|
125
|
+
* a valid class on the wire.
|
|
126
|
+
*/
|
|
127
|
+
export interface CliError {
|
|
128
|
+
code: string;
|
|
129
|
+
message: string;
|
|
130
|
+
cause?: string;
|
|
131
|
+
suggested_fix?: string;
|
|
132
|
+
alternatives?: string[];
|
|
133
|
+
exit_code: number;
|
|
134
|
+
transience?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Retained source errors, keyed by envelope. Mirrors Go's unexported
|
|
139
|
+
* `err` field: off the wire by construction, readable via
|
|
140
|
+
* {@link unwrapError}.
|
|
141
|
+
*/
|
|
142
|
+
const retained = new WeakMap<CliError, unknown>();
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Default transience class for one of the standard codes. Unrecognized
|
|
146
|
+
* (adopter-defined) codes map to unknown; adopters set `transience`
|
|
147
|
+
* (or use {@link withTransience}) to classify their own codes.
|
|
148
|
+
*/
|
|
149
|
+
export function transienceForCode(code: string): string {
|
|
150
|
+
switch (code) {
|
|
151
|
+
case CODE_USAGE:
|
|
152
|
+
case CODE_NOT_FOUND:
|
|
153
|
+
case CODE_CONFLICT:
|
|
154
|
+
case CODE_UNAUTHORIZED:
|
|
155
|
+
case CODE_PROVENANCE_MISSING:
|
|
156
|
+
return TRANSIENCE_PERMANENT;
|
|
157
|
+
case CODE_RATE_LIMITED:
|
|
158
|
+
case CODE_TRANSIENT:
|
|
159
|
+
case CODE_CONSENT_REFUSED:
|
|
160
|
+
case CODE_PREREQUISITE:
|
|
161
|
+
return TRANSIENCE_TRANSIENT;
|
|
162
|
+
default:
|
|
163
|
+
return TRANSIENCE_UNKNOWN;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The class-symbol-to-exit-code relation, as data. Mirrors Go's
|
|
169
|
+
* `exitCodeForClass` in `go/console/output/envelope/exitcodes.go`.
|
|
170
|
+
*
|
|
171
|
+
* Expressed as a table rather than as constants plus trailing comments
|
|
172
|
+
* because the string-to-number relationship is the thing consumers
|
|
173
|
+
* actually need, and a comment cannot be consumed — nor can it be
|
|
174
|
+
* checked against the cross-language contract. Pinned against
|
|
175
|
+
* `contracts/exit-taxonomy-v1/taxonomy.json` by
|
|
176
|
+
* `test/output/taxonomy-contract.test.ts`.
|
|
177
|
+
*
|
|
178
|
+
* Scope is the classes kit itself owns. The conformance band's
|
|
179
|
+
* tool-specific slots (66 LEAK_DETECTED, 67 CONFIG, 68 GRADE_FAIL,
|
|
180
|
+
* 69 GRADE_UNGRADABLE) are deliberately absent: they are declared by the
|
|
181
|
+
* packages that own them.
|
|
182
|
+
*/
|
|
183
|
+
const EXIT_CODE_FOR_CLASS: ReadonlyMap<string, number> = new Map([
|
|
184
|
+
[CODE_OK, EXIT_OK],
|
|
185
|
+
[CODE_GENERIC, EXIT_GENERIC],
|
|
186
|
+
[CODE_USAGE, EXIT_USAGE],
|
|
187
|
+
[CODE_NOT_FOUND, EXIT_NOT_FOUND],
|
|
188
|
+
[CODE_CONFLICT, EXIT_CONFLICT],
|
|
189
|
+
[CODE_UNAUTHORIZED, EXIT_UNAUTHORIZED],
|
|
190
|
+
[CODE_TRANSIENT, EXIT_TRANSIENT],
|
|
191
|
+
[CODE_CONSENT_REFUSED, EXIT_CONSENT_REFUSED],
|
|
192
|
+
[CODE_RATE_LIMITED, EXIT_RATE_LIMITED],
|
|
193
|
+
[CODE_PROVENANCE_MISSING, EXIT_PROVENANCE_MISSING],
|
|
194
|
+
[CODE_PREREQUISITE, EXIT_PREREQUISITE],
|
|
195
|
+
]);
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Resolves a standard class symbol to its numeric exit code, or
|
|
199
|
+
* `undefined` for adopter-defined and tool-specific codes.
|
|
200
|
+
*
|
|
201
|
+
* Callers that must produce a number for an unknown class decide their
|
|
202
|
+
* own fallback. This function does not pick one: a built-in fallback
|
|
203
|
+
* turns "this class was added to kit and never copied here" into an
|
|
204
|
+
* assertion against exit 1 that looks like a real failure rather than a
|
|
205
|
+
* stale table.
|
|
206
|
+
*/
|
|
207
|
+
export function exitCodeForClass(code: string): number | undefined {
|
|
208
|
+
return EXIT_CODE_FOR_CLASS.get(code);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The class symbols kit defines, in ascending exit-code order (ties
|
|
213
|
+
* broken by symbol). Callers rendering the taxonomy iterate this rather
|
|
214
|
+
* than hard-coding rows, so a class added above appears without a
|
|
215
|
+
* second edit.
|
|
216
|
+
*/
|
|
217
|
+
export function exitClasses(): string[] {
|
|
218
|
+
return [...EXIT_CODE_FOR_CLASS.entries()]
|
|
219
|
+
.sort((a, b) => (a[1] !== b[1] ? a[1] - b[1] : a[0].localeCompare(b[0])))
|
|
220
|
+
.map(([code]) => code);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Builds an envelope from `err`, retaining it for {@link unwrapError}
|
|
225
|
+
* while rendering as `code` and message. Transience defaults from the
|
|
226
|
+
* code via {@link transienceForCode}; use {@link withTransience} to
|
|
227
|
+
* override.
|
|
228
|
+
*/
|
|
229
|
+
export function wrapError(
|
|
230
|
+
err: unknown,
|
|
231
|
+
code: string,
|
|
232
|
+
exitCode: number,
|
|
233
|
+
): CliError | null {
|
|
234
|
+
if (err === null || err === undefined) return null;
|
|
235
|
+
const e: CliError = {
|
|
236
|
+
code,
|
|
237
|
+
message: err instanceof Error ? err.message : String(err),
|
|
238
|
+
exit_code: exitCode,
|
|
239
|
+
transience: transienceForCode(code),
|
|
240
|
+
};
|
|
241
|
+
retained.set(e, err);
|
|
242
|
+
return e;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The error this envelope was built from via {@link wrapError}, so
|
|
247
|
+
* callers can classify failures by cause instead of string-matching
|
|
248
|
+
* `message`. Mirrors Go's `(*Error).Unwrap`.
|
|
249
|
+
*/
|
|
250
|
+
export function unwrapError(e: CliError): unknown {
|
|
251
|
+
return retained.get(e);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Copy of `e` with `transience` set, every other field (and the retained
|
|
256
|
+
* source error) untouched. Copies rather than mutating: adopters
|
|
257
|
+
* commonly share module-level envelopes, and writing to one would leak
|
|
258
|
+
* across call sites.
|
|
259
|
+
*/
|
|
260
|
+
export function withTransience(e: CliError, transience: string): CliError {
|
|
261
|
+
const clone: CliError = { ...e, transience };
|
|
262
|
+
if (retained.has(e)) retained.set(clone, retained.get(e));
|
|
263
|
+
return clone;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* CODE_GENERIC envelope with exit code 1. The catch-all for failures no
|
|
268
|
+
* narrower code describes; permanent because retrying the same input
|
|
269
|
+
* in the same environment is not expected to help. Wrapping an
|
|
270
|
+
* arbitrary error as CODE_GENERIC via {@link wrapError} still defaults
|
|
271
|
+
* to unknown.
|
|
272
|
+
*/
|
|
273
|
+
export function genericError(message: string): CliError {
|
|
274
|
+
return {
|
|
275
|
+
code: CODE_GENERIC,
|
|
276
|
+
message,
|
|
277
|
+
exit_code: EXIT_GENERIC,
|
|
278
|
+
transience: TRANSIENCE_PERMANENT,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** CODE_NOT_FOUND envelope with exit code 3. */
|
|
283
|
+
export function notFoundError(message: string): CliError {
|
|
284
|
+
return {
|
|
285
|
+
code: CODE_NOT_FOUND,
|
|
286
|
+
message,
|
|
287
|
+
exit_code: 3,
|
|
288
|
+
transience: TRANSIENCE_PERMANENT,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** CODE_CONFLICT envelope with exit code 4. */
|
|
293
|
+
export function conflictError(message: string): CliError {
|
|
294
|
+
return {
|
|
295
|
+
code: CODE_CONFLICT,
|
|
296
|
+
message,
|
|
297
|
+
exit_code: 4,
|
|
298
|
+
transience: TRANSIENCE_PERMANENT,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** CODE_UNAUTHORIZED envelope with exit code 5. */
|
|
303
|
+
export function unauthorizedError(message: string): CliError {
|
|
304
|
+
return {
|
|
305
|
+
code: CODE_UNAUTHORIZED,
|
|
306
|
+
message,
|
|
307
|
+
exit_code: 5,
|
|
308
|
+
transience: TRANSIENCE_PERMANENT,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** CODE_USAGE envelope with exit code 2. */
|
|
313
|
+
export function usageError(message: string): CliError {
|
|
314
|
+
return {
|
|
315
|
+
code: CODE_USAGE,
|
|
316
|
+
message,
|
|
317
|
+
exit_code: 2,
|
|
318
|
+
transience: TRANSIENCE_PERMANENT,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* CODE_TRANSIENT envelope with exit code 6 (Factor 11). Use it for
|
|
324
|
+
* failures a retry may clear: upstream timeouts, connection resets,
|
|
325
|
+
* service-unavailable responses.
|
|
326
|
+
*/
|
|
327
|
+
export function transientError(message: string): CliError {
|
|
328
|
+
return {
|
|
329
|
+
code: CODE_TRANSIENT,
|
|
330
|
+
message,
|
|
331
|
+
exit_code: EXIT_TRANSIENT,
|
|
332
|
+
transience: TRANSIENCE_TRANSIENT,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* CODE_CONSENT_REFUSED envelope with exit code 7. Use it when a
|
|
338
|
+
* confirmation gate declines to run a destructive operation:
|
|
339
|
+
* `--confirm=no`, the non-TTY default, a missing or mismatched
|
|
340
|
+
* `--confirm-token`, or `N` at the prompt.
|
|
341
|
+
*
|
|
342
|
+
* Classified transient: the caller clears it by re-invoking with
|
|
343
|
+
* `--confirm=yes` (or the matching token). Do not use it for policy
|
|
344
|
+
* denials, which no confirmation can clear — those stay
|
|
345
|
+
* {@link unauthorizedError} and permanent.
|
|
346
|
+
*/
|
|
347
|
+
export function consentRefusedError(message: string): CliError {
|
|
348
|
+
return {
|
|
349
|
+
code: CODE_CONSENT_REFUSED,
|
|
350
|
+
message,
|
|
351
|
+
exit_code: EXIT_CONSENT_REFUSED,
|
|
352
|
+
transience: TRANSIENCE_TRANSIENT,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* CODE_PREREQUISITE envelope with exit code 70. Use it when a declared
|
|
358
|
+
* external dependency could not be contacted: nothing listening on the
|
|
359
|
+
* configured endpoint, connection refused, dial timeout.
|
|
360
|
+
*
|
|
361
|
+
* Classified transient: the operator starts the dependency and the same
|
|
362
|
+
* command succeeds. Do not use it for a dependency that answered and
|
|
363
|
+
* then misbehaved — that is {@link genericError} — nor for one that was
|
|
364
|
+
* never configured, which is {@link usageError}.
|
|
365
|
+
*/
|
|
366
|
+
export function prerequisiteError(message: string): CliError {
|
|
367
|
+
return {
|
|
368
|
+
code: CODE_PREREQUISITE,
|
|
369
|
+
message,
|
|
370
|
+
exit_code: EXIT_PREREQUISITE,
|
|
371
|
+
transience: TRANSIENCE_TRANSIENT,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** CODE_RATE_LIMITED envelope with exit code 64 (Factor 10). */
|
|
376
|
+
export function rateLimitedError(message: string): CliError {
|
|
377
|
+
return {
|
|
378
|
+
code: CODE_RATE_LIMITED,
|
|
379
|
+
message,
|
|
380
|
+
exit_code: EXIT_RATE_LIMITED,
|
|
381
|
+
transience: TRANSIENCE_TRANSIENT,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* CODE_PROVENANCE_MISSING envelope with exit code 65 (Factor 12).
|
|
387
|
+
* `detail` is a free-form string suitable for the `cause` slot
|
|
388
|
+
* (typically the JSON-pointer list of offending fields).
|
|
389
|
+
*/
|
|
390
|
+
export function provenanceMissingError(detail: string): CliError {
|
|
391
|
+
return {
|
|
392
|
+
code: CODE_PROVENANCE_MISSING,
|
|
393
|
+
message: 'provenance not recorded for one or more output fields',
|
|
394
|
+
cause: detail,
|
|
395
|
+
suggested_fix:
|
|
396
|
+
'record provenance for synthesized/cached fields before rendering ' +
|
|
397
|
+
'(see @hop-top/kit/provenance)',
|
|
398
|
+
exit_code: EXIT_PROVENANCE_MISSING,
|
|
399
|
+
transience: TRANSIENCE_PERMANENT,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Wire form of `e`: empty optional fields dropped (omitempty parity),
|
|
405
|
+
* key order mirroring the Go struct.
|
|
406
|
+
*/
|
|
407
|
+
function toWire(e: CliError): CliError {
|
|
408
|
+
const wire: Record<string, unknown> = { code: e.code, message: e.message };
|
|
409
|
+
if (e.cause) wire.cause = e.cause;
|
|
410
|
+
if (e.suggested_fix) wire.suggested_fix = e.suggested_fix;
|
|
411
|
+
if (e.alternatives && e.alternatives.length > 0) {
|
|
412
|
+
wire.alternatives = [...e.alternatives];
|
|
413
|
+
}
|
|
414
|
+
wire.exit_code = e.exit_code;
|
|
415
|
+
if (e.transience) wire.transience = e.transience;
|
|
416
|
+
return wire as unknown as CliError;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Writes `err` to `w` in the requested format. `format === ''` or
|
|
421
|
+
* `'table'` renders human-readable plain text (`"Code: Message\nFix:
|
|
422
|
+
* ..."`); JSON/YAML render the envelope structurally. An unset
|
|
423
|
+
* transience is normalized to unknown on the wire (Factor 4) without
|
|
424
|
+
* mutating `err`. Always returns; the caller decides the exit code from
|
|
425
|
+
* `err.exit_code` after rendering.
|
|
426
|
+
*/
|
|
427
|
+
export function renderError(
|
|
428
|
+
w: { write(chunk: string): unknown },
|
|
429
|
+
format: string,
|
|
430
|
+
err: CliError | null | undefined,
|
|
431
|
+
): void {
|
|
432
|
+
if (!err) return;
|
|
433
|
+
const e = err.transience ? err : withTransience(err, TRANSIENCE_UNKNOWN);
|
|
434
|
+
if (format === 'json') {
|
|
435
|
+
w.write(`${JSON.stringify(toWire(e), null, 2)}\n`);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (format === 'yaml') {
|
|
439
|
+
w.write(yaml.dump(toWire(e)));
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
renderErrorPlain(w, e);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Human-readable form used by `--format table` (and the default empty
|
|
447
|
+
* format). Each populated field appears on its own line so the output is
|
|
448
|
+
* grep-friendly.
|
|
449
|
+
*/
|
|
450
|
+
function renderErrorPlain(
|
|
451
|
+
w: { write(chunk: string): unknown },
|
|
452
|
+
err: CliError,
|
|
453
|
+
): void {
|
|
454
|
+
let out = err.code ? `${err.code}: ${err.message}\n` : `${err.message}\n`;
|
|
455
|
+
if (err.cause) out += `Cause: ${err.cause}\n`;
|
|
456
|
+
if (err.suggested_fix) out += `Fix: ${err.suggested_fix}\n`;
|
|
457
|
+
for (const alt of err.alternatives ?? []) out += `Alternative: ${alt}\n`;
|
|
458
|
+
w.write(out);
|
|
459
|
+
}
|
package/src/output/formatter.ts
CHANGED
|
@@ -24,11 +24,16 @@ export interface OptionSpec {
|
|
|
24
24
|
export type Options = Readonly<Record<string, string | number | boolean>>;
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
* Column metadata used by
|
|
27
|
+
* Column metadata used by every built-in formatter and by --cols validation.
|
|
28
28
|
*
|
|
29
|
-
* - `header` is the user-visible label
|
|
30
|
-
*
|
|
31
|
-
*
|
|
29
|
+
* - `header` is the user-visible label, the name matched against --cols, AND
|
|
30
|
+
* the property read off the row object: header == key, universally. Go
|
|
31
|
+
* cannot express a header/key split through `table:""` struct tags, so no
|
|
32
|
+
* SDK offers one.
|
|
33
|
+
* - `key` is retained for source compatibility and must equal `header`;
|
|
34
|
+
* `columnName` reports the single effective name.
|
|
35
|
+
* - `priority` is accepted and stored but ignored — hide-on-overflow is a
|
|
36
|
+
* Go-only feature today.
|
|
32
37
|
*/
|
|
33
38
|
export interface ColumnSpec {
|
|
34
39
|
readonly header: string;
|
|
@@ -36,6 +41,21 @@ export interface ColumnSpec {
|
|
|
36
41
|
readonly priority?: number;
|
|
37
42
|
}
|
|
38
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Returns a ColumnSpec's effective column name, rejecting a header/key split.
|
|
46
|
+
*
|
|
47
|
+
* Validating at read time keeps drift impossible while `key` still exists as
|
|
48
|
+
* a field.
|
|
49
|
+
*/
|
|
50
|
+
export function columnName(c: ColumnSpec): string {
|
|
51
|
+
if (c.key !== c.header) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`column "${c.header}": header and key must match (got key "${c.key}")`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return c.header;
|
|
57
|
+
}
|
|
58
|
+
|
|
39
59
|
/**
|
|
40
60
|
* A Formatter encodes structured data to a writable stream.
|
|
41
61
|
*
|
|
@@ -63,7 +83,11 @@ export interface Formatter<T = unknown> {
|
|
|
63
83
|
* @param out Destination writable stream.
|
|
64
84
|
* @param data Single row or readonly array of rows.
|
|
65
85
|
* @param opts Validated options; only declared keys with coerced values.
|
|
66
|
-
* @param cols
|
|
86
|
+
* @param cols Effective column list, already resolved by dispatch: the
|
|
87
|
+
* user's `--cols` when supplied, else the caller's ColumnSpec headers in
|
|
88
|
+
* list order, else empty meaning "fall back to payload key order".
|
|
89
|
+
* Render columns in exactly this order — it is both the labels and, since
|
|
90
|
+
* header == key, the lookup names on each row.
|
|
67
91
|
*/
|
|
68
92
|
render(
|
|
69
93
|
out: NodeJS.WritableStream,
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# output/formatters
|
|
2
|
+
|
|
3
|
+
## What it answers
|
|
4
|
+
|
|
5
|
+
Which bytes each built-in format emits and which `--format-opt` keys it accepts. Every file here is one `Formatter` registered against `defaultRegistry` when [`../builtins.ts`](../builtins.ts) loads. Wrong place for flag wiring or format resolution: that is [`../dispatch.ts`](../dispatch.ts) and [`../flags.ts`](../flags.ts).
|
|
6
|
+
|
|
7
|
+
## Use it when
|
|
8
|
+
|
|
9
|
+
- you need a formatter without the flag suite: `defaultRegistry.lookup(key)` then `render(out, data, opts, cols)`
|
|
10
|
+
- you are adding a built-in: copy the closest file, export a `Formatter`, register it in `../builtins.ts`
|
|
11
|
+
- you are checking what an option does: read the file's header comment
|
|
12
|
+
|
|
13
|
+
| Key | Extensions | Options |
|
|
14
|
+
|-----|------------|---------|
|
|
15
|
+
| `json` | `.json` | `indent` (int, default 2) |
|
|
16
|
+
| `yaml` | `.yaml`, `.yml` | `flow-level` (int, default -1) |
|
|
17
|
+
| `table` | none | none |
|
|
18
|
+
| `csv` | `.csv` | `delimiter`, `no-header`, `quote-all`, `crlf` |
|
|
19
|
+
| `text` | `.txt` | `style` (kv, lines, paragraph), `separator` (kv only) |
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { defaultRegistry } from '@hop-top/kit/output';
|
|
25
|
+
|
|
26
|
+
console.log(defaultRegistry.keys());
|
|
27
|
+
const csv = defaultRegistry.lookup('csv')!;
|
|
28
|
+
csv.render(process.stdout, [{ id: '1', name: 'Alice' }], { delimiter: ';' }, []);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Contract
|
|
32
|
+
|
|
33
|
+
- `render` trusts `opts`: callers run `parseOptions` against `options()` first.
|
|
34
|
+
- `json` and `yaml` preserve the payload's outer shape (object stays object, array stays array) and pass non-object payloads through untouched; [`project.ts`](project.ts) is the shared shim.
|
|
35
|
+
- `table`, `csv` and `text` take column order from the `ColumnSpec` list, else the first row's key order; `cols` narrows and reorders.
|
|
36
|
+
- `csv` encoding is hand-rolled: a quoted field's bytes are preserved verbatim in both line-ending modes.
|
|
37
|
+
- `text` mirrors `go/console/output/text.go` byte for byte.
|
|
38
|
+
- Parity: [`sdk/tests/cross-lang/fixtures/ordering.json`](../../../../tests/cross-lang/fixtures/ordering.json).
|
|
39
|
+
|
|
40
|
+
## Neighbours
|
|
41
|
+
|
|
42
|
+
- [`../registry.ts`](../registry.ts): `Registry`, `defaultRegistry`, duplicate-key fail-loud
|
|
43
|
+
- [`../template.ts`](../template.ts): `--template` (eta), not a formatter
|
|
44
|
+
- [`../format_help.ts`](../format_help.ts): `--format-help` catalog
|
|
45
|
+
- Python port: [`hop_top_kit/output/formatters`](../../../../py/hop_top_kit/output/formatters/README.md)
|
|
46
|
+
|
|
47
|
+
## See also
|
|
48
|
+
|
|
49
|
+
- [`../README.md`](../README.md)
|
|
50
|
+
- [`sdk/ts/README.md`](../../../README.md), section "Built-in formatters"
|
|
@@ -1,12 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @module output/formatters/csv
|
|
3
3
|
*
|
|
4
|
-
* Built-in CSV formatter.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Built-in CSV formatter. Honors `delimiter`, `no-header`, `quote-all`,
|
|
5
|
+
* `crlf` options + `cols` filtering.
|
|
6
|
+
*
|
|
7
|
+
* Encoding is hand-rolled rather than delegated to csv-stringify. In its
|
|
8
|
+
* `windows` record-delimiter mode that library left a field containing an
|
|
9
|
+
* embedded LF UNQUOTED, so a single record decoded as two (or three)
|
|
10
|
+
* records — structurally invalid CSV, not merely a quoting difference. It
|
|
11
|
+
* also left a leading space bare where the other runtimes quote it.
|
|
12
|
+
*
|
|
13
|
+
* The rule: quote a field iff it contains the active delimiter, a double
|
|
14
|
+
* quote, LF, or CR, or begins with a unicode whitespace character. Trailing
|
|
15
|
+
* whitespace is not quoted. Internal quotes are doubled per RFC 4180.
|
|
16
|
+
*
|
|
17
|
+
* A quoted field's bytes are preserved verbatim in both line-ending modes and
|
|
18
|
+
* both quoting paths. RFC 4180's `escaped` production lists CR and LF as
|
|
19
|
+
* separate alternatives, so a bare CR between quotes is legal, and the W3C
|
|
20
|
+
* CSV on the Web note states that line endings within escaped cells are not
|
|
21
|
+
* normalised. The `crlf` option changes the record terminator and nothing
|
|
22
|
+
* else.
|
|
7
23
|
*/
|
|
8
24
|
|
|
9
|
-
import { stringify } from 'csv-stringify/sync';
|
|
10
25
|
import type { Formatter, Options } from '../formatter';
|
|
11
26
|
|
|
12
27
|
export const csvFormatter: Formatter = {
|
|
@@ -47,20 +62,41 @@ export const csvFormatter: Formatter = {
|
|
|
47
62
|
}
|
|
48
63
|
|
|
49
64
|
const records = rows.map(r => headers.map(h => stringify_cell(r[h])));
|
|
65
|
+
// Headers are prepended here rather than via a library `header` option to
|
|
66
|
+
// keep row layout uniform and make `no-header` a single decision point.
|
|
50
67
|
const csvRows = noHeader ? records : [headers, ...records];
|
|
51
68
|
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
// row layout uniform with csv format and to make `no-header` toggle
|
|
58
|
-
// a single decision point.
|
|
59
|
-
});
|
|
69
|
+
const eol = crlf ? '\r\n' : '\n';
|
|
70
|
+
let text = '';
|
|
71
|
+
for (const cells of csvRows) {
|
|
72
|
+
text += cells.map(c => encodeField(c, delimiter, quoteAll)).join(delimiter) + eol;
|
|
73
|
+
}
|
|
60
74
|
out.write(text);
|
|
61
75
|
},
|
|
62
76
|
};
|
|
63
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Quote a field iff it contains the delimiter, a quote, LF or CR, or begins
|
|
80
|
+
* with a unicode whitespace character. Note the asymmetry: a LEADING space
|
|
81
|
+
* forces quoting, a trailing one does not. `\.` alone on a line terminates a
|
|
82
|
+
* PostgreSQL COPY stream and is quoted defensively.
|
|
83
|
+
*/
|
|
84
|
+
function needsQuotes(field: string, delim: string): boolean {
|
|
85
|
+
if (field === '') return false;
|
|
86
|
+
if (field === '\\.') return true;
|
|
87
|
+
if (field.includes(delim) || field.includes('"') || field.includes('\n') || field.includes('\r')) {
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
return /^\s/u.test(field);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function encodeField(field: string, delim: string, quoteAll: boolean): string {
|
|
94
|
+
if (!quoteAll && !needsQuotes(field, delim)) return field;
|
|
95
|
+
// RFC 4180: an embedded quote is doubled. Everything else, CR and LF
|
|
96
|
+
// included, is written through untouched.
|
|
97
|
+
return `"${field.replace(/"/g, '""')}"`;
|
|
98
|
+
}
|
|
99
|
+
|
|
64
100
|
function normalise(v: unknown): Record<string, unknown>[] {
|
|
65
101
|
if (Array.isArray(v)) return v as Record<string, unknown>[];
|
|
66
102
|
return [v as Record<string, unknown>];
|
|
@@ -2,15 +2,13 @@
|
|
|
2
2
|
* @module output/formatters/json
|
|
3
3
|
*
|
|
4
4
|
* Built-in JSON formatter. Honors `indent` option (default 2) + trailing
|
|
5
|
-
* newline.
|
|
5
|
+
* newline. Emitted key order follows the ColumnSpec list, narrowed and
|
|
6
|
+
* reordered by `cols`; without either, the payload passes through untouched.
|
|
6
7
|
*/
|
|
7
8
|
|
|
8
9
|
import type { Formatter, Options } from '../formatter';
|
|
10
|
+
import { projectForEncoding } from './project';
|
|
9
11
|
|
|
10
|
-
/**
|
|
11
|
-
* Build the JSON formatter. The `columns` ref is optional; when provided
|
|
12
|
-
* (via dispatch with a ColumnSpec list), rows are projected before encode.
|
|
13
|
-
*/
|
|
14
12
|
export const jsonFormatter: Formatter = {
|
|
15
13
|
key: 'json',
|
|
16
14
|
extensions: ['.json'],
|
|
@@ -19,26 +17,7 @@ export const jsonFormatter: Formatter = {
|
|
|
19
17
|
],
|
|
20
18
|
render(out, data, opts: Options, cols) {
|
|
21
19
|
const indent = (opts['indent'] as number) ?? 2;
|
|
22
|
-
const value =
|
|
20
|
+
const value = projectForEncoding(data, cols);
|
|
23
21
|
out.write(JSON.stringify(value, null, indent) + '\n');
|
|
24
22
|
},
|
|
25
23
|
};
|
|
26
|
-
|
|
27
|
-
function projectForJson(
|
|
28
|
-
data: unknown,
|
|
29
|
-
cols: readonly string[],
|
|
30
|
-
): unknown {
|
|
31
|
-
if (cols.length === 0) return data;
|
|
32
|
-
if (Array.isArray(data)) {
|
|
33
|
-
return data.map(row => projectRow(row, cols));
|
|
34
|
-
}
|
|
35
|
-
return projectRow(data, cols);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function projectRow(row: unknown, cols: readonly string[]): unknown {
|
|
39
|
-
if (row === null || typeof row !== 'object') return row;
|
|
40
|
-
const r = row as Record<string, unknown>;
|
|
41
|
-
const out: Record<string, unknown> = {};
|
|
42
|
-
for (const c of cols) out[c] = r[c];
|
|
43
|
-
return out;
|
|
44
|
-
}
|