@protovalidate-extensions/protovalidate-lingui 0.0.0-stage → 1.1.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 +212 -2
- package/dist/index.d.ts +27 -0
- package/dist/index.js +146 -0
- package/dist/messages.d.ts +11 -0
- package/dist/messages.js +15 -0
- package/package.json +56 -4
- package/skills/protovalidate-lingui/SKILL.md +97 -0
- package/skills/protovalidate-lingui/agents/openai.yaml +3 -0
- package/skills/protovalidate-lingui/references/message-overrides.md +72 -0
package/README.md
CHANGED
|
@@ -1,3 +1,213 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @protovalidate-extensions/protovalidate-lingui
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Standard Schema](https://standardschema.dev/schema) adapters for Protovalidate that return Lingui message IDs in `issue.message`. Translation happens in your UI, so existing errors can follow locale changes without revalidation.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @protovalidate-extensions/protovalidate-lingui @bufbuild/protovalidate @bufbuild/protobuf
|
|
9
|
+
# In applications that render translations:
|
|
10
|
+
pnpm add @lingui/core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Use Protobuf-ES message descriptors generated from `.proto` files with `buf.validate` annotations. This package does not generate descriptors or add validation rules, and does not require Lingui at runtime.
|
|
14
|
+
|
|
15
|
+
## Agent skill
|
|
16
|
+
|
|
17
|
+
The npm package bundles the `protovalidate-lingui` usage skill under `skills/protovalidate-lingui/`. It covers schema adapters, typed message overrides, and Lingui extraction.
|
|
18
|
+
|
|
19
|
+
With pnpm 12.11 or later, install the package normally, then run `pnpm approve` and select its skill. To persist that choice explicitly, merge these settings into the consuming project's `pnpm-workspace.yaml`:
|
|
20
|
+
|
|
21
|
+
```yaml
|
|
22
|
+
permissions:
|
|
23
|
+
"@protovalidate-extensions/protovalidate-lingui":
|
|
24
|
+
skills: [protovalidate-lingui]
|
|
25
|
+
skills:
|
|
26
|
+
dirs:
|
|
27
|
+
- .agents/skills
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Subsequent installs link the approved skill automatically. See [pnpm agent skills](https://pnpm.io/agent-skills). Other package managers still install the bundled files; copy `node_modules/@protovalidate-extensions/protovalidate-lingui/skills/protovalidate-lingui` into your agent's skill directory and refresh the copy when updating the package.
|
|
31
|
+
|
|
32
|
+
## Validate and translate
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { create } from "@bufbuild/protobuf";
|
|
36
|
+
import { i18n } from "@lingui/core";
|
|
37
|
+
import { createStandardSchema } from "@protovalidate-extensions/protovalidate-lingui";
|
|
38
|
+
import { UserSchema } from "./gen/user_pb.js";
|
|
39
|
+
|
|
40
|
+
const schema = createStandardSchema(UserSchema);
|
|
41
|
+
const result = await schema["~standard"].validate(
|
|
42
|
+
create(UserSchema, { displayName: "A" }),
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
if (result.issues) {
|
|
46
|
+
for (const issue of result.issues) {
|
|
47
|
+
// issue: { message: "string.min_len", path: ["displayName"] }
|
|
48
|
+
console.log(issue.path, i18n._(issue.message));
|
|
49
|
+
}
|
|
50
|
+
} else {
|
|
51
|
+
console.log(result.value);
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Pass `schema` to any Standard Schema V1 consumer. Consumers display raw IDs unless your UI translates them. In React, use the active instance from `useLingui()` so rendering updates when the locale changes.
|
|
56
|
+
|
|
57
|
+
## Validate an initializer
|
|
58
|
+
|
|
59
|
+
Use `createStandardSchemaInit` when a consumer supplies a Protobuf initializer instead of a complete message. Its inferred input allows omitted fields and does not require `$typeName`; its output is a complete, validated Protobuf message.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import {
|
|
63
|
+
createStandardSchemaInit,
|
|
64
|
+
type StandardSchemaV1,
|
|
65
|
+
} from "@protovalidate-extensions/protovalidate-lingui";
|
|
66
|
+
import { UserSchema } from "./gen/user_pb.js";
|
|
67
|
+
|
|
68
|
+
const schema = createStandardSchemaInit(UserSchema, { failFast: true });
|
|
69
|
+
type Input = StandardSchemaV1.InferInput<typeof schema>;
|
|
70
|
+
type Output = StandardSchemaV1.InferOutput<typeof schema>;
|
|
71
|
+
|
|
72
|
+
const input: Input = { displayName: "Alice" };
|
|
73
|
+
const result = await schema["~standard"].validate(input);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Both factories return the same issue IDs and paths and accept the same validator and message override options.
|
|
77
|
+
|
|
78
|
+
## Override messages with generated types
|
|
79
|
+
|
|
80
|
+
Run `protoc-gen-protovalidate-lingui` alongside your Protobuf-ES plugin in `buf.gen.yaml`:
|
|
81
|
+
|
|
82
|
+
```yaml
|
|
83
|
+
plugins:
|
|
84
|
+
# Keep your existing Protobuf-ES plugin here.
|
|
85
|
+
- local: [cargo, run, --quiet, --package, protoc-gen-protovalidate-lingui, --]
|
|
86
|
+
out: generated
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The Cargo command above runs from this repository. Consumers who install the binary can use `local: protoc-gen-protovalidate-lingui` instead.
|
|
90
|
+
|
|
91
|
+
For each source schema, the plugin generates a `_lingui.ts` module containing custom CEL message descriptors and an override type for each declared message. For example, `location/v1/location.proto` produces `location/v1/location_lingui.ts` with `LocationMessages`:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { msg } from "@lingui/core/macro";
|
|
95
|
+
import type { LocationMessages } from "./generated/location/v1/location_lingui.js";
|
|
96
|
+
|
|
97
|
+
const messages = {
|
|
98
|
+
latitude: {
|
|
99
|
+
"float.gte_lte": msg`Latitude must be between -90 and 90 degrees.`,
|
|
100
|
+
},
|
|
101
|
+
longitude: {
|
|
102
|
+
"float.gte_lte": msg`Longitude must be between -180 and 180 degrees.`,
|
|
103
|
+
},
|
|
104
|
+
$message: {
|
|
105
|
+
"location.coordinates": msg`Please check the coordinates.`,
|
|
106
|
+
},
|
|
107
|
+
} satisfies LocationMessages;
|
|
108
|
+
|
|
109
|
+
const schema = createStandardSchemaInit(LocationSchema, { messages });
|
|
110
|
+
// createStandardSchema accepts the same options.
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Use `satisfies` (or annotate the variable with the generated type) to reject unknown fields, incorrect rule IDs, and plain strings where a Lingui descriptor is expected. The adapter alone cannot infer validation annotations from Protobuf-ES's message types. `msg` generates the translation ID automatically; the rule keys remain the IDs reported by Protovalidate.
|
|
114
|
+
|
|
115
|
+
The types use JavaScript field names and include declared custom CEL IDs, including rules that produce dynamic messages. Built-in keys come from the predefined rule annotations in the compiled schema, plus native required, enum, and Any rules. Numeric and timestamp/duration range bounds are combined into their reported rule IDs, including reversed ranges. A predefined annotation can declare several conditional IDs (for example, `string.email` and `string.email_empty`); these are both valid override keys. Regenerate after editing validation annotations.
|
|
116
|
+
|
|
117
|
+
For nested messages, put the child's overrides inside its field's `$fields` property. Recursive message types are supported:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const messages = {
|
|
121
|
+
address: {
|
|
122
|
+
required: msg`Please provide an address.`,
|
|
123
|
+
$fields: {
|
|
124
|
+
city: { "string.min_len": msg`Please enter a city name.` },
|
|
125
|
+
$message: { "address.valid": msg`Please check the address.` },
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
} satisfies CustomerMessages;
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
List item and map key/value rules share their parent field's rule mapping; nested message elements use `$fields`. Overrides apply across all indices/keys. Oneof member rules use the member's JavaScript name, while a required oneof uses the group name. Reserved property names (`constructor`, `toString`, `toJSON`, and `valueOf`) use a `$` suffix in override keys, including oneof members. Well-known types use their field-level rule mappings rather than `$fields`.
|
|
132
|
+
|
|
133
|
+
An override changes only the returned `issue.message` to the descriptor's ID. It preserves validation behavior and issue paths. Unmapped violations keep their original IDs. Translation still happens at render time with `i18n._(issue.message)`, so locale changes do not require revalidation. Use static messages: descriptor interpolation values are not carried in Standard Schema issues. Adapter errors continue using the shared `protovalidate.*` IDs.
|
|
134
|
+
|
|
135
|
+
## Message IDs
|
|
136
|
+
|
|
137
|
+
For validation violations without overrides, `issue.message` is exactly `violation.ruleId`: for example, `required`, `string.min_len`, or your custom CEL rule ID. It never contains the rule's English error text.
|
|
138
|
+
|
|
139
|
+
Adapter errors also use stable IDs:
|
|
140
|
+
|
|
141
|
+
| Condition | Message ID |
|
|
142
|
+
| ----------------------------------------- | --------------------------------- |
|
|
143
|
+
| Input is null or is not an object | `protovalidate.expected_object` |
|
|
144
|
+
| A validation rule cannot be compiled | `protovalidate.compilation_error` |
|
|
145
|
+
| A validation rule fails during evaluation | `protovalidate.runtime_error` |
|
|
146
|
+
|
|
147
|
+
Define translations for these IDs and the rule IDs used by your schemas. Dynamic IDs are not automatically extracted by Lingui; add catalog entries explicitly or declare static messages with matching explicit IDs in your application's extraction sources. Load and compile the catalogs with your normal Lingui workflow.
|
|
148
|
+
|
|
149
|
+
Only the ID and field path are returned. English fallback text, rule parameters, and interpolation values are not included. Use translations that do not need those values, such as “Please enter a longer value” for `string.min_len`.
|
|
150
|
+
|
|
151
|
+
## Register messages for extraction
|
|
152
|
+
|
|
153
|
+
The package provides the three adapter error descriptors through a dedicated entry point:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { adapterMessages } from "@protovalidate-extensions/protovalidate-lingui/messages";
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
These are plain descriptors marked with `/* i18n */` for extraction. They require no macro compilation and have no runtime imports. The main package entry point does not import them or depend on Lingui. If you need an English fallback before catalogs are loaded, find the descriptor by `issue.message` and pass it to `i18n._(descriptor)`.
|
|
160
|
+
|
|
161
|
+
Include the published messages file explicitly in your application's Lingui catalog sources, along with your own built-in rule messages and plugin-generated custom CEL messages:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
import { fileURLToPath } from "node:url";
|
|
165
|
+
|
|
166
|
+
const adapterMessagesPath = fileURLToPath(
|
|
167
|
+
import.meta.resolve("@protovalidate-extensions/protovalidate-lingui/messages"),
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
// Within your existing lingui.config.ts configuration:
|
|
171
|
+
catalogs: [
|
|
172
|
+
{
|
|
173
|
+
path: "<rootDir>/src/locales/{locale}/messages",
|
|
174
|
+
include: ["<rootDir>/src", "<rootDir>/generated", adapterMessagesPath],
|
|
175
|
+
// Override the default node_modules exclusion for the explicitly included file.
|
|
176
|
+
exclude: [],
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Importing `adapterMessages` alone or calling `i18n._(issue.message)` does not discover dynamic IDs. The extractor must scan the file containing the declarations. Keep the `include` paths narrow when overriding exclusions.
|
|
182
|
+
|
|
183
|
+
Built-in validation rules are schema-specific and are not included in `adapterMessages`. Declare their messages in your application, for example:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
// src/i18n/validation-messages.ts
|
|
187
|
+
import { msg } from "@lingui/core/macro";
|
|
188
|
+
|
|
189
|
+
export const validationMessages = [
|
|
190
|
+
msg({ id: "required", message: "This field is required." }),
|
|
191
|
+
msg({ id: "string.min_len", message: "Please enter a longer value." }),
|
|
192
|
+
];
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The Protobuf plugin generates descriptors for custom CEL rules with static messages. Add declarations for any other rule IDs your schemas can return. Messages declared using `msg` require your application's normal Lingui macro setup.
|
|
196
|
+
|
|
197
|
+
Then extract, translate, compile, and load the catalogs with your normal Lingui workflow:
|
|
198
|
+
|
|
199
|
+
```sh
|
|
200
|
+
pnpm exec lingui extract
|
|
201
|
+
# Add translations to the extracted catalogs before compiling.
|
|
202
|
+
pnpm exec lingui compile
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
After loading the compiled catalog for the active locale, translate issues with `i18n._(issue.message)`. You do not need to merge the exported message collections. See Lingui's [message extraction](https://lingui.dev/guides/message-extraction) and [configuration](https://lingui.dev/ref/conf) documentation.
|
|
206
|
+
|
|
207
|
+
## Options and types
|
|
208
|
+
|
|
209
|
+
Both `createStandardSchema` and `createStandardSchemaInit` accept `SchemaOptions`, which extends Protovalidate `ValidatorOptions` with `messages`. Validator options include `failFast`, `registry`, and `regexMatch`. Keep schema instances around to reuse the underlying validator cache. There is no `i18n` instance or translation callback in the adapter options.
|
|
210
|
+
|
|
211
|
+
`createStandardSchema` infers `MessageShape` input; `createStandardSchemaInit` infers `MessageInitShape` input. Both infer `MessageValidType` output, including stronger required-field types when generated with Protobuf-ES valid types. The package exports `StandardSchemaV1`, `ValidatorOptions`, `SchemaOptions`, and `MessageOverrides` types. The adapters supply Protobuf defaults during construction; they do not parse Protobuf JSON. Malformed message construction can throw.
|
|
212
|
+
|
|
213
|
+
Issue paths use JavaScript field names, numeric list indices, map keys, and `[oneofName, "value"]` for oneof member fields. Message-level issues omit the path.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type DescMessage, type MessageInitShape, type MessageShape, type MessageValidType } from "@bufbuild/protobuf";
|
|
2
|
+
import { type ValidatorOptions } from "@bufbuild/protovalidate";
|
|
3
|
+
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
|
+
export type { ValidatorOptions } from "@bufbuild/protovalidate";
|
|
5
|
+
export type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
6
|
+
/** Use the plugin-generated message type with `satisfies` for exact rule checks. */
|
|
7
|
+
export type MessageOverrides = Readonly<Record<string, Readonly<Record<string, unknown>> | undefined>>;
|
|
8
|
+
export interface SchemaOptions extends ValidatorOptions {
|
|
9
|
+
messages?: MessageOverrides;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Create a Standard Schema validator whose issue messages are Lingui IDs.
|
|
13
|
+
*
|
|
14
|
+
* @param messageDesc - The Protobuf message descriptor
|
|
15
|
+
* @param options - Optional validator configuration
|
|
16
|
+
* @returns A StandardSchemaV1 compliant validator
|
|
17
|
+
*/
|
|
18
|
+
export declare function createStandardSchema<Desc extends DescMessage>(messageDesc: Desc, options?: SchemaOptions): StandardSchemaV1<MessageShape<Desc>, MessageValidType<Desc>>;
|
|
19
|
+
/**
|
|
20
|
+
* Create a Standard Schema compliant validator for a Protobuf message type
|
|
21
|
+
* that accepts the message's init shape as input.
|
|
22
|
+
*
|
|
23
|
+
* @param messageDesc - The Protobuf message descriptor
|
|
24
|
+
* @param options - Optional validator configuration
|
|
25
|
+
* @returns A StandardSchemaV1 compliant validator
|
|
26
|
+
*/
|
|
27
|
+
export declare function createStandardSchemaInit<Desc extends DescMessage>(messageDesc: Desc, options?: SchemaOptions): StandardSchemaV1<MessageInitShape<Desc>, MessageValidType<Desc>>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { create, } from "@bufbuild/protobuf";
|
|
2
|
+
import { createValidator, CompilationError, } from "@bufbuild/protovalidate";
|
|
3
|
+
function ownObject(value, key) {
|
|
4
|
+
if (typeof value !== "object" ||
|
|
5
|
+
value === null ||
|
|
6
|
+
!Object.hasOwn(value, key)) {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
const child = value[key];
|
|
10
|
+
return typeof child === "object" && child !== null
|
|
11
|
+
? child
|
|
12
|
+
: undefined;
|
|
13
|
+
}
|
|
14
|
+
function overrideId(violation, messages) {
|
|
15
|
+
let scope = messages;
|
|
16
|
+
let field;
|
|
17
|
+
let first = true;
|
|
18
|
+
for (const segment of violation.field) {
|
|
19
|
+
if (segment.kind !== "field" && segment.kind !== "oneof")
|
|
20
|
+
continue;
|
|
21
|
+
if (!first)
|
|
22
|
+
scope = ownObject(field, "$fields");
|
|
23
|
+
first = false;
|
|
24
|
+
// Escape reserved properties even for oneof members, where Protobuf-ES
|
|
25
|
+
// keeps the unescaped name. Optional `constructor` keys conflict with
|
|
26
|
+
// Object.constructor in TypeScript otherwise.
|
|
27
|
+
const name = ["constructor", "toString", "toJSON", "valueOf"].includes(segment.localName)
|
|
28
|
+
? `${segment.localName}$`
|
|
29
|
+
: segment.localName;
|
|
30
|
+
field = ownObject(scope, name);
|
|
31
|
+
}
|
|
32
|
+
const descriptor = violation.field.length === 0
|
|
33
|
+
? ownObject(ownObject(scope, "$message"), violation.ruleId)
|
|
34
|
+
: (ownObject(field, violation.ruleId) ??
|
|
35
|
+
ownObject(ownObject(ownObject(field, "$fields"), "$message"), violation.ruleId));
|
|
36
|
+
return typeof descriptor?.id === "string" && descriptor.id.length > 0
|
|
37
|
+
? descriptor.id
|
|
38
|
+
: violation.ruleId;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Convert a Violation to a StandardSchemaV1.Issue.
|
|
42
|
+
*/
|
|
43
|
+
function violationToIssue(violation, messages) {
|
|
44
|
+
const path = [];
|
|
45
|
+
for (const segment of violation.field) {
|
|
46
|
+
switch (segment.kind) {
|
|
47
|
+
case "field":
|
|
48
|
+
if (segment.oneof !== undefined) {
|
|
49
|
+
path.push(segment.oneof.localName);
|
|
50
|
+
path.push("value");
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
path.push(segment.localName);
|
|
54
|
+
}
|
|
55
|
+
continue;
|
|
56
|
+
case "oneof":
|
|
57
|
+
path.push(segment.localName);
|
|
58
|
+
continue;
|
|
59
|
+
case "list_sub":
|
|
60
|
+
path.push(segment.index);
|
|
61
|
+
continue;
|
|
62
|
+
case "map_sub":
|
|
63
|
+
const key = segment.key;
|
|
64
|
+
if (typeof key === "string" || typeof key === "number") {
|
|
65
|
+
path.push(key);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
path.push(String(key));
|
|
69
|
+
}
|
|
70
|
+
continue;
|
|
71
|
+
case "extension":
|
|
72
|
+
// Extensions are represented as field names with brackets
|
|
73
|
+
path.push(`[${segment.typeName}]`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (path.length > 0) {
|
|
77
|
+
return {
|
|
78
|
+
message: overrideId(violation, messages),
|
|
79
|
+
path: path,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
message: overrideId(violation, messages),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Create a Standard Schema validator whose issue messages are Lingui IDs.
|
|
88
|
+
*
|
|
89
|
+
* @param messageDesc - The Protobuf message descriptor
|
|
90
|
+
* @param options - Optional validator configuration
|
|
91
|
+
* @returns A StandardSchemaV1 compliant validator
|
|
92
|
+
*/
|
|
93
|
+
export function createStandardSchema(messageDesc, options) {
|
|
94
|
+
const { messages, ...validatorOptions } = options ?? {};
|
|
95
|
+
const validator = createValidator(validatorOptions);
|
|
96
|
+
return {
|
|
97
|
+
"~standard": {
|
|
98
|
+
version: 1,
|
|
99
|
+
vendor: "protovalidate-es",
|
|
100
|
+
validate: (value) => {
|
|
101
|
+
// Type guard to ensure value is an object
|
|
102
|
+
if (typeof value !== "object" || value === null) {
|
|
103
|
+
return {
|
|
104
|
+
issues: [
|
|
105
|
+
{
|
|
106
|
+
message: "protovalidate.expected_object",
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const result = validator.validate(messageDesc, create(messageDesc, value));
|
|
112
|
+
switch (result.kind) {
|
|
113
|
+
case "valid":
|
|
114
|
+
return {
|
|
115
|
+
value: result.message,
|
|
116
|
+
};
|
|
117
|
+
case "invalid":
|
|
118
|
+
return {
|
|
119
|
+
issues: result.violations.map((violation) => violationToIssue(violation, messages)),
|
|
120
|
+
};
|
|
121
|
+
case "error":
|
|
122
|
+
return {
|
|
123
|
+
issues: [
|
|
124
|
+
{
|
|
125
|
+
message: result.error instanceof CompilationError
|
|
126
|
+
? "protovalidate.compilation_error"
|
|
127
|
+
: "protovalidate.runtime_error",
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Create a Standard Schema compliant validator for a Protobuf message type
|
|
138
|
+
* that accepts the message's init shape as input.
|
|
139
|
+
*
|
|
140
|
+
* @param messageDesc - The Protobuf message descriptor
|
|
141
|
+
* @param options - Optional validator configuration
|
|
142
|
+
* @returns A StandardSchemaV1 compliant validator
|
|
143
|
+
*/
|
|
144
|
+
export function createStandardSchemaInit(messageDesc, options) {
|
|
145
|
+
return createStandardSchema(messageDesc, options);
|
|
146
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Extractable default messages for errors produced by the schema adapters. */
|
|
2
|
+
export declare const adapterMessages: readonly [{
|
|
3
|
+
readonly id: "protovalidate.expected_object";
|
|
4
|
+
readonly message: "Please provide a valid value.";
|
|
5
|
+
}, {
|
|
6
|
+
readonly id: "protovalidate.compilation_error";
|
|
7
|
+
readonly message: "Validation is unavailable. Please try again later.";
|
|
8
|
+
}, {
|
|
9
|
+
readonly id: "protovalidate.runtime_error";
|
|
10
|
+
readonly message: "We couldn't validate this value. Please try again.";
|
|
11
|
+
}];
|
package/dist/messages.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Extractable default messages for errors produced by the schema adapters. */
|
|
2
|
+
export const adapterMessages = [
|
|
3
|
+
/* i18n */ {
|
|
4
|
+
id: "protovalidate.expected_object",
|
|
5
|
+
message: "Please provide a valid value.",
|
|
6
|
+
},
|
|
7
|
+
/* i18n */ {
|
|
8
|
+
id: "protovalidate.compilation_error",
|
|
9
|
+
message: "Validation is unavailable. Please try again later.",
|
|
10
|
+
},
|
|
11
|
+
/* i18n */ {
|
|
12
|
+
id: "protovalidate.runtime_error",
|
|
13
|
+
message: "We couldn't validate this value. Please try again.",
|
|
14
|
+
},
|
|
15
|
+
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protovalidate-extensions/protovalidate-lingui",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Standard Schema validation with Lingui message IDs for Protovalidate.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/comradesharf/protovalidate-extensions.git",
|
|
8
|
+
"directory": "packages/protovalidate-lingui"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/comradesharf/protovalidate-extensions/tree/main/packages/protovalidate-lingui#readme",
|
|
11
|
+
"bugs": "https://github.com/comradesharf/protovalidate-extensions/issues",
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public",
|
|
14
|
+
"registry": "https://registry.npmjs.org/"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsc -p tsconfig.json",
|
|
18
|
+
"typecheck": "tsc -p tsconfig.test.json",
|
|
19
|
+
"test": "bun test",
|
|
20
|
+
"prepack": "pnpm run build"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"protovalidate",
|
|
24
|
+
"extensions"
|
|
25
|
+
],
|
|
26
|
+
"license": "ISC",
|
|
27
|
+
"type": "module",
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@bufbuild/protobuf": "^2.8.0",
|
|
30
|
+
"@bufbuild/protovalidate": "^1.3.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@bufbuild/protobuf": "^2.17.0",
|
|
34
|
+
"@bufbuild/protovalidate": "^1.3.0",
|
|
35
|
+
"@lingui/core": "^6.12.0"
|
|
36
|
+
},
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"main": "./dist/index.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"types": "./dist/index.d.ts",
|
|
43
|
+
"import": "./dist/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./messages": {
|
|
46
|
+
"types": "./dist/messages.d.ts",
|
|
47
|
+
"import": "./dist/messages.js"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"files": [
|
|
51
|
+
"dist",
|
|
52
|
+
"skills",
|
|
53
|
+
"README.md"
|
|
54
|
+
],
|
|
55
|
+
"dependencies": {
|
|
56
|
+
"@standard-schema/spec": "^1.1.0"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: protovalidate-lingui
|
|
3
|
+
description: Integrate @protovalidate-extensions/protovalidate-lingui into TypeScript applications and Standard Schema forms, including Lingui extraction, translation, and plugin-generated message overrides. Use when installing, using, or troubleshooting this package.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Protovalidate Lingui
|
|
7
|
+
|
|
8
|
+
Use the package as a Standard Schema V1 adapter for Protobuf-ES descriptors. Validation returns translation IDs; the UI translates them when rendering. Keep the application's existing package manager, form library, code generation, and Lingui setup.
|
|
9
|
+
|
|
10
|
+
## Match the installed API
|
|
11
|
+
|
|
12
|
+
Inspect the installed package's version, exports, declarations, and README before changing an integration. This skill ships with the package, but generated code and application dependencies can be from different versions. Do not assume a newer source checkout's API is present in a published version.
|
|
13
|
+
|
|
14
|
+
The npm package is `@protovalidate-extensions/protovalidate-lingui`, not the unscoped name. Install it with `@bufbuild/protobuf` and `@bufbuild/protovalidate` using the application's package manager. Add `@lingui/core` when the UI translates messages; choose compatible versions from the package's peer declarations and existing application setup.
|
|
15
|
+
|
|
16
|
+
Use generated Protobuf-ES `DescMessage` values from schemas containing `buf.validate` annotations. The adapter does not generate descriptors, add validation rules, or accept Prost/Buffa message objects. Its main runtime entry point does not require Lingui.
|
|
17
|
+
|
|
18
|
+
## Choose the adapter
|
|
19
|
+
|
|
20
|
+
- `createStandardSchema(MessageSchema, options?)`: the inferred input is a complete Protobuf `MessageShape`, including `$typeName`.
|
|
21
|
+
- `createStandardSchemaInit(MessageSchema, options?)`: the inferred input is `MessageInitShape`; prefer this for plain form values without `$typeName` and with omitted fields.
|
|
22
|
+
|
|
23
|
+
Both return a constructed, validated `MessageValidType` on success, supply Protobuf defaults, and preserve the same issue paths and IDs. Keep schema instances around to reuse validator caches. These adapters construct Protobuf messages; they do not parse Protobuf JSON, and malformed construction can throw.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createStandardSchemaInit } from "@protovalidate-extensions/protovalidate-lingui";
|
|
27
|
+
import { UserSchema } from "./generated/user_pb.js";
|
|
28
|
+
|
|
29
|
+
const schema = createStandardSchemaInit(UserSchema, { failFast: true });
|
|
30
|
+
const result = await schema["~standard"].validate({ displayName: "A" });
|
|
31
|
+
|
|
32
|
+
if (result.issues) {
|
|
33
|
+
// Use the application's active Lingui instance in the rendering layer.
|
|
34
|
+
const errors = result.issues.map((issue) => ({
|
|
35
|
+
path: issue.path,
|
|
36
|
+
message: i18n._(issue.message),
|
|
37
|
+
}));
|
|
38
|
+
} else {
|
|
39
|
+
const message = result.value;
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Connect `schema` directly to the existing Standard Schema consumer. For input/output types, use the exported `StandardSchemaV1.InferInput<typeof schema>` and `InferOutput` types.
|
|
44
|
+
|
|
45
|
+
`SchemaOptions` extends Protovalidate `ValidatorOptions` with `messages`; options such as `failFast`, `registry`, and `regexMatch` pass through. Do not invent an `i18n` option or translation callback.
|
|
46
|
+
|
|
47
|
+
## Keep translations reactive
|
|
48
|
+
|
|
49
|
+
Translate `issue.message` at render time with the active Lingui instance. In React, obtain it through `useLingui()` so locale changes update existing errors without revalidation. Do not translate when creating the schema or cache translated error strings.
|
|
50
|
+
|
|
51
|
+
Unmapped validation issues use `violation.ruleId`. Overrides return the descriptor's ID. Issues carry no English fallback, bound values, or interpolation values. Use static messages for overrides; do not promise interpolation support.
|
|
52
|
+
|
|
53
|
+
For field-specific wording or automatically generated translation IDs, use `msg` descriptors and the plugin-generated override type. Read [references/message-overrides.md](references/message-overrides.md) when adding overrides or configuring generation. `msg`/`defineMessage` returns a descriptor; `t` returns a translated string and is not an override descriptor.
|
|
54
|
+
|
|
55
|
+
Issue paths use JavaScript field names, numeric list indices, and map keys. Oneof member paths use `[oneofName, "value"]`; message-level issues omit the path. Preserve these paths when wiring the form UI.
|
|
56
|
+
|
|
57
|
+
## Supply extractable catalogs
|
|
58
|
+
|
|
59
|
+
The package owns three adapter error IDs:
|
|
60
|
+
|
|
61
|
+
- `protovalidate.expected_object`
|
|
62
|
+
- `protovalidate.compilation_error`
|
|
63
|
+
- `protovalidate.runtime_error`
|
|
64
|
+
|
|
65
|
+
Their static descriptors are exported as `adapterMessages` from `@protovalidate-extensions/protovalidate-lingui/messages`. This separate entry point contains plain descriptors marked `/* i18n */`, with no runtime imports or macro compilation requirement.
|
|
66
|
+
|
|
67
|
+
Include the actual published messages file in Lingui extraction. An import alone and `i18n._(issue.message)` cannot discover dynamic IDs. In an ESM Lingui configuration, resolve the installed export:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
import { fileURLToPath } from "node:url";
|
|
71
|
+
|
|
72
|
+
const adapterMessagesPath = fileURLToPath(
|
|
73
|
+
import.meta
|
|
74
|
+
.resolve("@protovalidate-extensions/protovalidate-lingui/messages"),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
// Merge into the application's existing catalog configuration.
|
|
78
|
+
catalogs: [
|
|
79
|
+
{
|
|
80
|
+
path: "<rootDir>/src/locales/{locale}/messages",
|
|
81
|
+
include: ["<rootDir>/src", "<rootDir>/generated", adapterMessagesPath],
|
|
82
|
+
exclude: [],
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Lingui normally excludes `node_modules`. Override exclusions only with narrowly scoped include paths so the explicitly included descriptor file is scanned. Adapt the configuration to the application's module system and actual generated directory.
|
|
88
|
+
|
|
89
|
+
The shared adapter descriptors do not cover built-in validation rules. For unmapped rule IDs, declare static messages with matching explicit IDs in application sources, for example `msg({ id: "string.min_len", message: "Please enter a longer value." })`. Alternatively, use a generated typed override with `msg` and no explicit ID. The Protobuf plugin supplies static descriptors for custom CEL messages; runtime-only CEL text is not extractable.
|
|
90
|
+
|
|
91
|
+
Run the application's extraction, translation, compilation, and catalog loading workflow. Files containing `msg` need the application's Lingui macro compiler. Do not import the plugin's macro-bearing module at runtime merely to access its types; use `import type`.
|
|
92
|
+
|
|
93
|
+
## Verify the integration
|
|
94
|
+
|
|
95
|
+
Run appropriate application typechecks and tests. Exercise valid input, an actual invalid built-in or custom rule, and null input. Check the reported IDs against the loaded catalog and check that the field paths reach the right form controls. When overrides change, verify that switching locale re-renders the same stored issues correctly without validating again.
|
|
96
|
+
|
|
97
|
+
If errors show IDs, first inspect catalog inclusion, extraction exclusions, compiled catalog loading, and the active locale. A missing `messages` export or unknown `messages` option can indicate an older installed package. Incorrect override keys can indicate stale generated types or a combined rule ID such as `float.gte_lte`.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Generated message overrides
|
|
2
|
+
|
|
3
|
+
Use the companion Rust plugin `protoc-gen-protovalidate-lingui` when precise override keys are needed. The npm adapter does not bundle this executable. Check the consumer's existing generation setup and installed binary before adding tooling.
|
|
4
|
+
|
|
5
|
+
## Generate from the same schemas
|
|
6
|
+
|
|
7
|
+
Append the local plugin to the existing `buf.gen.yaml`, preserving the Protobuf-ES plugin and its options:
|
|
8
|
+
|
|
9
|
+
```yaml
|
|
10
|
+
version: v2
|
|
11
|
+
plugins:
|
|
12
|
+
# Existing Protobuf-ES plugin remains here.
|
|
13
|
+
- local: protoc-gen-protovalidate-lingui
|
|
14
|
+
out: generated
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Inside the protovalidate-extensions Rust workspace, the local command can instead be `[cargo, run, --quiet, --package, protoc-gen-protovalidate-lingui, --]`. Do not use that workspace-specific command in an unrelated consumer repository. The plugin has no configuration parameters. Its output follows source-relative paths: `location/v1/location.proto` becomes `location/v1/location_lingui.ts`.
|
|
18
|
+
|
|
19
|
+
Regenerate Protobuf-ES bindings and override types from the same proto revision. The companion plugin implements the Protoc request/response protocol, so the source schemas can also be used by other generators; its JavaScript override types target this adapter and Protobuf-ES field names.
|
|
20
|
+
|
|
21
|
+
## Configure a typed override
|
|
22
|
+
|
|
23
|
+
Use the generated alias with `satisfies`, or annotate the override variable explicitly. The adapter's general `messages` option alone cannot infer rule annotations from Protobuf-ES types.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { msg } from "@lingui/core/macro";
|
|
27
|
+
import { createStandardSchemaInit } from "@protovalidate-extensions/protovalidate-lingui";
|
|
28
|
+
import { LocationSchema } from "./generated/location/v1/location_pb.js";
|
|
29
|
+
import type { LocationMessages } from "./generated/location/v1/location_lingui.js";
|
|
30
|
+
|
|
31
|
+
const messages = {
|
|
32
|
+
latitude: {
|
|
33
|
+
"float.gte_lte": msg`Latitude must be between -90 and 90 degrees.`,
|
|
34
|
+
},
|
|
35
|
+
$message: {
|
|
36
|
+
"location.coordinates": msg`Please check the coordinates.`,
|
|
37
|
+
},
|
|
38
|
+
} satisfies LocationMessages;
|
|
39
|
+
|
|
40
|
+
const schema = createStandardSchemaInit(LocationSchema, { messages });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Adapt field names and rule keys to the generated type rather than assuming the example's rules exist. `createStandardSchema` accepts the same configuration. `msg` and `defineMessage` automatically generate translation IDs when no explicit ID is supplied. Rule keys such as `float.gte_lte` are Protovalidate IDs; the adapter replaces the returned issue ID with the descriptor's translation ID. Invalid/missing descriptor IDs fall back to the original rule ID.
|
|
44
|
+
|
|
45
|
+
Combined bounds can report one combined ID instead of separate `gte` and `lte` IDs. The plugin accounts for numeric and timestamp/duration ranges, including reversed ranges, without losing 64-bit integer precision. Built-in IDs come from declared predefined rule annotations plus native rules; a predefined annotation can expose several conditional IDs, such as `string.email` and `string.email_empty`.
|
|
46
|
+
|
|
47
|
+
Custom CEL IDs belong to their declaring fields or `$message`. The plugin emits extractable descriptors for static custom CEL messages and exposes custom IDs in override types when CEL produces runtime-only text. It generates types even for messages whose rules have no static catalog text. Nested message aliases join proto nesting names with `_`; `ValidationMessagesByType` indexes definitions by fully qualified Protobuf message name.
|
|
48
|
+
|
|
49
|
+
## Nested and collection rules
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
const messages = {
|
|
53
|
+
address: {
|
|
54
|
+
required: msg`Please provide an address.`,
|
|
55
|
+
$fields: {
|
|
56
|
+
city: { "string.min_len": msg`Please enter a city name.` },
|
|
57
|
+
$message: { "address.valid": msg`Please check the address.` },
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
} satisfies CustomerMessages;
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
- `$message` targets message-level rules at the current scope.
|
|
64
|
+
- `$fields` enters a nested message's overrides. Recursive message types are supported.
|
|
65
|
+
- List item and map key/value rule IDs share the containing field's mapping. The override applies to all indices/keys. Nested message elements use `$fields`.
|
|
66
|
+
- Oneof members use their member field names, even though their returned issue paths point through the group and `value`. Required-oneof rules use the group name.
|
|
67
|
+
- Reserved properties `constructor`, `toString`, `toJSON`, and `valueOf` have a `$` suffix in override keys, including oneof members.
|
|
68
|
+
- Well-known types use field-level mappings instead of `$fields`.
|
|
69
|
+
|
|
70
|
+
An override changes only the translation ID, not validation behavior or paths. Unmapped rules retain their original IDs. `messages` does not override the adapter's `protovalidate.*` errors; include the package's shared descriptors in extraction for those.
|
|
71
|
+
|
|
72
|
+
Use static descriptors. Standard Schema issues do not carry descriptor interpolation values or rule parameters. Keep translation in the rendering layer, and keep override declarations and generated custom messages within the application's extraction sources.
|