@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.2

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 (101) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +237 -9
  3. package/dist/aim-CTp-kJW2.d.ts +139 -0
  4. package/dist/aim.d.ts +1 -116
  5. package/dist/alias-dhhr08Ei.d.ts +88 -0
  6. package/dist/alias.d.ts +2 -73
  7. package/dist/api-miiso81x.d.ts +77 -0
  8. package/dist/api.d.ts +1 -62
  9. package/dist/auth-2-jfgiHn.d.ts +34 -0
  10. package/dist/auth.d.ts +1 -26
  11. package/dist/cli-DgOEOsPB.d.ts +450 -0
  12. package/dist/cli.d.ts +5 -309
  13. package/dist/cli.js +190 -62
  14. package/dist/config-BUY7_W2n.d.ts +103 -0
  15. package/dist/config.d.ts +1 -97
  16. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  17. package/dist/errcorrect.d.ts +1 -37
  18. package/dist/id/index.d.ts +2 -83
  19. package/dist/index--C7Mtsmm.d.ts +328 -0
  20. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  21. package/dist/index-MLrRDvEG.d.ts +1073 -0
  22. package/dist/index-QSffbLnj.d.ts +94 -0
  23. package/dist/index.d.ts +26 -0
  24. package/dist/index.js +5863 -0
  25. package/dist/llm-B5XUWH8T.d.ts +231 -0
  26. package/dist/llm.d.ts +1 -188
  27. package/dist/mcp/index.d.ts +2 -0
  28. package/dist/mcp/index.js +1453 -0
  29. package/dist/netpolicy-asvCfwi8.d.ts +138 -0
  30. package/dist/netpolicy.d.ts +1 -0
  31. package/dist/netpolicy.js +118 -0
  32. package/dist/output-VFFLqor9.d.ts +521 -0
  33. package/dist/output.d.ts +2 -213
  34. package/dist/output.js +554 -43
  35. package/dist/progress-CAzyxeWl.d.ts +38 -0
  36. package/dist/progress.d.ts +1 -30
  37. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  38. package/dist/provenance.d.ts +1 -24
  39. package/dist/routellm-PGSt2D1y.d.ts +75 -0
  40. package/dist/routellm.d.ts +2 -64
  41. package/dist/rpc-D5xLEf8V.d.ts +32 -0
  42. package/dist/rpc.d.ts +2 -25
  43. package/dist/safety-CUaYEjZc.d.ts +30 -0
  44. package/dist/safety.d.ts +1 -24
  45. package/dist/scope-BrhYB4ij.d.ts +141 -0
  46. package/dist/scope.d.ts +1 -121
  47. package/dist/stream-CrjeCp0M.d.ts +44 -0
  48. package/dist/stream.d.ts +1 -35
  49. package/dist/telemetry/index.d.ts +1 -315
  50. package/dist/telemetry/index.js +12 -1
  51. package/dist/tui/index.d.ts +4 -298
  52. package/dist/tui/index.js +1 -9
  53. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  54. package/dist/upgrade.d.ts +1 -95
  55. package/dist/xdg-DB7Shoib.d.ts +179 -0
  56. package/dist/xdg.d.ts +1 -169
  57. package/package.json +21 -3
  58. package/src/cli.offline.test.ts +93 -0
  59. package/src/cli.parity.test.ts +192 -0
  60. package/src/cli.ts +112 -12
  61. package/src/index.test.ts +58 -0
  62. package/src/index.ts +36 -0
  63. package/src/log.parity.test.ts +105 -0
  64. package/src/log.ts +64 -13
  65. package/src/mcp/bridge.test.ts +150 -0
  66. package/src/mcp/bridge.ts +246 -0
  67. package/src/mcp/conformance.test.ts +336 -0
  68. package/src/mcp/dispatch.ts +313 -0
  69. package/src/mcp/index.ts +138 -0
  70. package/src/mcp/legacy.ts +314 -0
  71. package/src/mcp/mcp.test.ts +697 -0
  72. package/src/mcp/modern-confirm.test.ts +520 -0
  73. package/src/mcp/modern-confirm.ts +452 -0
  74. package/src/mcp/modern.ts +723 -0
  75. package/src/mcp/tasks.ts +82 -0
  76. package/src/mcp/testtree.ts +250 -0
  77. package/src/mcp/types.ts +504 -0
  78. package/src/netpolicy.test.ts +202 -0
  79. package/src/netpolicy.ts +231 -0
  80. package/src/output/dispatch.ts +10 -2
  81. package/src/output/error.ts +293 -0
  82. package/src/output/formatter.ts +29 -5
  83. package/src/output/formatters/csv.ts +48 -12
  84. package/src/output/formatters/json.ts +4 -25
  85. package/src/output/formatters/project.ts +34 -0
  86. package/src/output/formatters/table.ts +8 -6
  87. package/src/output/formatters/text.ts +7 -3
  88. package/src/output/formatters/yaml.ts +5 -22
  89. package/src/output/projection.test.ts +298 -0
  90. package/src/output/projection.ts +33 -59
  91. package/src/output/template.ts +11 -21
  92. package/src/output.surface.test.ts +41 -0
  93. package/src/output.ts +39 -3
  94. package/src/telemetry/client.test.ts +31 -0
  95. package/src/telemetry/client.ts +7 -1
  96. package/src/telemetry/offline.test.ts +64 -0
  97. package/src/tui/parity.test.ts +120 -31
  98. package/src/tui/parity.ts +58 -7
  99. package/test/output/csv.test.ts +164 -0
  100. package/test/output/error.test.ts +241 -0
  101. package/src/tui/parity.json +0 -74
