ts-procedures 5.15.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/agent_config/claude-code/agents/ts-procedures-architect.md +13 -6
- package/agent_config/claude-code/skills/ts-procedures/SKILL.md +26 -4
- package/agent_config/claude-code/skills/ts-procedures/anti-patterns.md +85 -17
- package/agent_config/claude-code/skills/ts-procedures/api-reference.md +220 -9
- package/agent_config/claude-code/skills/ts-procedures/patterns.md +271 -16
- package/agent_config/claude-code/skills/ts-procedures-review/SKILL.md +1 -1
- package/agent_config/claude-code/skills/ts-procedures-review/checklist.md +20 -12
- package/agent_config/claude-code/skills/ts-procedures-scaffold/SKILL.md +2 -1
- package/agent_config/claude-code/skills/ts-procedures-scaffold/templates/client.md +53 -18
- package/agent_config/claude-code/skills/ts-procedures-scaffold/templates/express-rpc.md +20 -17
- package/agent_config/claude-code/skills/ts-procedures-scaffold/templates/hono-api.md +20 -16
- package/agent_config/claude-code/skills/ts-procedures-scaffold/templates/hono-rpc.md +20 -17
- package/agent_config/claude-code/skills/ts-procedures-scaffold/templates/hono-stream.md +16 -3
- package/agent_config/copilot/copilot-instructions.md +132 -19
- package/agent_config/cursor/cursorrules +132 -19
- package/build/client/call.d.ts +19 -9
- package/build/client/call.js +33 -19
- package/build/client/call.js.map +1 -1
- package/build/client/call.test.js +167 -17
- package/build/client/call.test.js.map +1 -1
- package/build/client/error-dispatch.d.ts +13 -0
- package/build/client/error-dispatch.js +26 -0
- package/build/client/error-dispatch.js.map +1 -0
- package/build/client/error-dispatch.test.d.ts +1 -0
- package/build/client/error-dispatch.test.js +56 -0
- package/build/client/error-dispatch.test.js.map +1 -0
- package/build/client/fetch-adapter.js +10 -4
- package/build/client/fetch-adapter.js.map +1 -1
- package/build/client/index.d.ts +2 -1
- package/build/client/index.js +22 -3
- package/build/client/index.js.map +1 -1
- package/build/client/index.test.js +104 -0
- package/build/client/index.test.js.map +1 -1
- package/build/client/resolve-options.d.ts +45 -0
- package/build/client/resolve-options.js +82 -0
- package/build/client/resolve-options.js.map +1 -0
- package/build/client/resolve-options.test.d.ts +1 -0
- package/build/client/resolve-options.test.js +158 -0
- package/build/client/resolve-options.test.js.map +1 -0
- package/build/client/stream.d.ts +19 -9
- package/build/client/stream.js +36 -21
- package/build/client/stream.js.map +1 -1
- package/build/client/stream.test.js +102 -46
- package/build/client/stream.test.js.map +1 -1
- package/build/client/typed-error-dispatch.test.d.ts +1 -0
- package/build/client/typed-error-dispatch.test.js +168 -0
- package/build/client/typed-error-dispatch.test.js.map +1 -0
- package/build/client/types.d.ts +105 -1
- package/build/client/types.js +1 -1
- package/build/codegen/e2e.test.js +150 -4
- package/build/codegen/e2e.test.js.map +1 -1
- package/build/codegen/emit-client-runtime.js +7 -0
- package/build/codegen/emit-client-runtime.js.map +1 -1
- package/build/codegen/emit-errors.d.ts +17 -6
- package/build/codegen/emit-errors.integration.test.d.ts +1 -0
- package/build/codegen/emit-errors.integration.test.js +162 -0
- package/build/codegen/emit-errors.integration.test.js.map +1 -0
- package/build/codegen/emit-errors.js +50 -39
- package/build/codegen/emit-errors.js.map +1 -1
- package/build/codegen/emit-errors.test.js +75 -78
- package/build/codegen/emit-errors.test.js.map +1 -1
- package/build/codegen/emit-index.d.ts +7 -0
- package/build/codegen/emit-index.js +26 -4
- package/build/codegen/emit-index.js.map +1 -1
- package/build/codegen/emit-index.test.js +55 -23
- package/build/codegen/emit-index.test.js.map +1 -1
- package/build/codegen/emit-scope.d.ts +8 -0
- package/build/codegen/emit-scope.js +82 -7
- package/build/codegen/emit-scope.js.map +1 -1
- package/build/codegen/pipeline.js +22 -2
- package/build/codegen/pipeline.js.map +1 -1
- package/build/implementations/http/doc-registry.d.ts +21 -0
- package/build/implementations/http/doc-registry.js +51 -78
- package/build/implementations/http/doc-registry.js.map +1 -1
- package/build/implementations/http/doc-registry.test.js +8 -6
- package/build/implementations/http/doc-registry.test.js.map +1 -1
- package/build/implementations/http/error-taxonomy.d.ts +240 -0
- package/build/implementations/http/error-taxonomy.js +230 -0
- package/build/implementations/http/error-taxonomy.js.map +1 -0
- package/build/implementations/http/error-taxonomy.test.d.ts +1 -0
- package/build/implementations/http/error-taxonomy.test.js +399 -0
- package/build/implementations/http/error-taxonomy.test.js.map +1 -0
- package/build/implementations/http/express-rpc/error-taxonomy.test.d.ts +1 -0
- package/build/implementations/http/express-rpc/error-taxonomy.test.js +83 -0
- package/build/implementations/http/express-rpc/error-taxonomy.test.js.map +1 -0
- package/build/implementations/http/express-rpc/index.d.ts +39 -8
- package/build/implementations/http/express-rpc/index.js +39 -8
- package/build/implementations/http/express-rpc/index.js.map +1 -1
- package/build/implementations/http/hono-api/error-taxonomy.test.d.ts +1 -0
- package/build/implementations/http/hono-api/error-taxonomy.test.js +137 -0
- package/build/implementations/http/hono-api/error-taxonomy.test.js.map +1 -0
- package/build/implementations/http/hono-api/index.d.ts +38 -1
- package/build/implementations/http/hono-api/index.js +32 -0
- package/build/implementations/http/hono-api/index.js.map +1 -1
- package/build/implementations/http/hono-rpc/error-taxonomy.test.d.ts +1 -0
- package/build/implementations/http/hono-rpc/error-taxonomy.test.js +64 -0
- package/build/implementations/http/hono-rpc/error-taxonomy.test.js.map +1 -0
- package/build/implementations/http/hono-rpc/index.d.ts +34 -7
- package/build/implementations/http/hono-rpc/index.js +31 -4
- package/build/implementations/http/hono-rpc/index.js.map +1 -1
- package/build/implementations/http/hono-stream/error-taxonomy.test.d.ts +1 -0
- package/build/implementations/http/hono-stream/error-taxonomy.test.js +87 -0
- package/build/implementations/http/hono-stream/error-taxonomy.test.js.map +1 -0
- package/build/implementations/http/hono-stream/index.d.ts +40 -3
- package/build/implementations/http/hono-stream/index.js +37 -10
- package/build/implementations/http/hono-stream/index.js.map +1 -1
- package/build/implementations/http/hono-stream/index.test.js +45 -18
- package/build/implementations/http/hono-stream/index.test.js.map +1 -1
- package/build/implementations/http/on-request-error.test.d.ts +1 -0
- package/build/implementations/http/on-request-error.test.js +173 -0
- package/build/implementations/http/on-request-error.test.js.map +1 -0
- package/build/implementations/http/route-errors.test.d.ts +1 -0
- package/build/implementations/http/route-errors.test.js +140 -0
- package/build/implementations/http/route-errors.test.js.map +1 -0
- package/build/implementations/types.d.ts +30 -2
- package/docs/client-and-codegen.md +228 -14
- package/docs/core.md +14 -5
- package/docs/http-integrations.md +135 -4
- package/docs/streaming.md +3 -1
- package/package.json +7 -2
- package/src/client/call.test.ts +202 -29
- package/src/client/call.ts +50 -28
- package/src/client/error-dispatch.test.ts +72 -0
- package/src/client/error-dispatch.ts +27 -0
- package/src/client/fetch-adapter.ts +11 -5
- package/src/client/index.test.ts +117 -0
- package/src/client/index.ts +34 -8
- package/src/client/resolve-options.test.ts +205 -0
- package/src/client/resolve-options.ts +113 -0
- package/src/client/stream.test.ts +132 -107
- package/src/client/stream.ts +53 -27
- package/src/client/typed-error-dispatch.test.ts +211 -0
- package/src/client/types.ts +116 -2
- package/src/codegen/e2e.test.ts +160 -4
- package/src/codegen/emit-client-runtime.ts +7 -0
- package/src/codegen/emit-errors.integration.test.ts +183 -0
- package/src/codegen/emit-errors.test.ts +91 -87
- package/src/codegen/emit-errors.ts +123 -41
- package/src/codegen/emit-index.test.ts +68 -24
- package/src/codegen/emit-index.ts +66 -4
- package/src/codegen/emit-scope.ts +124 -7
- package/src/codegen/pipeline.ts +25 -2
- package/src/implementations/http/README.md +28 -5
- package/src/implementations/http/doc-registry.test.ts +10 -6
- package/src/implementations/http/doc-registry.ts +63 -80
- package/src/implementations/http/error-taxonomy.test.ts +438 -0
- package/src/implementations/http/error-taxonomy.ts +337 -0
- package/src/implementations/http/express-rpc/README.md +21 -22
- package/src/implementations/http/express-rpc/error-taxonomy.test.ts +103 -0
- package/src/implementations/http/express-rpc/index.ts +75 -14
- package/src/implementations/http/hono-api/README.md +284 -0
- package/src/implementations/http/hono-api/error-taxonomy.test.ts +179 -0
- package/src/implementations/http/hono-api/index.ts +76 -1
- package/src/implementations/http/hono-rpc/README.md +18 -19
- package/src/implementations/http/hono-rpc/error-taxonomy.test.ts +82 -0
- package/src/implementations/http/hono-rpc/index.ts +65 -9
- package/src/implementations/http/hono-stream/README.md +44 -25
- package/src/implementations/http/hono-stream/error-taxonomy.test.ts +98 -0
- package/src/implementations/http/hono-stream/index.test.ts +54 -18
- package/src/implementations/http/hono-stream/index.ts +83 -13
- package/src/implementations/http/on-request-error.test.ts +201 -0
- package/src/implementations/http/route-errors.test.ts +177 -0
- package/src/implementations/types.ts +30 -2
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-empty-object-type */
|
|
2
|
+
import { describe, expect, test } from 'vitest';
|
|
3
|
+
import { Type } from 'typebox';
|
|
4
|
+
import { Procedures } from '../../index.js';
|
|
5
|
+
import { HonoAPIAppBuilder } from './hono-api/index.js';
|
|
6
|
+
import { HonoRPCAppBuilder } from './hono-rpc/index.js';
|
|
7
|
+
import { ExpressRPCAppBuilder } from './express-rpc/index.js';
|
|
8
|
+
import { HonoStreamAppBuilder } from './hono-stream/index.js';
|
|
9
|
+
import { DocRegistry } from './doc-registry.js';
|
|
10
|
+
import { defineErrorTaxonomy } from './error-taxonomy.js';
|
|
11
|
+
class UseCaseError extends Error {
|
|
12
|
+
externalMsg;
|
|
13
|
+
constructor(externalMsg) {
|
|
14
|
+
super(externalMsg);
|
|
15
|
+
this.externalMsg = externalMsg;
|
|
16
|
+
this.name = 'UseCaseError';
|
|
17
|
+
Object.setPrototypeOf(this, UseCaseError.prototype);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
class AuthError extends Error {
|
|
21
|
+
}
|
|
22
|
+
const appErrors = defineErrorTaxonomy({
|
|
23
|
+
UseCaseError: { class: UseCaseError, statusCode: 422 },
|
|
24
|
+
AuthError: { class: AuthError, statusCode: 401 },
|
|
25
|
+
});
|
|
26
|
+
describe('per-route errors declaration', () => {
|
|
27
|
+
test('hono-api copies config.errors onto the route doc', () => {
|
|
28
|
+
const API = Procedures();
|
|
29
|
+
API.Create('GetUser', {
|
|
30
|
+
path: '/users/:id',
|
|
31
|
+
method: 'get',
|
|
32
|
+
errors: ['UseCaseError', 'AuthError'],
|
|
33
|
+
schema: {
|
|
34
|
+
input: { pathParams: Type.Object({ id: Type.String() }) },
|
|
35
|
+
returnType: Type.Object({}),
|
|
36
|
+
},
|
|
37
|
+
}, async () => ({}));
|
|
38
|
+
const builder = new HonoAPIAppBuilder().register(API, () => ({}));
|
|
39
|
+
builder.build();
|
|
40
|
+
expect(builder.docs[0].errors).toEqual(['UseCaseError', 'AuthError']);
|
|
41
|
+
});
|
|
42
|
+
test('hono-api route doc omits errors when not declared', () => {
|
|
43
|
+
const API = Procedures();
|
|
44
|
+
API.Create('Health', { path: '/health', method: 'get', schema: { returnType: Type.Object({}) } }, async () => ({}));
|
|
45
|
+
const builder = new HonoAPIAppBuilder().register(API, () => ({}));
|
|
46
|
+
builder.build();
|
|
47
|
+
expect(builder.docs[0].errors).toBeUndefined();
|
|
48
|
+
});
|
|
49
|
+
test('hono-rpc copies config.errors onto the route doc', () => {
|
|
50
|
+
const RPC = Procedures();
|
|
51
|
+
RPC.Create('DoThing', {
|
|
52
|
+
scope: 'things',
|
|
53
|
+
version: 1,
|
|
54
|
+
errors: ['UseCaseError'],
|
|
55
|
+
schema: { params: Type.Object({}) },
|
|
56
|
+
}, async () => ({}));
|
|
57
|
+
const builder = new HonoRPCAppBuilder().register(RPC, () => ({}));
|
|
58
|
+
builder.build();
|
|
59
|
+
expect(builder.docs[0].errors).toEqual(['UseCaseError']);
|
|
60
|
+
});
|
|
61
|
+
test('express-rpc copies config.errors onto the route doc', () => {
|
|
62
|
+
const RPC = Procedures();
|
|
63
|
+
RPC.Create('DoThing', {
|
|
64
|
+
scope: 'things',
|
|
65
|
+
version: 1,
|
|
66
|
+
errors: ['AuthError'],
|
|
67
|
+
schema: { params: Type.Object({}) },
|
|
68
|
+
}, async () => ({}));
|
|
69
|
+
const builder = new ExpressRPCAppBuilder().register(RPC, () => ({}));
|
|
70
|
+
builder.build();
|
|
71
|
+
expect(builder.docs[0].errors).toEqual(['AuthError']);
|
|
72
|
+
});
|
|
73
|
+
test('hono-stream copies config.errors onto the route doc', () => {
|
|
74
|
+
const Stream = Procedures();
|
|
75
|
+
Stream.CreateStream('Watch', { scope: 'watch', version: 1, errors: ['AuthError'] }, async function* () {
|
|
76
|
+
yield { ok: true };
|
|
77
|
+
});
|
|
78
|
+
const builder = new HonoStreamAppBuilder().register(Stream, () => ({}));
|
|
79
|
+
builder.build();
|
|
80
|
+
expect(builder.docs[0].errors).toEqual(['AuthError']);
|
|
81
|
+
});
|
|
82
|
+
test('compile-time: errors typed as keyof taxonomy narrows valid keys', () => {
|
|
83
|
+
const _valid = ['UseCaseError', 'AuthError'];
|
|
84
|
+
// @ts-expect-error - 'NotRegistered' is not in the taxonomy
|
|
85
|
+
const _invalid = ['NotRegistered'];
|
|
86
|
+
expect(_valid).toBeDefined();
|
|
87
|
+
expect(_invalid).toBeDefined();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
describe('DocRegistry.fromTaxonomy', () => {
|
|
91
|
+
test('seeds envelope errors from the taxonomy + framework defaults', () => {
|
|
92
|
+
const registry = DocRegistry.fromTaxonomy(appErrors, { basePath: '/api' });
|
|
93
|
+
const envelope = registry.toJSON();
|
|
94
|
+
const names = envelope.errors.map((e) => e.name);
|
|
95
|
+
expect(names).toContain('UseCaseError');
|
|
96
|
+
expect(names).toContain('AuthError');
|
|
97
|
+
expect(names).toContain('ProcedureValidationError');
|
|
98
|
+
expect(names).toContain('ProcedureRegistrationError');
|
|
99
|
+
expect(envelope.basePath).toBe('/api');
|
|
100
|
+
});
|
|
101
|
+
test('includeDefaults: false omits framework entries', () => {
|
|
102
|
+
const registry = DocRegistry.fromTaxonomy(appErrors, { includeDefaults: false });
|
|
103
|
+
const names = registry.toJSON().errors.map((e) => e.name);
|
|
104
|
+
expect(names).toEqual(['UseCaseError', 'AuthError']);
|
|
105
|
+
});
|
|
106
|
+
test('user entry with same key as default takes precedence (deduped)', () => {
|
|
107
|
+
const overridden = defineErrorTaxonomy({
|
|
108
|
+
ProcedureError: {
|
|
109
|
+
class: Error,
|
|
110
|
+
statusCode: 418,
|
|
111
|
+
description: 'custom override',
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
const envelope = DocRegistry.fromTaxonomy(overridden).toJSON();
|
|
115
|
+
const proc = envelope.errors.find((e) => e.name === 'ProcedureError');
|
|
116
|
+
expect(proc?.statusCode).toBe(418);
|
|
117
|
+
expect(proc?.description).toBe('custom override');
|
|
118
|
+
// no duplicates
|
|
119
|
+
const count = envelope.errors.filter((e) => e.name === 'ProcedureError').length;
|
|
120
|
+
expect(count).toBe(1);
|
|
121
|
+
});
|
|
122
|
+
test('registered route errors survive DocRegistry composition', () => {
|
|
123
|
+
const API = Procedures();
|
|
124
|
+
API.Create('GetUser', {
|
|
125
|
+
path: '/users/:id',
|
|
126
|
+
method: 'get',
|
|
127
|
+
errors: ['UseCaseError'],
|
|
128
|
+
schema: {
|
|
129
|
+
input: { pathParams: Type.Object({ id: Type.String() }) },
|
|
130
|
+
returnType: Type.Object({}),
|
|
131
|
+
},
|
|
132
|
+
}, async () => ({}));
|
|
133
|
+
const app = new HonoAPIAppBuilder().register(API, () => ({}));
|
|
134
|
+
app.build();
|
|
135
|
+
const envelope = DocRegistry.fromTaxonomy(appErrors).from(app).toJSON();
|
|
136
|
+
const route = envelope.routes.find((r) => r.kind === 'api' && r.name === 'GetUser');
|
|
137
|
+
expect(route?.errors).toEqual(['UseCaseError']);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
//# sourceMappingURL=route-errors.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-errors.test.js","sourceRoot":"","sources":["../../../src/implementations/http/route-errors.test.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IA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A;QACvE,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,KAAK,IAAI,CAAC,CAAC,IAAI,KAAK,SAAS,CAAC,CAAA;QACnF,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAC,CAAA;IACjD,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"}
|
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
import { Procedures } from '../index.js';
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* @typeParam TErrorKey - Union of valid taxonomy keys. Defaults to `string`
|
|
4
|
+
* (unconstrained). Narrow it by passing `keyof typeof yourTaxonomy & string`
|
|
5
|
+
* to get compile-time typo protection on `errors`.
|
|
6
|
+
*/
|
|
7
|
+
export interface RPCConfig<TErrorKey extends string = string> {
|
|
3
8
|
scope: string | string[];
|
|
4
9
|
version: number;
|
|
10
|
+
/**
|
|
11
|
+
* Taxonomy keys for errors this procedure may emit. Purely informational at
|
|
12
|
+
* runtime (nothing is rejected), but populates the DocEnvelope per-route
|
|
13
|
+
* error list so generated clients can narrow their catch types.
|
|
14
|
+
*/
|
|
15
|
+
errors?: TErrorKey[];
|
|
5
16
|
}
|
|
6
17
|
export type FactoryItem<C> = {
|
|
7
18
|
factory: ReturnType<typeof Procedures<C, RPCConfig>>;
|
|
@@ -16,10 +27,17 @@ export interface RPCHttpRouteDoc extends RPCConfig {
|
|
|
16
27
|
body?: Record<string, unknown>;
|
|
17
28
|
response?: Record<string, unknown>;
|
|
18
29
|
};
|
|
30
|
+
/** Taxonomy keys for errors this route may emit. */
|
|
31
|
+
errors?: string[];
|
|
19
32
|
}
|
|
20
33
|
export type StreamMode = 'sse' | 'text';
|
|
21
34
|
export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head';
|
|
22
|
-
|
|
35
|
+
/**
|
|
36
|
+
* @typeParam TErrorKey - Union of valid taxonomy keys. Defaults to `string`.
|
|
37
|
+
* Narrow it by passing `keyof typeof yourTaxonomy & string` for compile-time
|
|
38
|
+
* typo protection on `errors`.
|
|
39
|
+
*/
|
|
40
|
+
export interface APIConfig<TErrorKey extends string = string> {
|
|
23
41
|
/** HTTP route path (supports Hono path params, e.g., '/users/:id') */
|
|
24
42
|
path: string;
|
|
25
43
|
/** HTTP method for this endpoint */
|
|
@@ -28,6 +46,12 @@ export interface APIConfig {
|
|
|
28
46
|
successStatus?: number;
|
|
29
47
|
/** Optional scope for grouping API routes in generated client files */
|
|
30
48
|
scope?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Taxonomy keys for errors this procedure may emit. Purely informational at
|
|
51
|
+
* runtime (nothing is rejected), but populates the DocEnvelope per-route
|
|
52
|
+
* error list so generated clients can narrow their catch types.
|
|
53
|
+
*/
|
|
54
|
+
errors?: TErrorKey[];
|
|
31
55
|
}
|
|
32
56
|
export interface APIHttpRouteDoc extends APIConfig {
|
|
33
57
|
kind: 'api';
|
|
@@ -41,6 +65,8 @@ export interface APIHttpRouteDoc extends APIConfig {
|
|
|
41
65
|
headers?: Record<string, unknown>;
|
|
42
66
|
response?: Record<string, unknown>;
|
|
43
67
|
};
|
|
68
|
+
/** Taxonomy keys for errors this route may emit. */
|
|
69
|
+
errors?: string[];
|
|
44
70
|
}
|
|
45
71
|
/**
|
|
46
72
|
* Constrains schema.input channel names to valid HTTP input sources.
|
|
@@ -76,6 +102,8 @@ export interface StreamHttpRouteDoc extends RPCConfig {
|
|
|
76
102
|
yieldType?: Record<string, unknown>;
|
|
77
103
|
returnType?: Record<string, unknown>;
|
|
78
104
|
};
|
|
105
|
+
/** Taxonomy keys for errors this route may emit (pre-stream only). */
|
|
106
|
+
errors?: string[];
|
|
79
107
|
}
|
|
80
108
|
/**
|
|
81
109
|
* Extracts the TContext type from a Procedures factory return type.
|
|
@@ -20,14 +20,14 @@ npx ts-procedures-codegen --url http://localhost:3000/docs --out ./src/generated
|
|
|
20
20
|
|
|
21
21
|
**Step 3 — Use the client:**
|
|
22
22
|
|
|
23
|
+
The recommended entrypoint is the generated `create${Service}Client` factory. It calls `createClient` under the hood with the generated error registry pre-wired, so non-2xx responses arrive as typed class instances you can catch with `instanceof`.
|
|
24
|
+
|
|
23
25
|
```typescript
|
|
24
|
-
import {
|
|
25
|
-
import { createApiBindings, Api } from './generated/api'
|
|
26
|
+
import { createApiClient, ApiErrors, createFetchAdapter } from './generated/api'
|
|
26
27
|
|
|
27
|
-
const
|
|
28
|
+
const api = createApiClient({
|
|
28
29
|
adapter: createFetchAdapter(),
|
|
29
30
|
basePath: 'http://localhost:3000',
|
|
30
|
-
scopes: createApiBindings,
|
|
31
31
|
hooks: {
|
|
32
32
|
onBeforeRequest(ctx) {
|
|
33
33
|
ctx.request.headers = { ...ctx.request.headers, Authorization: `Bearer ${getToken()}` }
|
|
@@ -36,11 +36,32 @@ const client = createClient({
|
|
|
36
36
|
},
|
|
37
37
|
})
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
const user = await
|
|
39
|
+
try {
|
|
40
|
+
const user = await api.users.GetUser({ pathParams: { id: '123' } })
|
|
41
|
+
} catch (err) {
|
|
42
|
+
if (err instanceof ApiErrors.UseCaseError) {
|
|
43
|
+
// err.body, err.status, err.procedureName, err.scope all typed
|
|
44
|
+
} else if (err instanceof ApiErrors.ApiProcedureError) {
|
|
45
|
+
// Catch-all for any service error (shared base class)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Types live under the service namespace: Api.Users.GetUser.Params, Api.Errors.UseCaseError, etc.
|
|
50
|
+
// Pass --service-name <Name> to rename `Api` → `<Name>` throughout.
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
For advanced control (sharing one `ClientInstance` across services, composing with a custom registry), use `createClient` + `create${Service}Bindings` directly:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { createClient, createFetchAdapter } from 'ts-procedures/client'
|
|
57
|
+
import { createApiBindings, ApiErrors } from './generated/api'
|
|
41
58
|
|
|
42
|
-
|
|
43
|
-
|
|
59
|
+
const api = createClient({
|
|
60
|
+
adapter: createFetchAdapter(),
|
|
61
|
+
basePath: 'http://localhost:3000',
|
|
62
|
+
scopes: createApiBindings,
|
|
63
|
+
errorRegistry: ApiErrors.ApiErrorRegistry, // opt in to typed dispatch — omit to get the plain ClientRequestError transport shape
|
|
64
|
+
})
|
|
44
65
|
```
|
|
45
66
|
|
|
46
67
|
## Generated File Structure
|
|
@@ -54,8 +75,8 @@ generated/
|
|
|
54
75
|
notifications.ts # Types + callables for stream procedures
|
|
55
76
|
_types.ts # Client type definitions (self-contained mode)
|
|
56
77
|
_client.ts # Client runtime bundle (self-contained mode)
|
|
57
|
-
_errors.ts #
|
|
58
|
-
index.ts # Service namespace
|
|
78
|
+
_errors.ts # Runtime error classes extending ${ServiceName}ProcedureError + static fromResponse + ${ServiceName}ErrorRegistry + ${ServiceName}ProcedureErrorUnion (default: ApiProcedureError / ApiErrorRegistry / ApiProcedureErrorUnion)
|
|
79
|
+
index.ts # Service namespace + create${ServiceName}Bindings (manual wiring) and create${ServiceName}Client (convenience; registry pre-wired). Default: Api / createApiBindings / createApiClient.
|
|
59
80
|
```
|
|
60
81
|
|
|
61
82
|
## CLI Reference
|
|
@@ -106,9 +127,182 @@ const axiosAdapter: ClientAdapter = {
|
|
|
106
127
|
}
|
|
107
128
|
```
|
|
108
129
|
|
|
130
|
+
## Per-Call Options
|
|
131
|
+
|
|
132
|
+
Every generated callable accepts an optional second argument for per-call configuration. The options bag covers both request-level config (timeout, cancellation, headers, base path) and hooks.
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
// Timeout — aborts the request if it runs longer than 5 seconds
|
|
136
|
+
const user = await client.users.GetUser({ pathParams: { id: '123' } }, { timeout: 5000 })
|
|
137
|
+
|
|
138
|
+
// Cancellation — pass your own AbortSignal
|
|
139
|
+
const controller = new AbortController()
|
|
140
|
+
const user = await client.users.GetUser({ pathParams: { id: '123' } }, { signal: controller.signal })
|
|
141
|
+
|
|
142
|
+
// Per-call headers (correlation IDs, feature flags, etc.)
|
|
143
|
+
const user = await client.users.GetUser(
|
|
144
|
+
{ pathParams: { id: '123' } },
|
|
145
|
+
{ headers: { 'X-Request-Id': crypto.randomUUID() } },
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
// Override base path for a single call (multi-region fallback, dev/prod switching)
|
|
149
|
+
const user = await client.users.GetUser(
|
|
150
|
+
{ pathParams: { id: '123' } },
|
|
151
|
+
{ basePath: 'https://api-eu.example.com' },
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
// Combine options with per-call hooks
|
|
155
|
+
await client.users.GetUser(
|
|
156
|
+
{ pathParams: { id: '123' } },
|
|
157
|
+
{
|
|
158
|
+
timeout: 5000,
|
|
159
|
+
headers: { 'X-Trace-Id': traceId },
|
|
160
|
+
onAfterResponse(ctx) { log(ctx) },
|
|
161
|
+
},
|
|
162
|
+
)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Client-Level Defaults
|
|
166
|
+
|
|
167
|
+
Set defaults via `config.defaults` — they apply to every call and are overridden by per-call options. Headers merge (per-call keys win); `signal` combines with per-call via `AbortSignal.any` (whichever aborts first wins); `timeout` is overridden by per-call `timeout`, and per-call `timeout: 0` disables an inherited default timeout.
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
const client = createClient({
|
|
171
|
+
adapter,
|
|
172
|
+
basePath: 'http://localhost:3000',
|
|
173
|
+
scopes: createApiBindings,
|
|
174
|
+
defaults: {
|
|
175
|
+
timeout: 30_000,
|
|
176
|
+
headers: { 'X-Client-Version': '1.0.0' },
|
|
177
|
+
},
|
|
178
|
+
})
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Typed Per-Request Metadata
|
|
182
|
+
|
|
183
|
+
Every `AdapterRequest` carries an optional `meta` field typed via the `RequestMeta` interface. `RequestMeta` is declared empty by design — augment it in your own project via TypeScript declaration merging and your fields become typed end-to-end: in per-call options, in hook contexts, and inside your adapter.
|
|
184
|
+
|
|
185
|
+
**Self-contained (code-generated) client:**
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
declare module './generated/_types' {
|
|
189
|
+
interface RequestMeta {
|
|
190
|
+
traceId: string
|
|
191
|
+
priority?: 'high' | 'low'
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
**Direct import of `ts-procedures/client`:**
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
declare module 'ts-procedures/client' {
|
|
200
|
+
interface RequestMeta {
|
|
201
|
+
traceId: string
|
|
202
|
+
priority?: 'high' | 'low'
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
After augmentation, `meta` is typed everywhere:
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
const client = createClient({
|
|
211
|
+
adapter: {
|
|
212
|
+
async request(req) {
|
|
213
|
+
const trace = req.meta?.traceId // typed as string | undefined
|
|
214
|
+
const pri = req.meta?.priority // typed as 'high' | 'low' | undefined
|
|
215
|
+
// ...send the request
|
|
216
|
+
},
|
|
217
|
+
async stream(req) { /* same */ },
|
|
218
|
+
},
|
|
219
|
+
basePath: 'http://localhost:3000',
|
|
220
|
+
scopes: createApiBindings,
|
|
221
|
+
defaults: {
|
|
222
|
+
meta: { traceId: 'default-trace' }, // typed
|
|
223
|
+
},
|
|
224
|
+
hooks: {
|
|
225
|
+
onBeforeRequest(ctx) {
|
|
226
|
+
const trace = ctx.request.meta?.traceId // typed
|
|
227
|
+
return ctx
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
// Per-call meta — traceId required, priority optional
|
|
233
|
+
await client.users.GetUser(
|
|
234
|
+
{ pathParams: { id: '123' } },
|
|
235
|
+
{ meta: { traceId: 'req-abc', priority: 'high' } },
|
|
236
|
+
)
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
If `RequestMeta` declares required fields, the merged meta (defaults + per-call) must contain them at runtime. TypeScript can't statically verify this across the merge boundary, so supply required fields in `defaults.meta` or per-call `options.meta`.
|
|
240
|
+
|
|
241
|
+
## Typed Error Handling
|
|
242
|
+
|
|
243
|
+
Non-2xx responses whose body has a `name` field matching a registry key are dispatched into typed class instances. The generated `_errors.ts` exports:
|
|
244
|
+
|
|
245
|
+
- A shared base class `${ServiceName}ProcedureError<TBody>` — carries `status`, `procedureName`, `scope`, and `body`. Catch any service error with `instanceof ${ServiceName}Errors.${ServiceName}ProcedureError`.
|
|
246
|
+
- One concrete class per taxonomy entry in the envelope, each with a static `fromResponse(body, meta)` factory.
|
|
247
|
+
- `${ServiceName}ErrorRegistry` — a `{ [name]: ErrorClass }` object consumed by the client's `dispatchTypedError`.
|
|
248
|
+
- `${ServiceName}ProcedureErrorUnion` — a type union of every generated class for annotating catch clauses.
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
import { createApiClient, ApiErrors } from './generated/api'
|
|
252
|
+
|
|
253
|
+
const api = createApiClient({ adapter, basePath: '...' })
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
await api.users.GetUser({ pathParams: { id: 'x' } })
|
|
257
|
+
} catch (err) {
|
|
258
|
+
if (err instanceof ApiErrors.UseCaseError) {
|
|
259
|
+
// err.body is typed to UseCaseErrorBody; err.status, err.procedureName, err.scope available
|
|
260
|
+
} else if (err instanceof ApiErrors.ApiProcedureError) {
|
|
261
|
+
// Catch-all for any generated service error
|
|
262
|
+
} else if (err instanceof ClientRequestError) {
|
|
263
|
+
// Transport-level error (unmatched body.name, or non-JSON response)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Per-route error narrowing
|
|
269
|
+
|
|
270
|
+
When a server route declares `errors: ['UseCaseError', 'AuthError']` on its config, the generated scope file emits an `Errors` type union inside that route's namespace:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
// Generated scope file:
|
|
274
|
+
export namespace Users {
|
|
275
|
+
export namespace GetUser {
|
|
276
|
+
export type Params = { /* ... */ }
|
|
277
|
+
export type Response = { /* ... */ }
|
|
278
|
+
export type Errors = ApiErrors.UseCaseError | ApiErrors.AuthError
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Consumer:
|
|
283
|
+
try { await api.users.GetUser({ pathParams: { id: 'x' } }) }
|
|
284
|
+
catch (err) {
|
|
285
|
+
const e = err as Users.GetUser.Errors | ClientRequestError // TS has no typed-throws; manual annotation
|
|
286
|
+
if (e instanceof ApiErrors.UseCaseError) { /* ... */ }
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
Route-errors that reference keys missing from `_errors.ts` are filtered out at codegen time so generated code never references undefined types.
|
|
291
|
+
|
|
292
|
+
### How dispatch works
|
|
293
|
+
|
|
294
|
+
`src/client/error-dispatch.ts` exports a pure `dispatchTypedError(registry, body, meta)` helper. The client's `call.ts` invokes it on non-2xx responses:
|
|
295
|
+
|
|
296
|
+
1. If no registry, or body isn't an object with a string `name`, or no registry key matches → returns `null`.
|
|
297
|
+
2. Otherwise calls `registry[body.name].fromResponse(body, meta)` and returns the typed `Error` instance.
|
|
298
|
+
|
|
299
|
+
When the helper returns `null`, the call falls back to `ClientRequestError` — the plain transport-error shape, used for unmatched names, non-JSON bodies, and when no registry is configured.
|
|
300
|
+
|
|
301
|
+
Stream endpoints get the same treatment for **pre-stream** errors (thrown before the first yield — e.g. validation or auth). The fetch adapter's `stream()` eagerly parses a JSON body when status is non-2xx and exposes it via `AdapterStreamResponse.errorBody`, which `executeStream` passes through the registry. **Mid-stream** SSE error events continue to flow through `onMidStreamError` on the server and re-throw on the client without registry dispatch.
|
|
302
|
+
|
|
109
303
|
## Hooks
|
|
110
304
|
|
|
111
|
-
Hooks let you intercept requests and responses globally or per-procedure call. Global hooks apply to every call made through the client instance; per-procedure hooks
|
|
305
|
+
Hooks let you intercept requests and responses globally or per-procedure call. Global hooks apply to every call made through the client instance; per-procedure hooks run after global ones for a single invocation.
|
|
112
306
|
|
|
113
307
|
```typescript
|
|
114
308
|
// Global hooks (apply to all calls)
|
|
@@ -123,7 +317,7 @@ const client = createClient({
|
|
|
123
317
|
},
|
|
124
318
|
})
|
|
125
319
|
|
|
126
|
-
// Per-procedure hook
|
|
320
|
+
// Per-procedure hook — hooks and request options share the same options bag
|
|
127
321
|
await client.users.GetUser({ pathParams: { id: '123' } }, {
|
|
128
322
|
onAfterResponse(ctx) {
|
|
129
323
|
const rateLimit = ctx.response.headers['x-rate-limit-remaining']
|
|
@@ -131,6 +325,16 @@ await client.users.GetUser({ pathParams: { id: '123' } }, {
|
|
|
131
325
|
})
|
|
132
326
|
```
|
|
133
327
|
|
|
328
|
+
### Precedence
|
|
329
|
+
|
|
330
|
+
Headers and signals combine across layers. From lowest to highest precedence (within a given field):
|
|
331
|
+
|
|
332
|
+
1. Adapter config (e.g., `createFetchAdapter({ headers })`)
|
|
333
|
+
2. Client `defaults.headers` / `defaults.signal` / `defaults.timeout`
|
|
334
|
+
3. Per-call `options.headers` / `options.signal` / `options.timeout`
|
|
335
|
+
4. Route-declared headers from `schema.input.headers` (part of the typed contract)
|
|
336
|
+
5. `onBeforeRequest` hook mutations — final say
|
|
337
|
+
|
|
134
338
|
## Streaming
|
|
135
339
|
|
|
136
340
|
Stream procedures return a `TypedStream` — an async iterable for yield values, with a `.result` promise for the final return value:
|
|
@@ -186,12 +390,22 @@ import { createClient, createFetchAdapter } from './generated/_client'
|
|
|
186
390
|
import { createClient, createFetchAdapter } from 'ts-procedures/client'
|
|
187
391
|
```
|
|
188
392
|
|
|
393
|
+
- **`_client.ts`** also bundles `error-dispatch.ts`, so registry-based typed error dispatch works without importing `ts-procedures/client` at runtime.
|
|
394
|
+
|
|
189
395
|
## Type Exports
|
|
190
396
|
|
|
191
397
|
```typescript
|
|
192
398
|
// Client Runtime
|
|
193
|
-
import { createClient, createFetchAdapter } from 'ts-procedures/client'
|
|
194
|
-
import type {
|
|
399
|
+
import { createClient, createFetchAdapter, dispatchTypedError } from 'ts-procedures/client'
|
|
400
|
+
import type {
|
|
401
|
+
ClientAdapter,
|
|
402
|
+
ClientHooks,
|
|
403
|
+
TypedStream,
|
|
404
|
+
ClientInstance,
|
|
405
|
+
ErrorRegistry,
|
|
406
|
+
ErrorFactory,
|
|
407
|
+
ErrorResponseMeta,
|
|
408
|
+
} from 'ts-procedures/client'
|
|
195
409
|
|
|
196
410
|
// Code Generation
|
|
197
411
|
import { generateClient } from 'ts-procedures/codegen'
|
package/docs/core.md
CHANGED
|
@@ -31,7 +31,7 @@ Create(name, config, handler)
|
|
|
31
31
|
**Returns:**
|
|
32
32
|
- `{ [name]: handler }` - Named export for the handler
|
|
33
33
|
- `procedure` - Generic reference to the handler
|
|
34
|
-
- `info` - Procedure
|
|
34
|
+
- `info` - Procedure metadata (name, description, schema, `TExtendedConfig` properties, etc.)
|
|
35
35
|
|
|
36
36
|
## Structured Input with schema.input
|
|
37
37
|
|
|
@@ -234,7 +234,8 @@ Create(
|
|
|
234
234
|
async (ctx, params) => {
|
|
235
235
|
const resource = await db.find(params.id)
|
|
236
236
|
if (!resource) {
|
|
237
|
-
|
|
237
|
+
// Signature: ctx.error(message: string, meta?: object) => ProcedureError
|
|
238
|
+
throw ctx.error('Resource not found', { code: 'NOT_FOUND', id: params.id })
|
|
238
239
|
}
|
|
239
240
|
return resource
|
|
240
241
|
},
|
|
@@ -249,6 +250,7 @@ Create(
|
|
|
249
250
|
| ProcedureValidationError | Schema validation failure (params) |
|
|
250
251
|
| ProcedureYieldValidationError | Yield validation failure (streaming with `validateYields: true`) |
|
|
251
252
|
| ProcedureRegistrationError | Invalid schema at registration |
|
|
253
|
+
| `${Service}ProcedureError` (client-side) | Base class for every generated error class on the client — see [Client & Codegen → Typed Error Handling](./client-and-codegen.md#typed-error-handling) |
|
|
252
254
|
|
|
253
255
|
### Error Properties
|
|
254
256
|
|
|
@@ -264,6 +266,12 @@ try {
|
|
|
264
266
|
}
|
|
265
267
|
```
|
|
266
268
|
|
|
269
|
+
### Error Taxonomy (HTTP builders)
|
|
270
|
+
|
|
271
|
+
For structured HTTP error responses, declare an error taxonomy once with `defineErrorTaxonomy` and pass it to any HTTP builder via the `errors` option — handlers `throw` their classes and the builder serializes to the configured status + body. `ctx.error()` continues to work as the ad-hoc ProcedureError path.
|
|
272
|
+
|
|
273
|
+
The taxonomy also drives typed `catch` blocks on generated clients and per-route error documentation. See [HTTP Integrations → Error Handling](./http-integrations.md#error-handling) for the full contract, and [Client & Codegen → Typed Error Handling](./client-and-codegen.md#typed-error-handling) for the client-side surface.
|
|
274
|
+
|
|
267
275
|
## Abort Signal
|
|
268
276
|
|
|
269
277
|
For regular procedures, `ctx.signal` is available when the server implementation provides it. The built-in HTTP integrations (Hono RPC, Express RPC) inject the request's abort signal automatically:
|
|
@@ -394,10 +402,11 @@ describe('GetUser', () => {
|
|
|
394
402
|
})
|
|
395
403
|
|
|
396
404
|
test('has correct schema', () => {
|
|
405
|
+
// `info.schema.params` is the JSON Schema derived from the TypeBox
|
|
406
|
+
// definition above: `Type.Object({ hideName: Type.Optional(Type.Boolean()) })`.
|
|
397
407
|
expect(info.schema.params).toEqual({
|
|
398
408
|
type: 'object',
|
|
399
|
-
properties: {
|
|
400
|
-
required: ['id'],
|
|
409
|
+
properties: { hideName: { type: 'boolean' } },
|
|
401
410
|
})
|
|
402
411
|
})
|
|
403
412
|
})
|
|
@@ -431,7 +440,7 @@ Defines a procedure.
|
|
|
431
440
|
**Returns:**
|
|
432
441
|
- `{ [name]: handler }` - Named handler export
|
|
433
442
|
- `procedure` - Generic handler reference
|
|
434
|
-
- `info` - Procedure
|
|
443
|
+
- `info` - Procedure metadata (name, description, schema, extended-config properties)
|
|
435
444
|
|
|
436
445
|
### Type Exports
|
|
437
446
|
|