@@ -0,0 +1,41 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import * as output from './output';
3
+
4
+ /**
5
+ * Guards the public symbol surface of the `./output` subpath export.
6
+ *
7
+ * The exports-map contract test in `index.test.ts` only asserts that each
8
+ * declared subpath has a source file and a build entry — it says nothing
9
+ * about which symbols a subpath exposes. `registerOutputFlags` and
10
+ * `dispatch` were defined under `output/` but never re-exported here, so
11
+ * the README's Commander wiring and the generated cli-ts template both
12
+ * threw `TypeError: registerOutputFlags is not a function` against the
13
+ * published package. `output/` is not itself a published subpath, so
14
+ * consumers had no alternate import path.
15
+ *
16
+ * These names are load-bearing for documented adopter code. Removing one
17
+ * is a breaking change and must fail here first.
18
+ */
19
+ describe('output — documented symbol surface', () => {
20
+ // README "Wiring into a Commander CLI" + templates/cli-ts/src/cli.ts.tmpl.
21
+ it.each(['registerOutputFlags', 'dispatch'])(
22
+ 'exports %s as a function',
23
+ (name) => {
24
+ expect(typeof (output as Record<string, unknown>)[name]).toBe('function');
25
+ },
26
+ );
27
+
28
+ it('exports the rest of the flag-wiring surface', () => {
29
+ expect(typeof output.registryFor).toBe('function');
30
+ expect(typeof output.resolveCols).toBe('function');
31
+ });
32
+
33
+ it('keeps the render shim and format constants', () => {
34
+ expect(typeof output.render).toBe('function');
35
+ expect(output.JSON_FORMAT).toBe('json');
36
+ expect(output.YAML_FORMAT).toBe('yaml');
37
+ expect(output.TABLE_FORMAT).toBe('table');
38
+ expect(output.CSV_FORMAT).toBe('csv');
39
+ expect(output.TEXT_FORMAT).toBe('text');
40
+ });
41
+ });
package/src/output.ts CHANGED
@@ -28,17 +28,53 @@
28
28
  *
29
29
  * ## Backward compatibility
30
30
  *
31
- * `render(w, format, v)` keeps its original signature. New per-format
32
- * options + column projection are accessed via `dispatch()`.
31
+ * `render(w, format, v)` keeps its original signature and renders every
32
+ * column in payload key order. New per-format options and column ordering
33
+ * (ColumnSpec lists, `--cols`) are accessed via `dispatch()`.
33
34
  */
34
35
 
35
36
  // Re-export the typed surface.
36
37
  export type { Formatter, OptionSpec, OptionType, Options, ColumnSpec } from './output/formatter';
37
- export { parseOptions, optionTypeName } from './output/formatter';
38
+ export { parseOptions, optionTypeName, columnName } from './output/formatter';
39
+ export { deriveHeaders, resolveEffectiveCols, projectRows } from './output/projection';
38
40
  export { Registry, defaultRegistry, newRegistry } from './output/registry';
39
41
  export { jsonFormatter } from './output/formatters/json';
40
42
  export { yamlFormatter } from './output/formatters/yaml';
41
43
  export { tableFormatter } from './output/formatters/table';
44
+ export type { RegisterOutputFlagsOptions } from './output/flags';
45
+ export { registerOutputFlags, registryFor, resolveCols } from './output/flags';
46
+ export type { DispatchOptions } from './output/dispatch';
47
+ export { dispatch } from './output/dispatch';
48
+ export type { CliError } from './output/error';
49
+ export {
50
+ CODE_OK,
51
+ CODE_GENERIC,
52
+ CODE_USAGE,
53
+ CODE_NOT_FOUND,
54
+ CODE_CONFLICT,
55
+ CODE_UNAUTHORIZED,
56
+ CODE_TRANSIENT,
57
+ CODE_PROVENANCE_MISSING,
58
+ CODE_RATE_LIMITED,
59
+ EXIT_TRANSIENT,
60
+ EXIT_RATE_LIMITED,
61
+ EXIT_PROVENANCE_MISSING,
62
+ TRANSIENCE_TRANSIENT,
63
+ TRANSIENCE_PERMANENT,
64
+ TRANSIENCE_UNKNOWN,
65
+ transienceForCode,
66
+ wrapError,
67
+ unwrapError,
68
+ withTransience,
69
+ notFoundError,
70
+ conflictError,
71
+ unauthorizedError,
72
+ usageError,
73
+ transientError,
74
+ rateLimitedError,
75
+ provenanceMissingError,
76
+ renderError,
77
+ } from './output/error';
42
78
 
43
79
  // Side-effect: register built-ins.
44
80
  import './output/builtins';
@@ -232,6 +232,37 @@ describe('Client.https sink', () => {
232
232
  }
233
233
  });
234
234
 
235
+ // Telemetry is logging-class egress: --offline stops traffic the user
236
+ // asked for, it is not a second consent gate on diagnostics. The sink
237
+ // must therefore still ship while the process is marked offline.
238
+ //
239
+ // The endpoint is deliberately remote: loopback is exempt from the
240
+ // guard by design, so a 127.0.0.1 target could never fail this test.
241
+ it('ships while offline: --offline must not mute telemetry', async () => {
242
+ const { install, setProcessOffline } = await import('../netpolicy');
243
+ await grantConsent();
244
+ process.env.KIT_TELEMETRY_MODE = 'anon';
245
+
246
+ const mockFetch = vi.fn(async () => new Response(null, { status: 202 }));
247
+ vi.stubGlobal('fetch', mockFetch);
248
+ // Guard the global exactly as createCLI does at start-up.
249
+ install();
250
+ setProcessOffline(true);
251
+
252
+ try {
253
+ const c = new Client({
254
+ sink: 'https',
255
+ endpoint: 'https://telemetry.example.com/v1/events',
256
+ });
257
+ c.record('probe', { i: 1 });
258
+ await c.shutdown(2_000);
259
+
260
+ expect(mockFetch).toHaveBeenCalledTimes(1);
261
+ } finally {
262
+ setProcessOffline(false);
263
+ }
264
+ });
265
+
235
266
  it('retries once on 5xx, then drops', async () => {
236
267
  await grantConsent();
237
268
  process.env.KIT_TELEMETRY_MODE = 'anon';
@@ -36,6 +36,7 @@ import * as yaml from 'js-yaml';
36
36
 
37
37
  import { Mode, resolveMode } from './mode';
38
38
  import { getInstallId } from './installId';
39
+ import { observabilityFetch } from '../netpolicy';
39
40
  import { consentPath, legacyConsentPath } from './consent';
40
41
  import { redact } from './redact';
41
42
 
@@ -412,7 +413,12 @@ export class Client {
412
413
  HTTPS_CONNECT_TIMEOUT_MS,
413
414
  );
414
415
  try {
415
- const res = await fetch(this.endpoint, {
416
+ // Telemetry is logging-class egress: --offline stops traffic
417
+ // the user asked for, not diagnostics. Consent and mode already
418
+ // govern whether anything is emitted, so this sink deliberately
419
+ // uses the unguarded fetch captured before install() patched the
420
+ // global.
421
+ const res = await observabilityFetch()(this.endpoint, {
416
422
  method: 'POST',
417
423
  headers,
418
424
  body,
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it, afterEach, vi } from 'vitest';
2
+
3
+ import {
4
+ install,
5
+ observabilityFetch,
6
+ setProcessOffline,
7
+ isOfflineError,
8
+ } from '../netpolicy';
9
+
10
+ /**
11
+ * Telemetry is logging-class egress: `--offline` stops traffic the user
12
+ * asked for, it is not a second consent gate on diagnostics. Consent and
13
+ * telemetry mode already govern whether anything is emitted at all.
14
+ *
15
+ * Destinations here are deliberately remote. Loopback is exempt from the
16
+ * guard by design, so a 127.0.0.1 target would pass with or without the
17
+ * carve-out and could never fail.
18
+ */
19
+ describe('telemetry exemption from --offline', () => {
20
+ const REMOTE = 'https://telemetry.example.com/v1/events';
21
+
22
+ afterEach(() => {
23
+ setProcessOffline(false);
24
+ vi.restoreAllMocks();
25
+ });
26
+
27
+ it('observability fetch reaches a remote endpoint while offline', async () => {
28
+ const base = vi.fn(async () => new Response('', { status: 200 }));
29
+ globalThis.fetch = base as unknown as typeof globalThis.fetch;
30
+
31
+ // Re-import so the pristine reference is captured from the stub.
32
+ vi.resetModules();
33
+ const fresh = await import('../netpolicy');
34
+ fresh.install();
35
+ fresh.setProcessOffline(true);
36
+
37
+ const res = await fresh.observabilityFetch()(REMOTE, { method: 'POST' });
38
+ expect(res.status).toBe(200);
39
+ expect(base).toHaveBeenCalledTimes(1);
40
+ });
41
+
42
+ it('keeps the carve-out narrow: ordinary fetch is still refused', async () => {
43
+ const base = vi.fn(async () => new Response('', { status: 200 }));
44
+ globalThis.fetch = base as unknown as typeof globalThis.fetch;
45
+
46
+ install();
47
+ setProcessOffline(true);
48
+
49
+ let caught: unknown;
50
+ try {
51
+ await globalThis.fetch(REMOTE, { method: 'GET' });
52
+ } catch (err) {
53
+ caught = err;
54
+ }
55
+ expect(isOfflineError(caught)).toBe(true);
56
+ expect(base).not.toHaveBeenCalled();
57
+ });
58
+
59
+ it('observability fetch is not the guarded global', () => {
60
+ install();
61
+ expect(observabilityFetch()).not.toBe(globalThis.fetch);
62
+ });
63
+ });
64
+
@@ -1,53 +1,142 @@
1
1
  /**
2
- * Contract-sync tests for tui/parity.
2
+ * Drift guards for tui/parity.
3
3
  *
4
- * - Compare the vendored sdk/ts/src/tui/parity.json against the canonical
5
- * contracts/parity/parity.json. If they drift, the test fails — keeping
6
- * the published package self-contained without losing the single source
7
- * of truth.
8
- * - Sanity-check the shape the loader exposes.
4
+ * The loader reads the canonical `contracts/parity/parity.json` directly, so
5
+ * there is no vendored second copy to keep in sync. What remains to protect
6
+ * is the LOADER: a block can be added to parity.json and read as enforced
7
+ * while nothing in TypeScript ever models it.
8
+ *
9
+ * Mirrors `TestParityNoUnloadedBlocks` and `TestParityLoadedBlocksNonZero`
10
+ * in `contracts/parity/parity_test.go`.
9
11
  */
10
12
 
11
13
  import * as fs from 'fs';
12
14
  import * as path from 'path';
13
15
  import { describe, expect, it } from 'vitest';
14
16
 
15
- import { parity } from './parity.js';
17
+ import { PARITY_BLOCKS, parity } from './parity.js';
18
+
19
+ const CANONICAL_PATH = path.join(
20
+ __dirname,
21
+ '..',
22
+ '..',
23
+ '..',
24
+ '..',
25
+ 'contracts',
26
+ 'parity',
27
+ 'parity.json',
28
+ );
29
+
30
+ /** Top-level keys parity.json declares, minus `$`-prefixed schema metadata. */
31
+ function declaredBlocks(): string[] {
32
+ const raw = JSON.parse(fs.readFileSync(CANONICAL_PATH, 'utf8')) as Record<string, unknown>;
33
+ return Object.keys(raw).filter((k) => !k.startsWith('$'));
34
+ }
35
+
36
+ // ─── Drift guard: block registry ─────────────────────────────────────────────
37
+
38
+ describe('parity block registry', () => {
39
+ it('models every block parity.json declares', () => {
40
+ const known = new Set<string>(PARITY_BLOCKS);
41
+ const unknown = declaredBlocks().filter((k) => !known.has(k));
42
+
43
+ expect(
44
+ unknown,
45
+ `contracts/parity/parity.json declares block(s) ${JSON.stringify(unknown)} that the ` +
46
+ `TypeScript loader does not know.\n` +
47
+ `parity.json is a loaded contract, not documentation: an unloaded block is ` +
48
+ `invisible to every test and every consumer.\n` +
49
+ `Fix by adding the block to the ParityData interface and to PARITY_BLOCKS in ` +
50
+ `sdk/ts/src/tui/parity.ts — or, if it is not a cross-language constant, move it ` +
51
+ `to prose in contracts/parity/README.md.`,
52
+ ).toEqual([]);
53
+ });
16
54
 
17
- // ─── Contract sync ───────────────────────────────────────────────────────────
55
+ it('does not list blocks parity.json no longer declares', () => {
56
+ const declared = new Set(declaredBlocks());
57
+ const stale = PARITY_BLOCKS.filter((b) => !declared.has(b));
18
58
 
19
- describe('tui parity contract sync', () => {
20
- it('local parity.json matches contracts/parity/parity.json', () => {
21
- const local = JSON.parse(
22
- fs.readFileSync(path.join(__dirname, 'parity.json'), 'utf8'),
23
- );
24
- const canonical = JSON.parse(
25
- fs.readFileSync(
26
- path.join(__dirname, '..', '..', '..', '..', 'contracts', 'parity', 'parity.json'),
27
- 'utf8',
28
- ),
29
- );
30
- expect(local).toEqual(canonical);
59
+ expect(
60
+ stale,
61
+ `PARITY_BLOCKS lists ${JSON.stringify(stale)} but contracts/parity/parity.json no ` +
62
+ `longer declares it; drop it from PARITY_BLOCKS in sdk/ts/src/tui/parity.ts.`,
63
+ ).toEqual([]);
31
64
  });
32
65
  });
33
66
 
34
- // ─── Loader shape ────────────────────────────────────────────────────────────
67
+ // ─── Drift guard: loaded values are non-empty ────────────────────────────────
68
+
69
+ /**
70
+ * A block wired into ParityData under a mismatched key name still parses
71
+ * clean and leaves `undefined` behind — silent, and exactly what this
72
+ * contract exists to prevent. Asserting the key was SEEN is not enough;
73
+ * assert the value actually arrived.
74
+ */
75
+ describe('parity loaded blocks are non-empty', () => {
76
+ it('status symbols loaded', () => {
77
+ expect(Object.keys(parity.status?.symbols ?? {}).length).toBeGreaterThan(0);
78
+ for (const kind of ['info', 'success', 'error', 'warn'] as const) {
79
+ expect(parity.status.symbols[kind], `status.symbols.${kind}: empty after load`).toBeTruthy();
80
+ }
81
+ });
35
82
 
36
- describe('parity loader', () => {
37
- it('exposes status symbols', () => {
38
- expect(parity.status.symbols.success).toBeTruthy();
39
- expect(parity.status.symbols.error).toBeTruthy();
83
+ it('spinner loaded', () => {
84
+ expect(parity.spinner?.frames?.length ?? 0).toBeGreaterThan(0);
85
+ expect(parity.spinner?.interval_ms ?? 0).toBeGreaterThan(0);
40
86
  });
41
87
 
42
- it('exposes spinner frames and interval', () => {
43
- expect(parity.spinner.frames.length).toBeGreaterThan(0);
44
- expect(parity.spinner.interval_ms).toBeGreaterThan(0);
88
+ it('anim loaded', () => {
89
+ expect(parity.anim?.runes ?? '').toBeTruthy();
90
+ expect(parity.anim?.interval_ms ?? 0).toBeGreaterThan(0);
91
+ expect(parity.anim?.default_width ?? 0).toBeGreaterThan(0);
45
92
  });
46
93
 
47
- it('exposes help section order and titles', () => {
48
- expect(parity.help.section_order.length).toBeGreaterThan(0);
94
+ it('help loaded', () => {
95
+ expect(parity.help?.section_order?.length ?? 0).toBeGreaterThan(0);
96
+ expect(Object.keys(parity.help?.sections ?? {}).length).toBeGreaterThan(0);
49
97
  for (const section of parity.help.section_order) {
50
- expect(parity.help.sections[section]).toBeDefined();
98
+ expect(parity.help.sections[section], `help.sections[${section}]: missing`).toBeDefined();
51
99
  }
52
100
  });
101
+
102
+ it('verbosity loaded', () => {
103
+ const v = parity.verbosity;
104
+ expect(v?.flag, `verbosity: incompletely loaded: ${JSON.stringify(v)}`).toBeTruthy();
105
+ expect(
106
+ Object.keys(v?.levels ?? {}).length,
107
+ `verbosity: incompletely loaded: ${JSON.stringify(v)}`,
108
+ ).toBeGreaterThan(0);
109
+ expect(
110
+ v?.quiet_override,
111
+ `verbosity: incompletely loaded: ${JSON.stringify(v)}`,
112
+ ).toBeTruthy();
113
+ });
114
+
115
+ it('streams loaded', () => {
116
+ const s = parity.streams;
117
+ expect(s?.flag, `streams: incompletely loaded: ${JSON.stringify(s)}`).toBeTruthy();
118
+ expect(s?.label_format, `streams: incompletely loaded: ${JSON.stringify(s)}`).toBeTruthy();
119
+ expect(s?.output, `streams: incompletely loaded: ${JSON.stringify(s)}`).toBeTruthy();
120
+ });
121
+
122
+ it('description and extends loaded', () => {
123
+ expect(parity.description).toBeTruthy();
124
+ expect(parity.extends?.length ?? 0).toBeGreaterThan(0);
125
+ });
126
+ });
127
+
128
+ // ─── Value pins ──────────────────────────────────────────────────────────────
129
+
130
+ describe('parity pinned values', () => {
131
+ it('pins verbosity contract', () => {
132
+ expect(parity.verbosity.flag).toBe('-V');
133
+ expect(parity.verbosity.levels).toEqual({ '0': 'info', '1': 'debug', '2': 'trace' });
134
+ expect(parity.verbosity.quiet_override).toBe('warn');
135
+ });
136
+
137
+ it('pins streams contract', () => {
138
+ expect(parity.streams.flag).toBe('--stream');
139
+ expect(parity.streams.label_format).toBe('[{name}]');
140
+ expect(parity.streams.output).toBe('stderr');
141
+ });
53
142
  });
package/src/tui/parity.ts CHANGED
@@ -2,17 +2,30 @@
2
2
  * @module tui/parity
3
3
  * @package @hop-top/kit
4
4
  *
5
- * Cross-language parity constants SoT. The canonical file lives at
6
- * `contracts/parity/parity.json`; a vendored copy ships next to this
7
- * module so the published package is self-contained. A contract-sync
8
- * test keeps the two in lockstep.
5
+ * Cross-language parity constants SoT. Values are read from the canonical
6
+ * `contracts/parity/parity.json` at build time — tsup/esbuild inlines the
7
+ * JSON into the emitted bundle, so the published package stays
8
+ * self-contained without vendoring a second copy of the file.
9
9
  *
10
10
  * All TUI modules should import constants from here, not hardcode them.
11
11
  */
12
12
 
13
- import parityRaw from './parity.json';
13
+ import parityRaw from '../../../../contracts/parity/parity.json';
14
14
 
15
- interface ParityData {
15
+ /** Display metadata for a single help section. */
16
+ export interface SectionConfig {
17
+ title: string;
18
+ }
19
+
20
+ /**
21
+ * ParityData models every content block `parity.json` declares.
22
+ *
23
+ * A block present in the JSON but absent here is decoration: nothing loads
24
+ * it, so no test and no consumer can see it drift. `PARITY_BLOCKS` below is
25
+ * the machine-checkable half of that rule.
26
+ */
27
+ export interface ParityData {
28
+ description: string;
16
29
  status: {
17
30
  symbols: Record<'info' | 'success' | 'error' | 'warn', string>;
18
31
  };
@@ -29,8 +42,46 @@ interface ParityData {
29
42
  /** Fang-vocabulary section names in render order. */
30
43
  section_order: string[];
31
44
  /** Display metadata keyed by fang section name. */
32
- sections: Record<string, { title: string }>;
45
+ sections: Record<string, SectionConfig>;
46
+ };
47
+ verbosity: {
48
+ flag: string;
49
+ /**
50
+ * Maps the stacked `-V` count (as a decimal string) to a log level name.
51
+ * Keys are strings because JSON object keys are.
52
+ */
53
+ levels: Record<string, string>;
54
+ quiet_override: string;
33
55
  };
56
+ streams: {
57
+ flag: string;
58
+ label_format: string;
59
+ output: string;
60
+ };
61
+ /** Sibling contract files the parity suite also covers. */
62
+ extends: string[];
34
63
  }
35
64
 
65
+ /**
66
+ * PARITY_BLOCKS is the registry of top-level `parity.json` keys this loader
67
+ * knows. Every content block in `parity.json` MUST appear here and MUST have
68
+ * a corresponding property on `ParityData` — the drift guard in
69
+ * `parity.test.ts` enforces both directions so a new block cannot be added
70
+ * as decoration.
71
+ *
72
+ * Mirrors `parity.Blocks` in `contracts/parity/parity.go`.
73
+ *
74
+ * Keys starting with `$` are JSON Schema metadata, not content.
75
+ */
76
+ export const PARITY_BLOCKS = [
77
+ 'description',
78
+ 'status',
79
+ 'spinner',
80
+ 'anim',
81
+ 'help',
82
+ 'verbosity',
83
+ 'streams',
84
+ 'extends',
85
+ ] as const;
86
+
36
87
  export const parity: ParityData = parityRaw;
@@ -127,3 +127,167 @@ describe('csv — registry', () => {
127
127
  expect(defaultRegistry.extensionMap().get('.csv')).toBe('csv');
128
128
  });
129
129
  });
130
+
131
+ // --- CR/LF preservation -------------------------------------------------
132
+
133
+ // The adversarial row that pins csv quoting rules byte-for-byte. Every field
134
+ // is a separate hazard: the delimiter, an internal quote, an embedded LF, a
135
+ // leading space, a trailing space, empty, a tab, and a LONE CR.
136
+ const adversarialRow = {
137
+ a: 'plain',
138
+ b: 'with,comma',
139
+ c: 'with"quote',
140
+ d: 'with\nnewline',
141
+ e: ' leading space',
142
+ f: 'trailing ',
143
+ g: '',
144
+ h: 'with\ttab',
145
+ i: 'with\rcr',
146
+ };
147
+
148
+ const adversarialValues = [
149
+ 'plain',
150
+ 'with,comma',
151
+ 'with"quote',
152
+ 'with\nnewline',
153
+ ' leading space',
154
+ 'trailing ',
155
+ '',
156
+ 'with\ttab',
157
+ 'with\rcr',
158
+ ];
159
+
160
+ /**
161
+ * A minimal RFC 4180 reader. The package ships no csv parser, so round-trip
162
+ * is proved against a decoder written to the grammar directly:
163
+ * `escaped = DQUOTE *(TEXTDATA / COMMA / CR / LF / 2DQUOTE) DQUOTE`.
164
+ * Records split only on an UNQUOTED line ending.
165
+ */
166
+ function decodeCsv(input: string, delim = ','): string[][] {
167
+ const records: string[][] = [];
168
+ let record: string[] = [];
169
+ let field = '';
170
+ let inQuotes = false;
171
+ let pending = false;
172
+
173
+ for (let i = 0; i < input.length; i++) {
174
+ const c = input[i];
175
+ pending = true;
176
+ if (inQuotes) {
177
+ if (c === '"') {
178
+ if (input[i + 1] === '"') {
179
+ field += '"';
180
+ i++;
181
+ } else {
182
+ inQuotes = false;
183
+ }
184
+ } else {
185
+ field += c;
186
+ }
187
+ continue;
188
+ }
189
+ if (c === '"' && field === '') {
190
+ inQuotes = true;
191
+ } else if (c === delim) {
192
+ record.push(field);
193
+ field = '';
194
+ } else if (c === '\r' || c === '\n') {
195
+ if (c === '\r' && input[i + 1] === '\n') i++;
196
+ record.push(field);
197
+ field = '';
198
+ records.push(record);
199
+ record = [];
200
+ pending = false;
201
+ } else {
202
+ field += c;
203
+ }
204
+ }
205
+ if (pending || field !== '') {
206
+ record.push(field);
207
+ records.push(record);
208
+ }
209
+ return records;
210
+ }
211
+
212
+ describe('csv — CR/LF preservation', () => {
213
+ const modes: [string, boolean, boolean][] = [
214
+ ['lf', false, false],
215
+ ['crlf', true, false],
216
+ ['lf/quote-all', false, true],
217
+ ['crlf/quote-all', true, true],
218
+ ];
219
+
220
+ // The load-bearing case: in CRLF mode csv-stringify left the embedded LF
221
+ // UNQUOTED, so one 9-field record decoded as two records. That is not a
222
+ // parity question — it is structurally invalid CSV.
223
+ it.each(modes)('quotes and preserves CR/LF verbatim (%s)', (_label, crlf, quoteAll) => {
224
+ const s = makeStream();
225
+ csvFormatter.render(
226
+ s.stream,
227
+ [adversarialRow],
228
+ { delimiter: ',', 'no-header': true, 'quote-all': quoteAll, crlf },
229
+ [],
230
+ );
231
+ const out = s.captured();
232
+ expect(out).toContain('"with\rcr"');
233
+ expect(out).toContain('"with\nnewline"');
234
+ expect(out).toContain('" leading space"');
235
+ expect(out.endsWith(crlf ? '\r\n' : '\n')).toBe(true);
236
+ });
237
+
238
+ // Round-trip is the acceptance criterion, not byte-equality: byte-equality
239
+ // alone would be satisfied by every runtime agreeing on lossy output.
240
+ it.each(modes)('round-trips the adversarial row (%s)', (_label, crlf, quoteAll) => {
241
+ const s = makeStream();
242
+ csvFormatter.render(
243
+ s.stream,
244
+ [adversarialRow],
245
+ { delimiter: ',', 'no-header': true, 'quote-all': quoteAll, crlf },
246
+ [],
247
+ );
248
+ const recs = decodeCsv(s.captured());
249
+ expect(recs).toHaveLength(1);
250
+ expect(recs[0]).toEqual(adversarialValues);
251
+ });
252
+
253
+ it('changes only the record terminator in crlf mode', () => {
254
+ const s = makeStream();
255
+ csvFormatter.render(
256
+ s.stream,
257
+ [{ v: 'a\nb' }],
258
+ { delimiter: ',', 'no-header': true, 'quote-all': false, crlf: true },
259
+ [],
260
+ );
261
+ expect(s.captured()).toBe('"a\nb"\r\n');
262
+ });
263
+
264
+ it.each([
265
+ ['tab', '\tlead', '"\tlead"\n'],
266
+ ['space', ' lead', '" lead"\n'],
267
+ ['nbsp', '\u00a0lead', '"\u00a0lead"\n'],
268
+ ['vtab', '\vlead', '"\vlead"\n'],
269
+ ['trailing space stays bare', 'trail ', 'trail \n'],
270
+ ['plain stays bare', 'plain', 'plain\n'],
271
+ ])('quotes any leading unicode space (%s)', (_label, input, want) => {
272
+ const s = makeStream();
273
+ csvFormatter.render(
274
+ s.stream,
275
+ [{ v: input }],
276
+ { delimiter: ',', 'no-header': true, 'quote-all': false, crlf: false },
277
+ [],
278
+ );
279
+ expect(s.captured()).toBe(want);
280
+ });
281
+
282
+ // `\.` alone on a line terminates a PostgreSQL COPY stream.
283
+ it('quotes the postgres COPY sentinel', () => {
284
+ const s = makeStream();
285
+ csvFormatter.render(
286
+ s.stream,
287
+ [{ v: '\\.' }],
288
+ { delimiter: ',', 'no-header': true, 'quote-all': false, crlf: false },
289
+ [],
290
+ );
291
+ expect(s.captured()).toBe('"\\."\n');
292
+ });
293
+ });